:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(notebooks): keep explicitly added markdown blocks as separate nodes (#74937)
Sinan Kucukkoselerfcdf603170ed
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.tsindex 32c3fc74c22d..0d544d595d8e 100644--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts@@ -869,13 +869,19 @@ continued line'<Embed src="https://example.com" />','','Tail paragraph',+ // A second blank line marks a block that was added as a node of its own,+ // so it gets its own card instead of joining the paragraph above it+ '',+ '',+ 'Separated paragraph',].join('\n')),}))const groups = Array.from(container.querySelectorAll('.MarkdownNotebook__text-group'))- expect(groups).toHaveLength(2)+ expect(groups).toHaveLength(3)+ expect(groups[2].textContent).toContain('Separated paragraph')expect(groups[0].querySelectorAll('.MarkdownNotebook__text-block')).toHaveLength(4)expect(groups[0].querySelectorAll('.MarkdownNotebook__list-block')).toHaveLength(2)expect(groups[0].querySelector('.MarkdownNotebook__list-block ul')).toBeInstanceOf(HTMLUListElement)@@ -889,6 +895,60 @@ continued lineexpect(container.querySelector('.MarkdownNotebook__text-group .MarkdownNotebook__component-shell')).toBeNull()})+ it('adds a block from the insert boundary as a node of its own', () => {+ const onChange = jest.fn()+ const { container } = render(+ createElement(MarkdownNotebook, { value: withNotebookTitle('Intro paragraph'), onChange })+ )++ const addBlockButtons = container.querySelectorAll<HTMLButtonElement>('[aria-label="Add block"]')+ fireEvent.click(addBlockButtons[addBlockButtons.length - 1])++ const textCommand = Array.from(container.querySelectorAll('.MarkdownNotebook__insert-item')).find(+ (button) => button.textContent === 'Text'+ )+ fireEvent.click(textCommand as HTMLButtonElement)++ const insertedTextBlock = getBodyTextBlock(container, 1)+ insertedTextBlock.textContent = 'Second block'+ fireEvent.input(insertedTextBlock)++ expect(container.querySelectorAll('.MarkdownNotebook__text-group')).toHaveLength(2)+ expect(onChange).toHaveBeenLastCalledWith(+ `${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\nIntro paragraph\n\n\nSecond block`+ )+ })++ it('rejoins the block below an inserted one once the insert is undone', () => {+ // Opening the boundary pushes the block below onto its own card so the inserted node+ // does not absorb it. That card boundary is invisible to the node fingerprint, so undo+ // used to leave it standing: the block below stayed in a card of its own, with the+ // extra blank line saved into the markdown.+ const markdown = withNotebookTitle('Intro paragraph\n\nTail paragraph')+ const onChange = jest.fn()+ const { container } = render(createElement(MarkdownNotebook, { value: markdown, onChange }))++ fireEvent.click(container.querySelector('[aria-label="Add block"][data-boundary-index="2"]') as HTMLElement)+ const textCommand = Array.from(container.querySelectorAll('.MarkdownNotebook__insert-item')).find(+ (button) => button.textContent === 'Text'+ )+ fireEvent.click(textCommand as HTMLButtonElement)++ const insertedTextBlock = getBodyTextBlock(container, 1)+ insertedTextBlock.textContent = 'Inserted block'+ fireEvent.input(insertedTextBlock)+ expect(onChange).toHaveBeenLastCalledWith(+ `${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\nIntro paragraph\n\n\nInserted block\n\n\nTail paragraph`+ )++ for (let undoCount = 0; undoCount < 4; undoCount++) {+ fireUndoShortcut(getEditableTextBlocks(container)[0])+ }++ expect(onChange).toHaveBeenLastCalledWith(markdown)+ expect(container.querySelectorAll('.MarkdownNotebook__text-group')).toHaveLength(1)+ })+it('serializes hidden component panel props as bare JSX props', () => {const markdown = `<Query query={{"kind":"DataTableNode"}} hideFilters={true} hideResults={false} disabled={false} />`const document = parseMarkdownNotebook(markdown)@@ -2803,7 +2863,7 @@ Intro paragraphfireEvent.click(addAfterButton)expect(container.querySelector('.MarkdownNotebook__row--insert-menu-open')).toBeInstanceOf(HTMLElement)- expect(onChange).toHaveBeenLastCalledWith(`${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\nIntro paragraph\n\n `)+ expect(onChange).toHaveBeenLastCalledWith(`${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\nIntro paragraph\n\n\n `)const textBlocks = getEditableTextBlocks(container)const slashTextBlock = textBlocks[2]expect(document.activeElement).toEqual(slashTextBlock)@@ -2835,20 +2895,20 @@ Intro paragraphactiveSlashTextBlock.textContent = 'zzzz'fireEvent.input(activeSlashTextBlock)- expect(onChange).toHaveBeenLastCalledWith(`${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\nIntro paragraph\n\nzzzz`)+ expect(onChange).toHaveBeenLastCalledWith(`${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\nIntro paragraph\n\n\nzzzz`)expect(container.querySelector('.MarkdownNotebook__empty-menu')?.textContent).toEqual('No components found')fireEvent.keyDown(activeSlashTextBlock, { key: 'Enter' })activeSlashTextBlock = getEditableTextBlocks(container)[2]expect(container.querySelector('.MarkdownNotebook__insert-menu')).toBeInstanceOf(HTMLElement)- expect(onChange).toHaveBeenLastCalledWith(`${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\nIntro paragraph\n\n `)+ expect(onChange).toHaveBeenLastCalledWith(`${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\nIntro paragraph\n\n\n `)expect(document.activeElement).toEqual(activeSlashTextBlock)expect(activeSlashTextBlock.textContent).toEqual('')activeSlashTextBlock.textContent = 'tr'fireEvent.input(activeSlashTextBlock)- expect(onChange).toHaveBeenLastCalledWith(`${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\nIntro paragraph\n\ntr`)+ expect(onChange).toHaveBeenLastCalledWith(`${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\nIntro paragraph\n\n\ntr`)expect(container.querySelector('.MarkdownNotebook__insert-menu')).toBeInstanceOf(HTMLElement)@@ -2864,7 +2924,7 @@ Intro paragraphfireEvent.click(trendButton as HTMLButtonElement)expect(onChange).toHaveBeenLastCalledWith(- expect.stringContaining(`${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\nIntro paragraph\n\n<Query hideFilters`)+ expect.stringContaining(`${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\nIntro paragraph\n\n\n<Query hideFilters`))expect(container.querySelector('.MarkdownNotebook__component-edit')).toBeNull()expect(container.querySelector('.MarkdownNotebook__component-preview')).toBeInstanceOf(HTMLElement)@@ -2957,7 +3017,7 @@ Intro paragraphrerender(createElement(MarkdownNotebook, { value: nextValue, onChange }))const textBlocks = Array.from(container.querySelectorAll(NOTEBOOK_TEST_EDITABLE_SELECTOR)) as HTMLElement[]- expect(nextValue).toEqual(`${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\nIntro paragraph\n\n `)+ expect(nextValue).toEqual(`${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\nIntro paragraph\n\n\n `)expect(textBlocks).toHaveLength(3)expect(textBlocks[2].textContent).toEqual('')})@@ -3249,7 +3309,7 @@ Second paragraph`)fireEvent.click(boundaryButton as HTMLButtonElement)expect(onChange).toHaveBeenLastCalledWith(- `${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\nFirst paragraph\n\n \n\nSecond paragraph`+ `${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\nFirst paragraph\n\n\n \n\n\nSecond paragraph`)const closeButton = container.querySelector('.MarkdownNotebook__line-insert-menu-button[aria-expanded="true"]')expect(closeButton).toBeInstanceOf(HTMLButtonElement)@@ -3299,7 +3359,7 @@ Second paragraph`),expect(container.querySelector('.MarkdownNotebook__insert-menu')).toBeInstanceOf(HTMLElement)expect(onChange).toHaveBeenLastCalledWith(- `${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\nFirst paragraph\n\n \n\nSecond paragraph`+ `${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\nFirst paragraph\n\n\n \n\n\nSecond paragraph`)})@@ -3318,7 +3378,7 @@ ${queryMarkdown}`)fireEvent.click(boundaryButton as HTMLButtonElement)expect(onChange).toHaveBeenLastCalledWith(- `${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\nIntro paragraph\n\n \n\n${queryMarkdown}`+ `${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\nIntro paragraph\n\n\n \n\n${queryMarkdown}`)const closeButton = container.querySelector('.MarkdownNotebook__line-insert-menu-button[aria-expanded="true"]')expect(closeButton).toBeInstanceOf(HTMLButtonElement)@@ -4260,7 +4320,7 @@ aXbcfireEvent.mouseDown(addBeforeGap as HTMLElement, { button: 0 })expect(onChange).toHaveBeenLastCalledWith(- `${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\n${queryMarkdown}\n\n \n\nIntro paragraph`+ `${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\n${queryMarkdown}\n\n\n \n\n\nIntro paragraph`)expect(container.querySelector('.MarkdownNotebook__insert-menu')).toBeInstanceOf(HTMLElement)expect(container.querySelector('.MarkdownNotebook__insert-category h5')?.textContent).toEqual('Common')@@ -4277,7 +4337,7 @@ aXbcexpect(trendButton).toBeInstanceOf(HTMLButtonElement)fireEvent.click(trendButton as HTMLButtonElement)- expect(onChange).toHaveBeenLastCalledWith(expect.stringContaining(`/>\n\nIntro paragraph`))+ expect(onChange).toHaveBeenLastCalledWith(expect.stringContaining(`/>\n\n\nIntro paragraph`))})it('floats and closes the formatting toolbar based on the active text selection', () => {@@ -8723,7 +8783,7 @@ Second paragraph`),const textBlocks = getEditableTextBlocks(container)expect(onChange).toHaveBeenLastCalledWith(- `${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\nFirst paragraph\n\nSecond paragraph\n\n `+ `${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\nFirst paragraph\n\nSecond paragraph\n\n\n `)expect(textBlocks).toHaveLength(4)expect(document.activeElement).toEqual(textBlocks[3])diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsxindex 5f7b4e99ddd3..e7747c597841 100644--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx@@ -65,6 +65,7 @@ import {isGroupedBlockquoteNode,isPromptComponentNode,isTextBlockNode,+ isTextGroupNode,makeEmptyNotebookTitle,removeNotebookNodesWithRefCleanup,stripNotebookRefMarksFromNodes,@@ -77,6 +78,7 @@ import {textBlocksShareContinuationStyle,updateNotebookCodeBlockText,withoutLeadingEmptyTitleGroup,+ withPreservedGroupStart,writeSystemClipboardText,} from './documentModel'import {@@ -1663,7 +1665,9 @@ function MarkdownNotebookEditor({commitDocument({...currentDocument,- nodes: nodes.flatMap((currentNode) => (currentNode.id === node.id ? replacementNodes : [currentNode])),+ nodes: nodes.flatMap((currentNode) =>+ currentNode.id === node.id ? withPreservedGroupStart(node, replacementNodes) : [currentNode]+ ),})return true}, [commitDocument, insertMenu?.nodeId])@@ -2622,7 +2626,7 @@ function MarkdownNotebookEditor({const replaceNode = useCallback((nodeId: string, nextNode: NotebookBlockNode): void => {- updateNode(nodeId, () => nextNode)+ updateNode(nodeId, (previousNode) => withPreservedGroupStart(previousNode, [nextNode])[0])},[updateNode])@@ -2673,7 +2677,7 @@ function MarkdownNotebookEditor({return [node]}didReplace = true- return replacementNodes+ return withPreservedGroupStart(node, replacementNodes)}),})},@@ -4119,7 +4123,11 @@ function MarkdownNotebookEditor({commitDocument({...currentDocument,- nodes: currentDocument.nodes.filter((_, index) => index !== nodeIndex),+ nodes: currentDocument.nodes+ .filter((_, index) => index !== nodeIndex)+ .map((node) =>+ node.id === menu.rejoinNodeIdOnClose ? { ...node, startsGroup: undefined } : node+ ),},{ addToHistory: false })@@ -4200,12 +4208,26 @@ function MarkdownNotebookEditor({const currentDocument = documentRef.currentconst nodes = currentDocument.nodes- const insertedNode = makeEmptyParagraph(`boundary-${String(boundaryIndex)}`)+ const insertedNode: NotebookBlockNode = {+ ...makeEmptyParagraph(`boundary-${String(boundaryIndex)}`),+ startsGroup: true,+ }const clampedBoundaryIndex = Math.max(1, Math.min(boundaryIndex, nodes.length))+ // The block that followed the boundary starts its own card too, or it would join the+ // inserted one instead of staying with the text it was grouped with.+ const followingNode = nodes[clampedBoundaryIndex]+ const rejoinNodeIdOnClose =+ followingNode && isTextGroupNode(followingNode) && !followingNode.startsGroup ? followingNode.id : undefinedcommitDocument({...currentDocument,- nodes: [...nodes.slice(0, clampedBoundaryIndex), insertedNode, ...nodes.slice(clampedBoundaryIndex)],+ nodes: [+ ...nodes.slice(0, clampedBoundaryIndex),+ insertedNode,+ ...nodes+ .slice(clampedBoundaryIndex)+ .map((node) => (node.id === rejoinNodeIdOnClose ? { ...node, startsGroup: true } : node)),+ ],})restoreSelectionRef.current = { nodeId: insertedNode.id, start: 0, end: 0 }onInteractionStateChange?.(true)@@ -4216,6 +4238,7 @@ function MarkdownNotebookEditor({mode: 'tools',detached: true,removeNodeOnClose: true,+ rejoinNodeIdOnClose,})}diff --git a/frontend/src/lib/components/MarkdownNotebook/README.md b/frontend/src/lib/components/MarkdownNotebook/README.mdindex 72a26aa11903..67a5ad33faa5 100644--- a/frontend/src/lib/components/MarkdownNotebook/README.md+++ b/frontend/src/lib/components/MarkdownNotebook/README.md@@ -24,7 +24,7 @@ See [COMPONENTS.md](./COMPONENTS.md) for how to register embeddable components (## Supported markdown-Inline: bold (`**`/`__`), italic (`*`/`_`, underscores only at word boundaries), underline (`<u>`), strikethrough (`~~`), inline code, links (http/https only; balanced parentheses in hrefs supported), hard breaks, ref anchors (`<ref id="x">highlighted text</ref>`, lowercase inline tags so they can never collide with uppercase component tags), and mentions (`<mention id="5">@Name</mention>`; the text is the display label, the id is the member). Blocks: paragraphs, headings (`#`–`######` parse and round-trip; the UI offers H1–H3), blockquotes (including quoted headings — `> ## Heading` — and quoted lists), ordered/unordered lists with nesting, GFM task lists (`- [ ]`/`- [x]` on bullet items; the checkbox replaces the bullet and `1. [x]` stays literal), GFM tables with column alignment (header and body rows must start with `|`), fenced code blocks (language tag preserved; the serializer picks a fence longer than any backtick run in the content), dividers (`---`/`***`/`___`, stored as a reserved `Divider` component tag), images (``, stored as the `Image` component), and JSX-like component tags.+Inline: bold (`**`/`__`), italic (`*`/`_`, underscores only at word boundaries), underline (`<u>`), strikethrough (`~~`), inline code, links (http/https only; balanced parentheses in hrefs supported), hard breaks, ref anchors (`<ref id="x">highlighted text</ref>`, lowercase inline tags so they can never collide with uppercase component tags), and mentions (`<mention id="5">@Name</mention>`; the text is the display label, the id is the member). Blocks: paragraphs, headings (`#`–`######` parse and round-trip; the UI offers H1–H3), blockquotes (including quoted headings — `> ## Heading` — and quoted lists), ordered/unordered lists with nesting, GFM task lists (`- [ ]`/`- [x]` on bullet items; the checkbox replaces the bullet and `1. [x]` stays literal), GFM tables with column alignment (header and body rows must start with `|`), fenced code blocks (language tag preserved; the serializer picks a fence longer than any backtick run in the content), dividers (`---`/`***`/`___`, stored as a reserved `Divider` component tag), images (``, stored as the `Image` component), and JSX-like component tags. Blocks are separated by a blank line; a second blank line additionally starts a new card (see [Visual grouping](#visual-grouping)).### Round-trip guarantee@@ -34,6 +34,11 @@ Inline: bold (`**`/`__`), italic (`*`/`_`, underscores only at word boundaries),Consecutive text-like blocks (paragraphs, headings, lists, blockquotes, code blocks) render inside one shared card surface — a _text group_ (`getMarkdownNotebookVisualGroups` in `documentModel.ts`). Within a group, blockquote runs and code blocks form their own tinted sub-surfaces (`MarkdownNotebookTextSurface`: `text` | `quote` | `code`); a surface that starts or ends its group stretches flush to the card edge. Components, tables, and dividers render as standalone rows between groups.+A block carrying `startsGroup` breaks out of the run above it and starts its own card. It is set when the block was added as a node in its own right rather than typed as a continuation: the insert boundary's "+", an MCP `notebooks-add-cell` insert, `appendMarkdownNotebookBlock`. Enter inside a card keeps making blocks in that same card, so the two stay distinguishable. The flag lives in the markdown as a **second blank line** before the block (`NOTEBOOK_BLOCK_SEPARATOR`) — nothing else would survive a save, since markdown is the only storage. It never applies to the first block, which has no separator to widen.++Because it belongs to the slot rather than the content, `withPreservedGroupStart` carries it across a replacement (an insert-menu command swapping a real node in for the placeholder) and keeps it on the first half only when Enter splits a block.+It also stays out of `getNodeFingerprint`, since folding it in would churn the content-derived node id every time a card splits, so both layers that compare nodes by fingerprint handle it explicitly: `diffNotebookDocuments` emits a `set_group_start` operation (what makes a card boundary undoable, and what rebases it past concurrent edits), and `mergeNotebookMarkdownChanges` merges it on its own three-way rule.+Code blocks render a non-editable line-number gutter next to the editable `<pre>`. Gutter numbers are absolutely positioned at line tops measured from the DOM (wrapped lines hang without numbers), so the gutter never participates in selection, copy, or text offsets. A trailing `<br>` sentinel keeps trailing blank lines visible; it contributes nothing to `textContent`, which keeps offsets stable.## Event architecture: one editing hostdiff --git a/frontend/src/lib/components/MarkdownNotebook/collaboration.ts b/frontend/src/lib/components/MarkdownNotebook/collaboration.tsindex d874815aca6c..22e46eea96cc 100644--- a/frontend/src/lib/components/MarkdownNotebook/collaboration.ts+++ b/frontend/src/lib/components/MarkdownNotebook/collaboration.ts@@ -68,17 +68,19 @@ export function mergeNotebookMarkdownChanges({const remoteFingerprint = getNodeFingerprint(remoteNode)const localChanged = localFingerprint !== baseFingerprintconst remoteChanged = remoteFingerprint !== baseFingerprint+ const pushMergedNode = (node: NotebookBlockNode): void =>+ pushOutputNode(outputNodes, outputIds, withMergedGroupStart(baseNode, localNode, remoteNode, node))if (localChanged && remoteChanged && localFingerprint !== remoteFingerprint) {const mergedComponentNode = mergeNotebookComponentNodes(baseNode, localNode, remoteNode)if (mergedComponentNode) {- pushOutputNode(outputNodes, outputIds, mergedComponentNode)+ pushMergedNode(mergedComponentNode)return}const mergedNode = mergeNotebookBlockNodeText(baseNode, localNode, remoteNode)if (mergedNode) {- pushOutputNode(outputNodes, outputIds, mergedNode)+ pushMergedNode(mergedNode)return}@@ -88,11 +90,11 @@ export function mergeNotebookMarkdownChanges({localMarkdown: serializeNode(localNode),remoteMarkdown: serializeNode(remoteNode),})- pushOutputNode(outputNodes, outputIds, localNode)+ pushMergedNode(localNode)return}- pushOutputNode(outputNodes, outputIds, localChanged ? localNode : remoteNode)+ pushMergedNode(localChanged ? localNode : remoteNode)})// The deletion still wins (re-adding would resurrect deleted blocks on every merge),@@ -146,6 +148,19 @@ export function mergeNotebookMarkdownChanges({}}+// `startsGroup` is deliberately outside a node's fingerprint — folding it in would churn the+// content-derived node id every time a card is split — so it merges on its own three-way rule:+// whichever side moved the card boundary away from base wins.+function withMergedGroupStart(+ baseNode: NotebookBlockNode,+ localNode: NotebookBlockNode,+ remoteNode: NotebookBlockNode,+ mergedNode: NotebookBlockNode+): NotebookBlockNode {+ const startsGroup = baseNode.startsGroup === localNode.startsGroup ? remoteNode.startsGroup : localNode.startsGroup+ return startsGroup === mergedNode.startsGroup ? mergedNode : { ...mergedNode, startsGroup }+}+function pushOutputNode(nodes: NotebookBlockNode[], outputIds: Set<string>, node: NotebookBlockNode): void {if (outputIds.has(node.id)) {returndiff --git a/frontend/src/lib/components/MarkdownNotebook/documentModel.ts b/frontend/src/lib/components/MarkdownNotebook/documentModel.tsindex fa07a2cdd1d7..4b8c93f6c749 100644--- a/frontend/src/lib/components/MarkdownNotebook/documentModel.ts+++ b/frontend/src/lib/components/MarkdownNotebook/documentModel.ts@@ -51,14 +51,20 @@ export type MarkdownNotebookVisualGroup =index: number}+/** Blocks that share a card with the text-like blocks around them. Components, tables, and+ * dividers always stand alone, so they never need a `startsGroup` boundary. */+export function isTextGroupNode(node: NotebookBlockNode | undefined): boolean {+ return (+ !!node && (isTextBlockNode(node) || node.type === 'list' || node.type === 'code' || isPromptComponentNode(node))+ )+}+export function getMarkdownNotebookVisualGroups(nodes: NotebookBlockNode[],insertMenuNodeId?: string): MarkdownNotebookVisualGroup[] {const groups: MarkdownNotebookVisualGroup[] = []let currentTextGroup: Extract<MarkdownNotebookVisualGroup, { type: 'text' }> | null = null- const isTextLikeNode = (node: NotebookBlockNode | undefined): boolean =>- !!node && (isTextBlockNode(node) || node.type === 'list' || node.type === 'code' || isPromptComponentNode(node))// A discussion comment sits right above the text it highlights; joining the surrounding// text group keeps that text from being split into separate cards. A comment anchored to@@ -74,12 +80,15 @@ export function getMarkdownNotebookVisualGroups(while (nextIndex < nodes.length && isDiscussionCommentNode(nodes[nextIndex])) {nextIndex += 1}- return isTextLikeNode(nodes[nextIndex])+ return isTextGroupNode(nodes[nextIndex])}nodes.forEach((node, index) => {const shouldBreakTextGroupForInsertMenu = node.id === insertMenuNodeId && !isPromptComponentNode(node)- if ((isTextLikeNode(node) || commentJoinsTextGroup(index)) && !shouldBreakTextGroupForInsertMenu) {+ if ((isTextGroupNode(node) || commentJoinsTextGroup(index)) && !shouldBreakTextGroupForInsertMenu) {+ if (node.startsGroup) {+ currentTextGroup = null+ }if (!currentTextGroup) {currentTextGroup = {type: 'text',@@ -131,6 +140,19 @@ export function withoutLeadingEmptyTitleGroup(groups: MarkdownNotebookVisualGroureturn restItems.length ? [{ ...firstGroup, items: restItems }, ...groups.slice(1)] : groups.slice(1)}+// `startsGroup` belongs to the slot a block occupies, not to its content: whatever replaces the+// block inherits the card boundary, and the halves a split leaves behind must not each keep it —+// that would start a fresh card on every Enter.+export function withPreservedGroupStart(+ replacedNode: NotebookBlockNode,+ replacementNodes: NotebookBlockNode[]+): NotebookBlockNode[] {+ return replacementNodes.map((node, index) => {+ const startsGroup = index === 0 ? replacedNode.startsGroup : undefined+ return startsGroup === node.startsGroup ? node : { ...node, startsGroup }+ })+}+export function isTextBlockNode(node: NotebookBlockNode): node is NotebookTextBlockNode {return node.type === 'paragraph' || node.type === 'heading' || node.type === 'blockquote'}diff --git a/frontend/src/lib/components/MarkdownNotebook/editorTypes.ts b/frontend/src/lib/components/MarkdownNotebook/editorTypes.tsindex 25e8d61adc0a..aaa71fb97ca0 100644--- a/frontend/src/lib/components/MarkdownNotebook/editorTypes.ts+++ b/frontend/src/lib/components/MarkdownNotebook/editorTypes.ts@@ -58,6 +58,9 @@ export type InsertMenuState = {mode?: 'tools' | 'ai'detached?: booleanremoveNodeOnClose?: boolean+ /** Set with `removeNodeOnClose`: the block pushed onto its own card to make room for the+ * inserted one. Closing the menu without inserting rejoins it to the card it came from. */+ rejoinNodeIdOnClose?: stringsource?: 'slash' | 'selection'selectedMarkdown?: stringselectedRefId?: stringdiff --git a/frontend/src/lib/components/MarkdownNotebook/markdown.ts b/frontend/src/lib/components/MarkdownNotebook/markdown.tsindex 40ceee863703..8b5266b77538 100644--- a/frontend/src/lib/components/MarkdownNotebook/markdown.ts+++ b/frontend/src/lib/components/MarkdownNotebook/markdown.ts@@ -57,6 +57,11 @@ export function isDiscussionCommentProps(props: NotebookComponentProps): boolean}const TABLE_SEPARATOR_CELL_REGEX = /^:?-{3,}:?$/const EMPTY_PARAGRAPH_MARKDOWN = ' '+/** One blank line separates two blocks of the same card; a second one starts a new card+ * (`startsGroup` in `types.ts`). Programmatic writers append blocks with this separator so each+ * one lands as its own node. */+export const NOTEBOOK_BLOCK_SEPARATOR = '\n\n\n'+const NOTEBOOK_BLOCK_JOINER = '\n\n'// Every character the serializer may backslash-escape; the inline parser turns `\X` back into// the literal character for exactly this set, so the two must stay in sync.const INLINE_ESCAPABLE_CHARS = new Set([@@ -114,6 +119,7 @@ export function parseMarkdownNotebook(markdown: string | null | undefined): Note}let lineIndex = 0+ let blankLinesBeforeBlock = 0while (lineIndex < lines.length) {const line = lines[lineIndex]@@ -122,12 +128,15 @@ export function parseMarkdownNotebook(markdown: string | null | undefined): Noteid: '',type: 'paragraph',children: [],+ startsGroup: nodes.length > 0 && blankLinesBeforeBlock > 1 ? true : undefined,})+ blankLinesBeforeBlock = 0lineIndex += 1continue}if (!line.trim()) {+ blankLinesBeforeBlock += 1lineIndex += 1continue}@@ -137,8 +146,12 @@ export function parseMarkdownNotebook(markdown: string | null | undefined): Noteerrors.push(result.error)}if (result.node) {+ if (nodes.length > 0 && blankLinesBeforeBlock > 1) {+ result.node.startsGroup = true+ }pushParsedNode(result.node)}+ blankLinesBeforeBlock = 0lineIndex = Math.max(result.nextLineIndex, lineIndex + 1)}@@ -152,8 +165,14 @@ export function serializeMarkdownNotebook(document: NotebookDocument): string {const shouldPreserveEmptyParagraphs = document.nodes.length > 1const serialized = document.nodes- .map((node) => serializeDocumentNode(node, shouldPreserveEmptyParagraphs))- .join('\n\n')+ .map((node, index) => {+ const block = serializeDocumentNode(node, shouldPreserveEmptyParagraphs)+ if (index === 0) {+ return block+ }+ return `${node.startsGroup ? NOTEBOOK_BLOCK_SEPARATOR : NOTEBOOK_BLOCK_JOINER}${block}`+ })+ .join('')const lastNode = document.nodes[document.nodes.length - 1]const previousNode = document.nodes[document.nodes.length - 2]const shouldPreserveTrailingEmptyParagraph =diff --git a/frontend/src/lib/components/MarkdownNotebook/operations.test.ts b/frontend/src/lib/components/MarkdownNotebook/operations.test.tsindex 9233cc27e832..d7766e4def0b 100644--- a/frontend/src/lib/components/MarkdownNotebook/operations.test.ts+++ b/frontend/src/lib/components/MarkdownNotebook/operations.test.ts@@ -28,6 +28,7 @@ describe('notebook operations', () => {['list edit', '- one\n- two', '- one\n- two\n- three'],['code edit', '```py\nprint(1)\n```', '```py\nprint(2)\n```'],['component props', '<Query query={{"kind":"A"}} />', '<Query query={{"kind":"B"}} />'],+ ['card boundary', '# T\n\na\n\nb', '# T\n\na\n\n\nb'],['everything at once', '# T\n\na\n\nb\n\nc', '# T\n\nc edited\n\nnew\n\na'],])('round-trips %s', (_name, fromMarkdown, toMarkdown) => {const fromDocument = parseDocument(fromMarkdown)@@ -48,7 +49,7 @@ describe('notebook operations', () => {it('produces inverse operations that revert the change', () => {const fromDocument = parseDocument('# Title\n\nalpha\n\nbeta')- const toDocument = evolveDocument(fromDocument, '# Title\n\nalpha edited\n\nnew block\n\nbeta')+ const toDocument = evolveDocument(fromDocument, '# Title\n\nalpha edited\n\nnew block\n\n\nbeta')const operations = diffNotebookDocuments(fromDocument, toDocument)const applied = applyNotebookOperations(fromDocument, operations)diff --git a/frontend/src/lib/components/MarkdownNotebook/operations.ts b/frontend/src/lib/components/MarkdownNotebook/operations.tsindex 44b4a5d40faf..5495dc0327b5 100644--- a/frontend/src/lib/components/MarkdownNotebook/operations.ts+++ b/frontend/src/lib/components/MarkdownNotebook/operations.ts@@ -45,12 +45,19 @@ export type NotebookMoveBlockOperation = {afterId: string | null}+export type NotebookSetGroupStartOperation = {+ type: 'set_group_start'+ nodeId: string+ startsGroup: boolean+}+export type NotebookOperation =| NotebookTextOperation| NotebookInsertBlockOperation| NotebookDeleteBlockOperation| NotebookReplaceBlockOperation| NotebookMoveBlockOperation+ | NotebookSetGroupStartOperationexport type NotebookOperationApplyResult = {document: NotebookDocument@@ -110,7 +117,19 @@ export function diffNotebookDocuments(for (const node of toDocument.nodes) {const fromNode = fromById.get(node.id)- if (!fromNode || getNodeFingerprint(fromNode) === getNodeFingerprint(node)) {+ if (!fromNode) {+ continue+ }++ // A card boundary is outside the node fingerprint (see `startsGroup` in types.ts) and a+ // text change can't carry it either, so moving one needs an operation of its own. Undo+ // depends on it: without it, reverting a block inserted from the boundary would leave the+ // block below stranded in the card the insert gave it.+ if (!!fromNode.startsGroup !== !!node.startsGroup) {+ operations.push({ type: 'set_group_start', nodeId: node.id, startsGroup: !!node.startsGroup })+ }++ if (getNodeFingerprint(fromNode) === getNodeFingerprint(node)) {continue}@@ -226,6 +245,21 @@ export function applyNotebookOperations(continue}+ if (operation.type === 'set_group_start') {+ const index = nodes.findIndex((node) => node.id === operation.nodeId)+ if (index === -1) {+ return null+ }+ const previous = nodes[index]+ nodes[index] = { ...previous, startsGroup: operation.startsGroup ? true : undefined }+ inverted.push({+ type: 'set_group_start',+ nodeId: operation.nodeId,+ startsGroup: !!previous.startsGroup,+ })+ continue+ }+const index = nodes.findIndex((node) => node.id === operation.nodeId)if (index === -1) {return null@@ -332,6 +366,12 @@ function transformNotebookOperationPair(a: NotebookOperation, b: NotebookOperati}}+ if (a.type === 'set_group_start' && b.type === 'set_group_start') {+ // Both sides moved the same card boundary: matching values make each side a no-op for+ // the other, while opposite values have no resolution that respects both.+ return a.startsGroup === b.startsGroup ? { a: null, b: null } : null+ }+if (a.type === 'delete_block') {// After a deletes the node, b has nothing to act on; a survives any change b made.return { a: b.type === 'delete_block' ? null : a, b: null }@@ -352,7 +392,8 @@ function transformNotebookOperationPair(a: NotebookOperation, b: NotebookOperatireturn null}- // move vs text on the same node: independent concerns.+ // What's left touches independent concerns of the same node: a move, a text edit, or a card+ // boundary, none of which invalidates the others.return { a, b }}diff --git a/frontend/src/lib/components/MarkdownNotebook/types.ts b/frontend/src/lib/components/MarkdownNotebook/types.tsindex f8d9fb3b952a..d01ab46bd736 100644--- a/frontend/src/lib/components/MarkdownNotebook/types.ts+++ b/frontend/src/lib/components/MarkdownNotebook/types.ts@@ -36,8 +36,18 @@ export type NotebookPropValue =export type NotebookComponentProps = Record<string, NotebookPropValue>-export type NotebookTextBlockNode = {+/** A run of consecutive text-like blocks shares one card (see `getMarkdownNotebookVisualGroups`).+ * `startsGroup` opts a block out of the run above it, so it gets a card of its own: it is set when+ * the block was added as a node in its own right — the insert menu's "+", an MCP cell insert, a+ * block appended into the notebook — rather than typed as a continuation of the text before it.+ * Stored in the markdown as a second blank line before the block so the split survives a save.+ * Never set on the first block, which has no separator to widen and always starts a card. */+type NotebookBlockNodeBase = {id: string+ startsGroup?: boolean+}++export type NotebookTextBlockNode = NotebookBlockNodeBase & {type: 'paragraph' | 'heading' | 'blockquote'level?: 1 | 2 | 3 | 4 | 5 | 6/** A heading that is part of a blockquote: serialized with a `> ` prefix on every line. */@@ -55,8 +65,7 @@ export type NotebookListItem = {checked?: boolean}-export type NotebookListBlockNode = {- id: string+export type NotebookListBlockNode = NotebookBlockNodeBase & {type: 'list'ordered: booleanstart?: number@@ -71,8 +80,7 @@ export type NotebookTableCell = {children: NotebookInlineNode[]}-export type NotebookTableBlockNode = {- id: string+export type NotebookTableBlockNode = NotebookBlockNodeBase & {type: 'table'headers: NotebookTableCell[]rows: NotebookTableCell[][]@@ -88,16 +96,14 @@ export type NotebookCodeRefMark = {end: number}-export type NotebookCodeBlockNode = {- id: string+export type NotebookCodeBlockNode = NotebookBlockNodeBase & {type: 'code'language?: stringtext: stringrefs?: NotebookCodeRefMark[]}-export type NotebookComponentBlockNode = {- id: string+export type NotebookComponentBlockNode = NotebookBlockNodeBase & {type: 'component'tagName: stringprops: NotebookComponentPropsdiff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookEditorState.test.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookEditorState.test.tsindex a2353e95e988..7c786263e982 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookEditorState.test.ts+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookEditorState.test.ts@@ -276,7 +276,7 @@ Thinking...`)logic.actions.pasteAfterLastNode('Dropped text')}).toDispatchActions(['setLocalContent'])- expect(getMarkdownNotebookMarkdown(logic.values.localContent)).toEqual(`${BASE_MARKDOWN}\n\nDropped text`)+ expect(getMarkdownNotebookMarkdown(logic.values.localContent)).toEqual(`${BASE_MARKDOWN}\n\n\nDropped text`)})it.each([diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.tsindex 5d1dc77453db..285dd8bade49 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts@@ -57,9 +57,11 @@ describe('markdownNotebookV2', () => {'<Query query={{"kind":"SavedInsightNode","shortId":"abc123"}} />')- expect(getMarkdownNotebookMarkdown(nextContent)).toEqual(`# Activation--<Query query={{"kind":"SavedInsightNode","shortId":"abc123"}} />`)+ // Two blank lines: an appended block is a node of its own, not a continuation of the+ // card the notebook currently ends with.+ expect(getMarkdownNotebookMarkdown(nextContent)).toEqual(+ '# Activation\n\n\n<Query query={{"kind":"SavedInsightNode","shortId":"abc123"}} />'+ )})it('converts common legacy notebook nodes to markdown', () => {diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.tsindex f779608134cc..7ff1cf54d098 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts@@ -3,6 +3,7 @@ import {escapeInlineMarkdownText,escapeMarkdownBlockLines,makeEmptyParagraph,+ NOTEBOOK_BLOCK_SEPARATOR,parseMarkdownNotebook,sanitizeNotebookLinkHref,serializeMarkdownNotebook,@@ -121,8 +122,10 @@ export function appendMarkdownNotebookBlock(blockMarkdown: string): JSONContent {const markdown = getMarkdownNotebookMarkdown(content)+ // An appended block is a node in its own right, so it gets the wider separator rather than+ // folding into the card the notebook currently ends with.return buildMarkdownNotebookContent(- [markdown, blockMarkdown].filter((block) => block.trim()).join('\n\n'),+ [markdown, blockMarkdown].filter((block) => block.trim()).join(NOTEBOOK_BLOCK_SEPARATOR),getMarkdownNotebookNodeId(content))}diff --git a/services/mcp/src/tools/notebooks/addCell.ts b/services/mcp/src/tools/notebooks/addCell.tsindex 61e2904ebf9f..6b386dfa70d3 100644--- a/services/mcp/src/tools/notebooks/addCell.ts+++ b/services/mcp/src/tools/notebooks/addCell.ts@@ -72,6 +72,13 @@ export interface AddCellResult {run?: ShapedRunResult}+/**+ * One blank line separates two blocks of the same card in the notebook editor; a second one starts+ * a new card. Cells added here are nodes in their own right, so they are separated on both sides —+ * otherwise consecutive markdown cells land as one card (`startsGroup` in the editor's types.ts).+ */+const BLOCK_SEPARATOR = '\n\n\n'+function insertBlock(markdown: string, block: string, afterNodeId: string | undefined): string {const trimmed = markdown.replace(/\s+$/, '')if (afterNodeId) {@@ -79,9 +86,11 @@ function insertBlock(markdown: string, block: string, afterNodeId: string | undeif (!anchor) {throw new Error(`No cell with node_id ${afterNodeId} found to insert after.`)}- return `${markdown.slice(0, anchor.end)}\n\n${block}${markdown.slice(anchor.end)}`+ const rest = markdown.slice(anchor.end).replace(/^\n+/, '')+ const head = `${markdown.slice(0, anchor.end)}${BLOCK_SEPARATOR}${block}`+ return rest ? `${head}${BLOCK_SEPARATOR}${rest}` : `${head}\n`}- return trimmed ? `${trimmed}\n\n${block}\n` : `${block}\n`+ return trimmed ? `${trimmed}${BLOCK_SEPARATOR}${block}\n` : `${block}\n`}async function runAndWriteBack(diff --git a/services/mcp/tests/unit/notebook-cell-tools.test.ts b/services/mcp/tests/unit/notebook-cell-tools.test.tsindex 43402ce7de33..7d42083347b1 100644--- a/services/mcp/tests/unit/notebook-cell-tools.test.ts+++ b/services/mcp/tests/unit/notebook-cell-tools.test.ts@@ -169,11 +169,19 @@ describe('notebook cell tools', () => {cell_type: 'markdown',markdown: 'Some **notes**.',})+ await addCellHandler(context, {+ notebook_id: 'aBcD1234',+ cell_type: 'markdown',+ markdown: 'More notes.',+ })expect(result).toEqual({})- expect(state.saveBodies).toHaveLength(1)- expect(state.saveBodies[0].content.content[0].attrs.markdown).toContain('Some **notes**.')expect(state.runBodies).toHaveLength(0)+ // Each cell is a node of its own: one blank line would fold consecutive prose cells+ // into a single card in the editor, two keeps them separate.+ expect(state.saveBodies[1].content.content[0].attrs.markdown).toBe(+ '# Doc\n\n\nSome **notes**.\n\n\nMore notes.\n'+ )})it('add component cell inserts the tag with a minted nodeId and no run', async () => {