: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): let add-cell place a cell after a markdown block (#102014)
Sinan Kucukkoseler8876463ebfe8
diff --git a/products/notebooks/backend/test/test_sql_v2_state.py b/products/notebooks/backend/test/test_sql_v2_state.pyindex ee483b7f0032..bfad37c3df6d 100644--- a/products/notebooks/backend/test/test_sql_v2_state.py+++ b/products/notebooks/backend/test/test_sql_v2_state.py@@ -182,9 +182,18 @@ class TestMarkdownBlockSpans(SimpleTestCase):"Closing paragraph.")- def test_every_block_span_slices_back_to_its_source(self) -> None:- blocks = list(iter_markdown_blocks(self.MARKDOWN))- assert [self.MARKDOWN[block.start : block.end] for block in blocks] == [block.source for block in blocks]+ @parameterized.expand(+ [+ ("no_terminator", ""),+ ("newline", "\n"),+ ("crlf", "\r\n"),+ ]+ )+ def test_every_block_span_slices_back_to_its_source(self, _name: str, ending: str) -> None:+ markdown = self.MARKDOWN + ending+ blocks = list(iter_markdown_blocks(markdown))+ assert [markdown[block.start : block.end] for block in blocks] == [block.source for block in blocks]+ assert blocks[-1].source == "Closing paragraph."def test_a_fenced_block_stays_whole_across_its_blank_line(self) -> None:sources = [block.source for block in iter_markdown_blocks(self.MARKDOWN)]diff --git a/products/notebooks/backend/util.py b/products/notebooks/backend/util.pyindex 4e3378263dcb..da54c7b6ff1a 100644--- a/products/notebooks/backend/util.py+++ b/products/notebooks/backend/util.py@@ -396,9 +396,10 @@ def iter_markdown_blocks(markdown: str, max_prose_blocks: int | None = None) ->return widthdef block_source(start_line: int, end_line: int) -> str:- width = span_code_points(start_line, end_line)- closing = _markdown_terminator_width(markdown, code_points + width - 1)- return markdown[code_points : code_points + width - closing]+ # The last line of a document often has no terminator, so one looked up from the end of+ # the span would be a character of the block itself.+ width = span_code_points(start_line, end_line - 1) + len(lines[end_line - 1])+ return markdown[code_points : code_points + width]def consume(start_line: int, end_line: int) -> None:nonlocal code_points, utf16diff --git a/services/mcp/src/tools/notebooks/addCell.ts b/services/mcp/src/tools/notebooks/addCell.tsindex 07bae047c812..88079e2e76d0 100644--- a/services/mcp/src/tools/notebooks/addCell.ts+++ b/services/mcp/src/tools/notebooks/addCell.ts@@ -75,7 +75,9 @@ const AddCellInputSchema = zafter_node_id: z.string().optional()- .describe('Insert after this cell (node_id from a previous add). Defaults to the end of the document.'),+ .describe(+ 'Insert after this block: any node_id notebooks-get returns, a markdown block included. Defaults to the end of the document. A markdown block id comes from the text, so pass one from the read you are acting on.'+ ),}).strict()@@ -94,8 +96,92 @@ export interface AddCellResult {*/const BLOCK_SEPARATOR = '\n\n\n'-function insertBlock(markdown: string, block: string, afterNodeId: string | undefined): string {+/**+ * A prose block resolved through the state endpoint, which owns the block grammar this side+ * cannot reproduce. `source` re-locates the block when an edit elsewhere has moved the offsets.+ */+interface ProseAnchor {+ nodeId: string+ source: string+ start: number+ end: number+ /** Notebook version the span was read at. The span is exact for that version only. */+ version: number | null+}++// Notebook markdown keeps CRLF and lone-CR line endings, and the backend walk splits on all three.+// The lookahead keeps the two halves of a CRLF from counting as two line breaks.+const EOL = '(?:\\r\\n|\\r(?!\\n)|\\n)'++/**+ * Whether the text at `index` stands as a block of its own, rather than sitting inside a longer+ * one. A blank line separates two blocks, so a match with one on each side covers a whole block.+ *+ * Deliberately strict. A layout this does not recognize is refused and the caller reads again,+ * which costs a round trip. Accepting a match inside a longer paragraph would split that+ * paragraph around the inserted cell, which costs the reader their text.+ */+const BLOCK_START_BOUNDARY = new RegExp(`(?:^|${EOL}[ \\t]*${EOL}[ \\t]*)$`)+const BLOCK_END_BOUNDARY = new RegExp(`^(?:[ \\t]*${EOL}[ \\t]*${EOL}|[ \\t]*${EOL}?$)`)++function isWholeBlockAt(markdown: string, index: number, source: string): boolean {+ return (+ BLOCK_START_BOUNDARY.test(markdown.slice(0, index)) &&+ BLOCK_END_BOUNDARY.test(markdown.slice(index + source.length))+ )+}++/**+ * Where the anchor block ends in `markdown`, by the offsets the read reported, or by its text+ * when an edit elsewhere has moved them.+ *+ * Refuses a source that now appears more than once rather than picking one: the insert would+ * land on a block the caller never saw. The same refusal guards a prose edit in updateCell.ts.+ */+function locateProseAnchorEnd(markdown: string, anchor: ProseAnchor, version: number): number {+ // The backend's grammar set this span, so it is trusted only for the version it was read at.+ // In a later version the same offsets can still hold the same text while the block has grown+ // past them, and an insert at the old end would split the block.+ if (version === anchor.version && markdown.slice(anchor.start, anchor.end) === anchor.source) {+ return anchor.end+ }+ const matches: number[] = []+ for (+ let index = markdown.indexOf(anchor.source);+ index !== -1;+ index = markdown.indexOf(anchor.source, index + 1)+ ) {+ if (isWholeBlockAt(markdown, index, anchor.source)) {+ matches.push(index)+ }+ }+ if (matches.length === 0) {+ throw new Error(+ `Block ${anchor.nodeId} is no longer a block of its own in notebook, so a cell cannot be placed after it. Read the notebook again with notebooks-get and retry with the id it returns.`+ )+ }+ if (matches.length > 1) {+ throw new Error(+ `Block ${anchor.nodeId} now matches more than one block, so it cannot name one of them. Read the notebook again with notebooks-get and retry with the id it returns.`+ )+ }+ return matches[0]! + anchor.source.length+}++function insertBlock(+ markdown: string,+ block: string,+ afterNodeId: string | undefined,+ proseAnchor: ProseAnchor | undefined,+ version: number+): string {const trimmed = markdown.replace(/\s+$/, '')+ if (proseAnchor) {+ const end = locateProseAnchorEnd(markdown, proseAnchor, version)+ const rest = markdown.slice(end).replace(/^[\r\n]+/, '')+ const head = `${markdown.slice(0, end)}${BLOCK_SEPARATOR}${block}`+ return rest ? `${head}${BLOCK_SEPARATOR}${rest}` : `${head}\n`+ }if (afterNodeId) {const anchor = findCellTag(markdown, afterNodeId)if (!anchor) {@@ -108,6 +194,51 @@ function insertBlock(markdown: string, block: string, afterNodeId: string | undereturn trimmed ? `${trimmed}${BLOCK_SEPARATOR}${block}\n` : `${block}\n`}+/**+ * Resolve `after_node_id` to a prose anchor, or to `undefined` when a cell tag already carries+ * the id and `insertBlock` can find it in the markdown on its own.+ *+ * A prose id is derived from block text, so it resolves only against the read that produced it.+ * Only the state endpoint walks prose, so a miss in the tag scan goes there rather than failing.+ */+async function resolveInsertAnchor(+ context: Context,+ notebookId: string,+ afterNodeId: string | undefined+): Promise<ProseAnchor | undefined> {+ if (!afterNodeId) {+ return undefined+ }+ const { markdown } = await fetchMarkdownNotebook(context, notebookId)+ if (findCellTag(markdown, afterNodeId)) {+ return undefined+ }++ const projectId = await context.stateManager.getProjectId()+ const state = await context.api.request<{ version: number | null; cells: Schemas.NotebookCellState[] }>({+ method: 'GET',+ path: `${notebookPathFor(projectId, notebookId)}sql_v2/state/`,+ })+ const matches = state.cells.filter((cell) => cell.node_id === afterNodeId)+ if (matches.length === 0) {+ throw new Error(+ `No block with node_id ${afterNodeId} in notebook ${notebookId} to insert after. Read the current ids with notebooks-get; an insight short id is not one of them.`+ )+ }+ if (matches.length > 1) {+ throw new Error(+ `Block ${afterNodeId} names ${matches.length} blocks in notebook ${notebookId}, so it cannot name one of them. Read the notebook again with notebooks-get.`+ )+ }+ const block = matches[0]!+ if (block.cell_type !== 'markdown') {+ throw new Error(+ `Cell ${afterNodeId} is a ${block.cell_type} cell but carries no tag identity, so a cell cannot be placed after it. Insert at the end by omitting after_node_id.`+ )+ }+ return { nodeId: afterNodeId, source: block.code, start: block.start, end: block.end, version: state.version }+}+async function runAndWriteBack(context: Context,notebookId: string,@@ -202,6 +333,9 @@ export const addCellHandler: ToolBase<typeof NotebooksAddCellSchema, AddCellResu}const title = params.title?.trim() || undefined+ // Resolved before any branch, so every cell type places after prose the same way and a bad+ // anchor fails before a cell is created or a query runs.+ const proseAnchor = await resolveInsertAnchor(context, params.notebook_id, params.after_node_id)if (params.cell_type === 'markdown') {if (title) {@@ -209,8 +343,8 @@ export const addCellHandler: ToolBase<typeof NotebooksAddCellSchema, AddCellResu'A markdown cell has no header to title — put the heading in the markdown itself (e.g. "## Weekly signups").')}- await applyMarkdownEdit(context, params.notebook_id, (markdown) =>- insertBlock(markdown, params.markdown!.trim(), params.after_node_id)+ await applyMarkdownEdit(context, params.notebook_id, (markdown, version) =>+ insertBlock(markdown, params.markdown!.trim(), params.after_node_id, proseAnchor, version))return {}}@@ -223,8 +357,8 @@ export const addCellHandler: ToolBase<typeof NotebooksAddCellSchema, AddCellResutitle,query: { kind: 'SavedInsightNode', shortId: params.insight_short_id },})- await applyMarkdownEdit(context, params.notebook_id, (markdown) =>- insertBlock(markdown, tag, params.after_node_id)+ await applyMarkdownEdit(context, params.notebook_id, (markdown, version) =>+ insertBlock(markdown, tag, params.after_node_id, proseAnchor, version))return { node_id: nodeId }}@@ -232,8 +366,8 @@ export const addCellHandler: ToolBase<typeof NotebooksAddCellSchema, AddCellResuif (params.cell_type === 'component') {// `title` last only when set, so a component that carries its own title prop keeps it.const tag = buildCellTag(params.tag_name!, { ...params.props, nodeId, ...(title ? { title } : {}) })- await applyMarkdownEdit(context, params.notebook_id, (markdown) =>- insertBlock(markdown, tag, params.after_node_id)+ await applyMarkdownEdit(context, params.notebook_id, (markdown, version) =>+ insertBlock(markdown, tag, params.after_node_id, proseAnchor, version))return { node_id: nodeId }}@@ -252,8 +386,8 @@ export const addCellHandler: ToolBase<typeof NotebooksAddCellSchema, AddCellResu// The save response carries the notebook as it stood when the save committed, so it holds a// variable edit that landed after the read above. The run binds those values to stay in step// with what the notebook now declares.- const { notebook, markdown } = await applyMarkdownEdit(context, params.notebook_id, (current) =>- insertBlock(current, tag, params.after_node_id)+ const { notebook, markdown } = await applyMarkdownEdit(context, params.notebook_id, (current, version) =>+ insertBlock(current, tag, params.after_node_id, proseAnchor, version))const run = await runAndWriteBack(context,diff --git a/services/mcp/src/tools/notebooks/markdownDoc.ts b/services/mcp/src/tools/notebooks/markdownDoc.tsindex 4f308d534d1e..551a12e26830 100644--- a/services/mcp/src/tools/notebooks/markdownDoc.ts+++ b/services/mcp/src/tools/notebooks/markdownDoc.ts@@ -96,12 +96,12 @@ export async function saveMarkdown(export async function applyMarkdownEdit(context: Context,shortId: string,- transform: (markdown: string) => string+ transform: (markdown: string, version: number) => string): Promise<{ notebook: Schemas.Notebook; markdown: string }> {let lastError: unknownfor (let attempt = 0; attempt < 2; attempt++) {const state = await fetchMarkdownNotebook(context, shortId)- const nextMarkdown = transform(state.markdown)+ const nextMarkdown = transform(state.markdown, state.version)try {const notebook = await saveMarkdown(context, state, nextMarkdown)return { notebook, markdown: nextMarkdown }diff --git a/services/mcp/tests/unit/notebook-cell-tools.test.ts b/services/mcp/tests/unit/notebook-cell-tools.test.tsindex a3aa0dd4419c..3b150498ccc5 100644--- a/services/mcp/tests/unit/notebook-cell-tools.test.ts+++ b/services/mcp/tests/unit/notebook-cell-tools.test.ts@@ -665,6 +665,122 @@ describe('notebook cell tools', () => {],})})+ describe('markdown block anchors', () => {+ const DOC = '# Doc\n\n\nFirst paragraph.\n\n\nSecond paragraph.\n'+ // Span of "First paragraph." in DOC, as the backend's block walk reports it.+ const FIRST = { node_id: 'mdp-abc-0', cell_type: 'markdown', code: 'First paragraph.', start: 8, end: 24 }++ it('places a cell directly after the addressed paragraph', async () => {+ const state = makeState(DOC)+ state.stateCells = [FIRST]+ state.runStatusResponses.push(DONE_STATUS)+ const context = createMockContext(state)++ const result = await addCellHandler(context, {+ notebook_id: 'aBcD1234',+ cell_type: 'sql',+ code: 'select 1',+ after_node_id: FIRST.node_id,+ })++ const inserted = state.saveBodies[0].content.content[0].attrs.markdown+ expect(inserted.indexOf('<SQLV2 ')).toBeGreaterThan(inserted.indexOf('First paragraph.'))+ expect(inserted.indexOf('<SQLV2 ')).toBeLessThan(inserted.indexOf('Second paragraph.'))+ expect(inserted).toContain(`nodeId="${result.node_id}"`)+ })++ it.each([+ { label: 'LF', doc: DOC },+ { label: 'CRLF', doc: DOC.replaceAll('\n', '\r\n') },+ ])('re-locates the paragraph by its text in a $label document', async ({ doc }) => {+ const state = makeState(doc)+ // An edit above the anchor shifts every later span, so the offsets the caller read+ // point into the wrong place while the block itself is untouched.+ state.stateCells = [{ ...FIRST, start: FIRST.start + 12, end: FIRST.end + 12 }]+ const context = createMockContext(state)++ await addCellHandler(context, {+ notebook_id: 'aBcD1234',+ cell_type: 'markdown',+ markdown: 'Inserted note.',+ after_node_id: FIRST.node_id,+ })++ const inserted = state.saveBodies[0].content.content[0].attrs.markdown+ const [before, after] = doc.split(/(?<=First paragraph\.)[\r\n]+/)+ expect(inserted).toBe(`${before}\n\n\nInserted note.\n\n\n${after}`)+ })++ it.each([+ {+ label: 'an id that names no block',+ cells: [],+ params: { after_node_id: 'mdp-missing-0' },+ expected: /No block with node_id mdp-missing-0/,+ },+ {+ label: 'an id that names two blocks that read the same',+ cells: [FIRST, { ...FIRST, start: 27, end: 43 }],+ params: { after_node_id: FIRST.node_id },+ expected: /names 2 blocks/,+ },+ ])('refuses $label and writes nothing', async ({ cells, params, expected }) => {+ const state = makeState(DOC)+ state.stateCells = cells+ const context = createMockContext(state)++ await expect(+ addCellHandler(context, {+ notebook_id: 'aBcD1234',+ cell_type: 'markdown',+ markdown: 'Inserted note.',+ ...params,+ })+ ).rejects.toThrow(expected)+ expect(state.saveBodies).toHaveLength(0)+ })++ // Relocation used to accept any unique occurrence of the source, so a paragraph that+ // grew around the old text took the insert into its middle and split it in two.+ it.each([+ { label: 'moved offsets', doc: '# Doc\n\n\nUpdated First paragraph. Now longer.\n' },+ // The text grew on the same line after the state read, so the old span still slices+ // back to the source. Only the notebook version shows that the span is stale.+ { label: 'the same offsets in a newer version', doc: '# Doc\n\n\nFirst paragraph. Now longer.\n' },+ ])('refuses a source that survives only inside a longer paragraph, at $label', async ({ doc }) => {+ const state = makeState(doc)+ state.stateCells = [FIRST]+ state.stateVersion = state.version - 1+ const context = createMockContext(state)++ await expect(+ addCellHandler(context, {+ notebook_id: 'aBcD1234',+ cell_type: 'markdown',+ markdown: 'Inserted note.',+ after_node_id: FIRST.node_id,+ })+ ).rejects.toThrow(/no longer a block of its own/)+ expect(state.saveBodies).toHaveLength(0)+ })++ it('refuses a paragraph that vanished between the read and the write', async () => {+ const state = makeState('# Doc\n\n\nSecond paragraph.\n')+ state.stateCells = [FIRST]+ const context = createMockContext(state)++ await expect(+ addCellHandler(context, {+ notebook_id: 'aBcD1234',+ cell_type: 'markdown',+ markdown: 'Inserted note.',+ after_node_id: FIRST.node_id,+ })+ ).rejects.toThrow(/no longer a block of its own/)+ expect(state.saveBodies).toHaveLength(0)+ })+ })+describe('markdown cells', () => {const DOC = ['# Title', '', 'First paragraph.', '', 'Second paragraph.'].join('\n')// Spans of "First paragraph." in DOC, as the backend reports them.