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): stop markdown conversion destroying cards inside blockquotes (#69027)

Marius Andrab50f15078345
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
index 5e01aa50edb1..ecc288a89ae8 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
@@ -583,6 +583,29 @@ continued line
expect(serializeMarkdownNotebook(document)).toEqual(markdown)
})
+ it('breaks component tags out of blockquotes instead of degrading them to quote text', () => {
+ const markdown = [
+ '> Quoted intro',
+ '> <Query query={{"kind":"SavedInsightNode","shortId":"abc123"}} />',
+ '> > <Python code="print(1)" />',
+ '> Quoted outro',
+ ].join('\n')
+ const document = parseMarkdownNotebook(markdown)
+
+ expect(document.errors).toEqual([])
+ expect(document.nodes.map((node) => node.type)).toEqual(['blockquote', 'component', 'component', 'blockquote'])
+ expect(document.nodes[1]).toMatchObject({
+ tagName: 'Query',
+ props: { query: { kind: 'SavedInsightNode', shortId: 'abc123' } },
+ })
+ expect(document.nodes[2]).toMatchObject({ tagName: 'Python', props: { code: 'print(1)' } })
+
+ // The rescued components stay standalone and stable across further saves
+ const serialized = serializeMarkdownNotebook(document)
+ expect(serialized).not.toContain('\\<')
+ expect(serializeMarkdownNotebook(parseMarkdownNotebook(serialized))).toEqual(serialized)
+ })
+
it('round-trips component string props with reversible escaping', () => {
const props = {
src: 'https://posthog.com/embed?one=1&two=2',
diff --git a/frontend/src/lib/components/MarkdownNotebook/markdown.ts b/frontend/src/lib/components/MarkdownNotebook/markdown.ts
index 2ecab7b4ebfa..540c4e9325ce 100644
--- a/frontend/src/lib/components/MarkdownNotebook/markdown.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/markdown.ts
@@ -608,13 +608,17 @@ function parseBlock(lines: string[], lineIndex: number): BlockParseResult {
if (isListLine(stripBlockquoteMarker(line))) {
return parseBlockquotedListBlock(lines, lineIndex)
}
+ if (COMPONENT_START_REGEX.test(stripAllBlockquoteMarkers(line))) {
+ return parseBlockquotedComponentBlock(lines, lineIndex)
+ }
const quoteLines: string[] = []
let nextLineIndex = lineIndex
while (
nextLineIndex < lines.length &&
lines[nextLineIndex].trim().startsWith('>') &&
- !isListLine(stripBlockquoteMarker(lines[nextLineIndex]))
+ !isListLine(stripBlockquoteMarker(lines[nextLineIndex])) &&
+ !COMPONENT_START_REGEX.test(stripAllBlockquoteMarkers(lines[nextLineIndex]))
) {
quoteLines.push(stripBlockquoteMarker(lines[nextLineIndex]))
nextLineIndex += 1
@@ -676,6 +680,34 @@ function stripBlockquoteMarker(line: string): string {
return line.trim().replace(/^>\s?/, '')
}
+function stripAllBlockquoteMarkers(line: string): string {
+ let stripped = stripBlockquoteMarker(line)
+ while (stripped.trim().startsWith('>')) {
+ stripped = stripBlockquoteMarker(stripped)
+ }
+ return stripped
+}
+
+// Component tags have no blockquote representation in this model, so a quoted tag line (as
+// produced by older legacy-notebook conversions, e.g. `> <Query … />`) is parsed as the
+// component itself, broken out of the quote. Treating it as quote text would degrade the tag
+// to escaped literal text on the next save, permanently destroying the node.
+function parseBlockquotedComponentBlock(lines: string[], lineIndex: number): BlockParseResult {
+ const strippedLines: string[] = []
+ let end = lineIndex
+ while (end < lines.length && lines[end].trim().startsWith('>')) {
+ strippedLines.push(stripAllBlockquoteMarkers(lines[end]))
+ end += 1
+ }
+
+ const result = parseComponentBlock(strippedLines, 0)
+ return {
+ ...result,
+ nextLineIndex: lineIndex + result.nextLineIndex,
+ error: result.error ? { ...result.error, line: lineIndex + result.error.line } : undefined,
+ }
+}
+
function parseBlockquotedListBlock(lines: string[], lineIndex: number): BlockParseResult {
const listLines: string[] = []
let nextLineIndex = lineIndex
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts
index 6d71b90cfb80..ec778ea1970c 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts
@@ -529,6 +529,82 @@ after`)
expect(parsed.nodes.map((node) => node.type)).toEqual(['heading', 'list', 'component', 'blockquote'])
})
+ it('splits embedded cards and headings out of blockquotes instead of quoting their tags', () => {
+ const content: JSONContent = {
+ type: 'doc',
+ content: [
+ {
+ type: 'blockquote',
+ content: [
+ { type: 'paragraph', content: [{ type: 'text', text: 'Quoted context' }] },
+ {
+ type: NotebookNodeType.Query,
+ attrs: {
+ query: { kind: NodeKind.SavedInsightNode, shortId: 'abc123' },
+ hideFilters: true,
+ },
+ },
+ {
+ type: 'blockquote',
+ content: [
+ {
+ type: 'heading',
+ attrs: { level: 2 },
+ content: [{ type: 'text', text: 'Where to improve' }],
+ },
+ { type: NotebookNodeType.Python, attrs: { code: 'print(1)', hideFilters: true } },
+ ],
+ },
+ ],
+ },
+ ],
+ }
+
+ const markdown = convertNotebookContentToMarkdown(content)
+
+ expect(markdown).toContain('> Quoted context')
+ expect(markdown).toContain('\n\n<Query ')
+ expect(markdown).toContain('\n\n## Where to improve')
+ expect(markdown).toContain('\n\n<Python ')
+ expect(markdown).not.toContain('> <')
+
+ const parsed = parseMarkdownNotebook(markdown)
+ expect(parsed.errors).toEqual([])
+ expect(parsed.nodes.flatMap((node) => (node.type === 'component' ? [node.tagName] : []))).toEqual([
+ 'Query',
+ 'Python',
+ ])
+ })
+
+ it('splits embedded cards out of callouts while keeping the emoji and text quoted', () => {
+ const content: JSONContent = {
+ type: 'doc',
+ content: [
+ {
+ type: 'callout',
+ attrs: { emoji: '!' },
+ content: [
+ { type: 'paragraph', content: [{ type: 'text', text: 'Watch this' }] },
+ {
+ type: NotebookNodeType.Query,
+ attrs: {
+ query: { kind: NodeKind.SavedInsightNode, shortId: 'abc123' },
+ hideFilters: true,
+ },
+ },
+ ],
+ },
+ ],
+ }
+
+ const markdown = convertNotebookContentToMarkdown(content)
+
+ expect(markdown).toContain('> ! Watch this')
+ expect(markdown).toContain('\n\n<Query ')
+ expect(markdown).not.toContain('> <')
+ expect(parseMarkdownNotebook(markdown).errors).toEqual([])
+ })
+
it('converts notebook artifacts to markdown notebook content', () => {
const content: NotebookArtifactContent = {
content_type: ArtifactContentType.Notebook,
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts
index d17ea190503b..522e2b45642e 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts
@@ -544,12 +544,7 @@ function serializeRichContentNode(
}
if (nodeType === 'blockquote') {
- return (node.content ?? [])
- .map((child) => serializeRichContentNode(child, listDepth, options))
- .join('\n')
- .split('\n')
- .map((line) => `> ${line}`)
- .join('\n')
+ return serializeBlockquoteNode(node, listDepth, options)
}
if (nodeType === 'bulletList' || nodeType === 'orderedList' || nodeType === 'taskList') {
@@ -684,26 +679,101 @@ function serializeLegacyLinkNode(node: JSONContent, options: NotebookMarkdownCon
return serializeUnknownRichContentNode(node)
}
+// The markdown notebook blockquote only holds inline text (and list lines), so block content
+// inside a v1 blockquote or callout — embedded cards like Query/Python, headings, code blocks,
+// tables, nested quotes — is emitted as standalone blocks that split the quote. Quoting those
+// lines instead would produce markdown the parser can only read back as escaped literal text,
+// destroying the nodes on the next save.
+function isBlockquotableRichContentNode(node: JSONContent, serialized: string): boolean {
+ const nodeType = getRichContentNodeType(node)
+ if (nodeType === 'paragraph' || nodeType === 'text') {
+ return true
+ }
+ // Blockquoted lists parse back (`> - item`), but only while every line is a list line — a
+ // list that spilled block content into standalone blocks splits out of the quote with them.
+ if (LIST_NODE_TYPES.has(nodeType ?? '')) {
+ return !serialized.includes('\n\n')
+ }
+ return false
+}
+
+function serializeBlockquoteNode(
+ node: JSONContent,
+ listDepth: number,
+ options: NotebookMarkdownConversionOptions = {}
+): string {
+ const blocks: string[] = []
+ let pendingQuoteLines: string[] = []
+ const flushQuoteLines = (): void => {
+ if (pendingQuoteLines.length) {
+ blocks.push(pendingQuoteLines.map((line) => `> ${line}`).join('\n'))
+ pendingQuoteLines = []
+ }
+ }
+
+ for (const child of node.content ?? []) {
+ const childMarkdown = serializeRichContentNode(child, listDepth, options)
+ if (isBlockquotableRichContentNode(child, childMarkdown)) {
+ pendingQuoteLines.push(...childMarkdown.split('\n'))
+ } else if (childMarkdown.trim()) {
+ flushQuoteLines()
+ blocks.push(childMarkdown)
+ }
+ }
+ flushQuoteLines()
+
+ return blocks.join('\n\n')
+}
+
function serializeCalloutNode(node: JSONContent, options: NotebookMarkdownConversionOptions = {}): string {
- const body = (node.content ?? [])
- .map((child) => serializeRichContentNode(child, 0, options))
- .filter((block) => block.trim().length > 0)
- .join('\n\n')
- .trim()
const emoji =
typeof node.attrs?.emoji === 'string' && node.attrs.emoji.trim()
? escapeInlineMarkdownText(node.attrs.emoji.trim())
: ''
- const blockquoteBody = `${emoji}${emoji && body ? ' ' : ''}${body}`.trim()
+ const blocks: string[] = []
+ let pendingQuoteBodies: string[] = []
+ let emojiPlaced = false
+ const flushQuoteBodies = (): void => {
+ if (!pendingQuoteBodies.length) {
+ return
+ }
+ let body = pendingQuoteBodies.join('\n\n')
+ if (emoji && !emojiPlaced) {
+ body = `${emoji} ${body}`
+ emojiPlaced = true
+ }
+ blocks.push(
+ body
+ .split('\n')
+ .map((line) => `> ${line}`)
+ .join('\n')
+ )
+ pendingQuoteBodies = []
+ }
+
+ for (const child of node.content ?? []) {
+ const childMarkdown = serializeRichContentNode(child, 0, options)
+ if (!childMarkdown.trim()) {
+ continue
+ }
+ if (isBlockquotableRichContentNode(child, childMarkdown)) {
+ pendingQuoteBodies.push(childMarkdown)
+ } else {
+ flushQuoteBodies()
+ blocks.push(childMarkdown)
+ }
+ }
+ flushQuoteBodies()
- if (!blockquoteBody) {
+ if (emoji && !emojiPlaced) {
+ blocks.unshift(`> ${emoji}`)
+ }
+
+ if (!blocks.length) {
return serializeUnknownRichContentNode(node)
}
- return blockquoteBody
- .split('\n')
- .map((line) => `> ${line}`)
- .join('\n')
+ return blocks.join('\n\n')
}
function isNotebookObjectProp(value: NotebookPropValue | undefined): value is Record<string, NotebookPropValue> {
diff --git a/products/notebooks/backend/markdown_conversion.py b/products/notebooks/backend/markdown_conversion.py
index f6b502654672..36080660cc12 100644
--- a/products/notebooks/backend/markdown_conversion.py
+++ b/products/notebooks/backend/markdown_conversion.py
@@ -242,12 +242,7 @@ def _serialize_rich_content_node(
return escape_markdown_block_lines(_serialize_inline_content(_content_list(node), options))
if node_type == "blockquote":
- return "\n".join(
- f"> {line}"
- for line in "\n".join(
- _serialize_rich_content_node(child, list_depth, options) for child in _content_list(node)
- ).split("\n")
- )
+ return _serialize_blockquote_node(node, list_depth, options)
if node_type in LIST_NODE_TYPES:
return _serialize_list(node, node_type == "orderedList", list_depth, options)
@@ -357,20 +352,80 @@ def _serialize_legacy_link_node(node: JSONContent, options: NotebookMarkdownConv
return _serialize_unknown_rich_content_node(node)
+# The markdown notebook blockquote only holds inline text (and list lines), so block content
+# inside a v1 blockquote or callout — embedded cards like Query/Python, headings, code blocks,
+# tables, nested quotes — is emitted as standalone blocks that split the quote. Quoting those
+# lines instead would produce markdown the parser can only read back as escaped literal text,
+# destroying the nodes on the next save.
+def _is_blockquotable_rich_content_node(node: JSONContent, serialized: str) -> bool:
+ node_type = _node_type(node)
+ if node_type in ("paragraph", "text"):
+ return True
+ # Blockquoted lists parse back (`> - item`), but only while every line is a list line — a
+ # list that spilled block content into standalone blocks splits out of the quote with them.
+ if node_type in LIST_NODE_TYPES:
+ return "\n\n" not in serialized
+ return False
+
+
+def _serialize_blockquote_node(node: JSONContent, list_depth: int, options: NotebookMarkdownConversionOptions) -> str:
+ blocks: list[str] = []
+ pending_quote_lines: list[str] = []
+
+ def flush_quote_lines() -> None:
+ if pending_quote_lines:
+ blocks.append("\n".join(f"> {line}" for line in pending_quote_lines))
+ pending_quote_lines.clear()
+
+ for child in _content_list(node):
+ child_markdown = _serialize_rich_content_node(child, list_depth, options)
+ if _is_blockquotable_rich_content_node(child, child_markdown):
+ pending_quote_lines.extend(child_markdown.split("\n"))
+ elif child_markdown.strip():
+ flush_quote_lines()
+ blocks.append(child_markdown)
+ flush_quote_lines()
+
+ return "\n\n".join(blocks)
+
+
def _serialize_callout_node(node: JSONContent, options: NotebookMarkdownConversionOptions) -> str:
attrs = node.get("attrs")
raw_emoji = attrs.get("emoji") if isinstance(attrs, dict) else None
- emoji = raw_emoji.strip() if isinstance(raw_emoji, str) else ""
- body = "\n\n".join(
- block
- for block in (_serialize_rich_content_node(child, 0, options) for child in _content_list(node))
- if block.strip()
- ).strip()
- if emoji:
- body = f"{escape_inline_markdown_text(emoji)} {body}".strip()
- if not body:
+ emoji = escape_inline_markdown_text(raw_emoji.strip()) if isinstance(raw_emoji, str) and raw_emoji.strip() else ""
+ blocks: list[str] = []
+ pending_quote_bodies: list[str] = []
+ emoji_placed = False
+
+ def flush_quote_bodies() -> None:
+ nonlocal emoji_placed
+ if not pending_quote_bodies:
+ return
+ body = "\n\n".join(pending_quote_bodies)
+ if emoji and not emoji_placed:
+ body = f"{emoji} {body}"
+ emoji_placed = True
+ blocks.append("\n".join(f"> {line}" for line in body.split("\n")))
+ pending_quote_bodies.clear()
+
+ for child in _content_list(node):
+ child_markdown = _serialize_rich_content_node(child, 0, options)
+ if not child_markdown.strip():
+ continue
+ if _is_blockquotable_rich_content_node(child, child_markdown):
+ pending_quote_bodies.append(child_markdown)
+ else:
+ flush_quote_bodies()
+ blocks.append(child_markdown)
+ flush_quote_bodies()
+
+ if emoji and not emoji_placed:
+ blocks.insert(0, f"> {emoji}")
+
+ if not blocks:
return _serialize_unknown_rich_content_node(node)
- return "\n".join(f"> {line}" for line in body.split("\n"))
+
+ return "\n\n".join(blocks)
def _serialize_unknown_rich_content_node(node: JSONContent) -> str:
diff --git a/products/notebooks/backend/test/test_markdown_migration.py b/products/notebooks/backend/test/test_markdown_migration.py
index adeae439e79d..7efd44a51a67 100644
--- a/products/notebooks/backend/test/test_markdown_migration.py
+++ b/products/notebooks/backend/test/test_markdown_migration.py
@@ -214,6 +214,60 @@ class TestNotebookMarkdownConversion(BaseTest):
assert "> ! **Heads** and *note*" in markdown
assert "[https://app.posthog.com/cohorts/37958](https://app.posthog.com/cohorts/37958)" in markdown
+ def test_splits_embedded_cards_and_headings_out_of_blockquotes_and_callouts(self) -> None:
+ content = {
+ "type": "doc",
+ "content": [
+ {
+ "type": "blockquote",
+ "content": [
+ {"type": "paragraph", "content": [{"type": "text", "text": "Quoted context"}]},
+ {
+ "type": "ph-query",
+ "attrs": {
+ "query": {"kind": "SavedInsightNode", "shortId": "abc123"},
+ "hideFilters": True,
+ },
+ },
+ {
+ "type": "blockquote",
+ "content": [
+ {
+ "type": "heading",
+ "attrs": {"level": 2},
+ "content": [{"type": "text", "text": "Where to improve"}],
+ },
+ {"type": "ph-python", "attrs": {"code": "print(1)", "hideFilters": True}},
+ ],
+ },
+ ],
+ },
+ {
+ "type": "callout",
+ "attrs": {"emoji": "!"},
+ "content": [
+ {"type": "paragraph", "content": [{"type": "text", "text": "Watch this"}]},
+ {
+ "type": "ph-query",
+ "attrs": {
+ "query": {"kind": "SavedInsightNode", "shortId": "abc123"},
+ "hideFilters": True,
+ },
+ },
+ ],
+ },
+ ],
+ }
+
+ markdown = convert_notebook_content_to_markdown(content)
+
+ assert "> Quoted context" in markdown
+ assert "\n\n<Query " in markdown
+ assert "\n\n## Where to improve" in markdown
+ assert "\n\n<Python " in markdown
+ assert "> ! Watch this" in markdown
+ assert "> <" not in markdown
+
class TestNotebookMarkdownMigration(BaseTest):
def test_stats_count_all_notebooks_for_optional_team_scope(self) -> None: