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.

feat(notebooks): give a markdown block a stored id (#102015)

Sinan Kucukkoseler9d7c676fc306
diff --git a/frontend/src/lib/components/MarkdownNotebook/markdown.ts b/frontend/src/lib/components/MarkdownNotebook/markdown.ts
index e9b80b89d977..96d1e6aafa31 100644
--- a/frontend/src/lib/components/MarkdownNotebook/markdown.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/markdown.ts
@@ -80,6 +80,31 @@ const EMPTY_PARAGRAPH_MARKDOWN = ' '
* one lands as its own node. */
export const NOTEBOOK_BLOCK_SEPARATOR = '\n\n\n'
const NOTEBOOK_BLOCK_JOINER = '\n\n'
+/**
+ * A block id the document stores, rather than one derived from the block's content on every
+ * parse. Only these are written back as an anchor, so a document that never carried one
+ * serializes byte for byte as it was read.
+ */
+export const STORED_NODE_ID_PREFIX = 'phb-'
+/**
+ * A stored block id, written on its own line above the block it names.
+ *
+ * A comment is the only place a paragraph can carry an id: the document is markdown, and prose
+ * has no attribute to hold one. It renders nowhere, so a reader never sees it.
+ *
+ * The prefix is part of the pattern, so this matches exactly what the serializer writes back.
+ * A wider pattern would eat an authorial `<!--ph:note-->` as an anchor and drop it on the next
+ * save, because the serializer writes no anchor for an id it did not store.
+ */
+const NODE_ANCHOR_REGEX = /^<!--ph:(phb-[A-Za-z0-9._-]{1,124})-->$/
+
+export function isStoredNodeId(id: string | undefined): boolean {
+ return !!id && id.startsWith(STORED_NODE_ID_PREFIX)
+}
+
+export function serializeNodeAnchor(id: string): string {
+ return `<!--ph:${id}-->\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([
@@ -128,7 +153,19 @@ export function parseMarkdownNotebook(markdown: string | null | undefined): Note
const nodes: NotebookBlockNode[] = []
const errors: NotebookParseError[] = []
const occurrences = new Map<string, number>()
+ let pendingAnchorId: string | null = null
const pushParsedNode = (node: NotebookBlockNode): void => {
+ const anchorId = pendingAnchorId
+ pendingAnchorId = null
+ // A tag's own `nodeId` prop wins over an anchor above it, matching the backend walk in
+ // products/notebooks/backend/util.py. Taking the anchor here would address one cell by
+ // two different ids, one per layer.
+ const carriesOwnId = node.type === 'component' && typeof node.props.nodeId === 'string' && !!node.props.nodeId
+ if (anchorId !== null && !carriesOwnId) {
+ node.id = anchorId
+ nodes.push(node)
+ return
+ }
const fingerprint = getNodeFingerprint(node)
const occurrence = occurrences.get(fingerprint) ?? 0
occurrences.set(fingerprint, occurrence + 1)
@@ -154,11 +191,25 @@ export function parseMarkdownNotebook(markdown: string | null | undefined): Note
}
if (!line.trim()) {
+ // An anchor names only the block on the line below it. Text removed from under an
+ // anchor leaves the anchor behind, and carried over a blank line it would hand the id
+ // to the next block, so an edit by that id would reach a block its caller never read.
+ pendingAnchorId = null
blankLinesBeforeBlock += 1
lineIndex += 1
continue
}
+ // Read before the block scan, so `parseCommentBlock` never takes an anchor for an
+ // authorial note. The blank-line count is left alone: the anchor sits inside the
+ // separator that decides the card boundary, and must not close it.
+ const anchorMatch = NODE_ANCHOR_REGEX.exec(line.trim())
+ if (anchorMatch) {
+ pendingAnchorId = anchorMatch[1]!
+ lineIndex += 1
+ continue
+ }
+
const result = parseBlock(lines, lineIndex)
if (result.error) {
errors.push(result.error)
@@ -184,7 +235,10 @@ export function serializeMarkdownNotebook(document: NotebookDocument): string {
const shouldPreserveEmptyParagraphs = document.nodes.length > 1
const serialized = document.nodes
.map((node, index) => {
- const block = serializeDocumentNode(node, shouldPreserveEmptyParagraphs)
+ const body = serializeDocumentNode(node, shouldPreserveEmptyParagraphs)
+ // A derived id is rebuilt from the block on the next parse, so writing it back would
+ // rewrite every document the editor opens and break `serialize(parse(md)) === md`.
+ const block = isStoredNodeId(node.id) ? `${serializeNodeAnchor(node.id)}${body}` : body
if (index === 0) {
return block
}
diff --git a/frontend/src/lib/components/MarkdownNotebook/markdownRoundTrip.test.ts b/frontend/src/lib/components/MarkdownNotebook/markdownRoundTrip.test.ts
index eb8c0b7288f4..e94a8414d586 100644
--- a/frontend/src/lib/components/MarkdownNotebook/markdownRoundTrip.test.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/markdownRoundTrip.test.ts
@@ -648,6 +648,76 @@ describe('markdown round trip', () => {
})
})
+ describe('stored block ids', () => {
+ it('reads an anchor as the block id and makes no node for it', () => {
+ const document = parseMarkdownNotebook('<!--ph:phb-abc-->\nA paragraph.')
+
+ expect(document.nodes.map((node) => node.type)).toEqual(['paragraph'])
+ expect(document.nodes[0].id).toEqual('phb-abc')
+ })
+
+ it('writes a stored id back, so the block keeps it across an edit to its text', () => {
+ const document = parseMarkdownNotebook('<!--ph:phb-abc-->\nA paragraph.')
+ const edited: NotebookDocument = {
+ ...document,
+ nodes: [{ ...document.nodes[0], children: [text('A rewritten paragraph.')] } as NotebookBlockNode],
+ }
+
+ const serialized = serializeMarkdownNotebook(edited)
+ expect(serialized).toEqual('<!--ph:phb-abc-->\nA rewritten paragraph.')
+ expect(parseMarkdownNotebook(serialized).nodes[0].id).toEqual('phb-abc')
+ })
+
+ // A derived id is rebuilt from the block on every parse. Written back, it would rewrite
+ // every document the editor opens, and the whole-document diff would reach the merge.
+ it('writes no anchor for a derived id, so an unanchored document is unchanged', () => {
+ const markdown = '# Title\n\nA paragraph.\n\nAnother paragraph.'
+ expect(serializeMarkdownNotebook(parseMarkdownNotebook(markdown))).toEqual(markdown)
+ })
+
+ // A three-way markdown merge can copy an anchor line onto a second block. Two blocks
+ // claiming one id would send an edit by id to whichever the lookup reached first.
+ it('refuses to let a duplicated anchor name two blocks', () => {
+ const document = parseMarkdownNotebook('<!--ph:phb-abc-->\nFirst.\n\n<!--ph:phb-abc-->\nSecond.')
+
+ const ids = document.nodes.map((node) => node.id)
+ expect(ids[0]).toEqual('phb-abc')
+ expect(new Set(ids).size).toEqual(2)
+ })
+
+ // The serializer writes an anchor back only for a stored id. A parser that consumed a
+ // wider set would eat an authorial note and drop it on the next save.
+ it('leaves a comment that is not a stored id as a comment', () => {
+ const markdown = '<!--ph:note-->\n\nA paragraph.'
+
+ const document = parseMarkdownNotebook(markdown)
+
+ expect(document.nodes.map((node) => node.type)).toEqual(['component', 'paragraph'])
+ // The comment serializer pads the delimiters, so the note comes back spaced.
+ expect(serializeMarkdownNotebook(document)).toContain('ph:note')
+ })
+
+ it('gives a tag its own nodeId prop rather than an anchor above it', () => {
+ const document = parseMarkdownNotebook('<!--ph:phb-outer-->\n<SQLV2 nodeId="s1" code="select 1" />')
+
+ expect(document.nodes[0].id).not.toEqual('phb-outer')
+ })
+
+ it('gives a left-behind anchor to no block', () => {
+ const document = parseMarkdownNotebook('<!--ph:phb-abc-->\n\n\nThe next paragraph.')
+
+ expect(document.nodes.map((node) => getNodeText(node))).toEqual(['The next paragraph.'])
+ expect(document.nodes[0].id).not.toEqual('phb-abc')
+ })
+
+ it('keeps an anchored block out of the paragraph above it', () => {
+ const document = parseMarkdownNotebook('First.\n<!--ph:phb-abc-->\nSecond.')
+
+ expect(document.nodes.map((node) => getNodeText(node))).toEqual(['First.', 'Second.'])
+ expect(document.nodes[1].id).toEqual('phb-abc')
+ })
+ })
+
describe('discussion comment tags', () => {
it('round-trips a discussion comment as a JSX tag, not an html comment', () => {
const markdown = '<Comment ref="banana" replies={[{"id":"r1","author":"Ann","text":"Looks off"}]} />'
diff --git a/products/notebooks/backend/test/test_sql_v2_state.py b/products/notebooks/backend/test/test_sql_v2_state.py
index bfad37c3df6d..24e2f0c75419 100644
--- a/products/notebooks/backend/test/test_sql_v2_state.py
+++ b/products/notebooks/backend/test/test_sql_v2_state.py
@@ -177,6 +177,7 @@ class TestMarkdownBlockSpans(SimpleTestCase):
MARKDOWN = (
"# Title\n\n"
"Some prose.\nA second line.\n\n"
+ "<!--ph:phb-anchored-->\nAn anchored paragraph.\n\n"
'<SQLV2 nodeId="s1" code="select 1" returnVariable="df" />\n\n'
"```python\nx = 1\n\ny = 2\n```\n\n"
"Closing paragraph."
@@ -231,6 +232,39 @@ class TestMarkdownBlockSpans(SimpleTestCase):
blocks = list(iter_markdown_blocks("Same text.\n\nSame text."))
assert len({block.node_id for block in blocks}) == 2
+ def test_an_anchored_block_keeps_its_id_when_its_text_changes(self) -> None:
+ edited = self.MARKDOWN.replace("An anchored paragraph.", "A rewritten paragraph.")
+ before = {block.node_id for block in iter_markdown_blocks(self.MARKDOWN)}
+ after = {block.node_id for block in iter_markdown_blocks(edited)}
+ assert "phb-anchored" in before & after
+
+ def test_a_tag_prop_id_wins_over_an_anchor_above_it(self) -> None:
+ markdown = '<!--ph:phb-outer-->\n<SQLV2 nodeId="s1" code="select 1" returnVariable="df" />'
+ blocks = list(iter_markdown_blocks(markdown))
+ assert [block.node_id for block in blocks] == ["s1"]
+
+ def test_a_repeated_anchor_names_only_the_first_block(self) -> None:
+ markdown = "<!--ph:phb-abc-->\nFirst.\n\n<!--ph:phb-abc-->\nSecond."
+ node_ids = [block.node_id for block in iter_markdown_blocks(markdown)]
+ assert node_ids[0] == "phb-abc"
+ assert len(set(node_ids)) == 2
+
+ def test_a_left_behind_anchor_names_no_block(self) -> None:
+ blocks = list(iter_markdown_blocks("<!--ph:phb-abc-->\n\n\nThe next paragraph.\n"))
+ assert [block.source for block in blocks] == ["The next paragraph."]
+ assert blocks[0].node_id != "phb-abc"
+
+ def test_a_comment_that_is_not_a_stored_id_is_not_an_anchor(self) -> None:
+ blocks = list(iter_markdown_blocks("<!--ph:note-->\n\nA paragraph."))
+ assert [block.node_id for block in blocks] != ["note"]
+ assert blocks[0].source == "<!--ph:note-->"
+
+ def test_an_anchor_inside_a_fence_is_not_read_as_one(self) -> None:
+ markdown = "```\n<!--ph:phb-example-->\n```\n\nParagraph."
+ blocks = list(iter_markdown_blocks(markdown))
+ assert [block.node_id for block in blocks] != ["phb-example"]
+ assert blocks[0].source == "```\n<!--ph:phb-example-->\n```"
+
class TestCellCountLimit(SimpleTestCase):
@parameterized.expand(
diff --git a/products/notebooks/backend/util.py b/products/notebooks/backend/util.py
index da54c7b6ff1a..60f134a9bf3e 100644
--- a/products/notebooks/backend/util.py
+++ b/products/notebooks/backend/util.py
@@ -365,9 +365,9 @@ class MarkdownBlock:
def iter_markdown_blocks(markdown: str, max_prose_blocks: int | None = None) -> Iterator[MarkdownBlock]:
"""Walk every block of a markdown notebook, prose included.
- Prose has no durable identity in the document, so its `node_id` is derived from the block
- text. The id therefore changes when the block changes, which is why a caller must resolve
- an id against the same read it edits.
+ A block whose document carries an anchor above it takes that stored id, which survives an
+ edit to the block. A block without one falls back to an id derived from its own content, so
+ the id changes when the block changes and a caller must resolve it against the read it edits.
`max_prose_blocks` bounds how many prose blocks this builds. A save accepts a body up to
`DATA_UPLOAD_MAX_MEMORY_SIZE`, and a body of that size holds millions of one-character
@@ -379,6 +379,22 @@ def iter_markdown_blocks(markdown: str, max_prose_blocks: int | None = None) ->
occurrences: dict[str, int] = {}
line_index = 0
prose_built = 0
+ pending_anchor_id: str | None = None
+ # An anchor names one block. A second copy of one reaches the document through a three-way
+ # markdown merge, and two blocks under one id leave neither addressable, because every cell
+ # tool refuses an id that names more than one. The first keeps it; the rest fall back to a
+ # derived id. `ensureUniqueNodeIds` does the same in the editor.
+ claimed_anchor_ids: set[str] = set()
+
+ def claim_anchor_id() -> str | None:
+ nonlocal pending_anchor_id
+ anchor_id = pending_anchor_id
+ pending_anchor_id = None
+ if anchor_id is None or anchor_id in claimed_anchor_ids:
+ return None
+ claimed_anchor_ids.add(anchor_id)
+ return anchor_id
+
# Two counters over one walk: code points to slice the document Python holds, UTF-16 units
# to report, because the caller slices in UTF-16. Each advances once per character.
code_points = 0
@@ -409,6 +425,20 @@ def iter_markdown_blocks(markdown: str, max_prose_blocks: int | None = None) ->
while line_index < len(lines):
if not lines[line_index].strip():
+ # An anchor names only the block on the line below it. Text removed from under an
+ # anchor leaves the anchor behind, and carried over a blank line it would hand the id
+ # to the next block, so an edit by that id would reach a block its caller never read.
+ pending_anchor_id = None
+ consume(line_index, line_index + 1)
+ line_index += 1
+ continue
+
+ # Read before the fence and tag scans, so an anchor never becomes a block of its own and
+ # its span never joins the block it names. A fenced block is consumed whole below, so an
+ # anchor written as an example inside one is never seen here.
+ anchor_match = _MARKDOWN_NODE_ANCHOR_REGEX.match(lines[line_index].strip())
+ if anchor_match:
+ pending_anchor_id = anchor_match.group(1)
consume(line_index, line_index + 1)
line_index += 1
continue
@@ -417,7 +447,10 @@ def iter_markdown_blocks(markdown: str, max_prose_blocks: int | None = None) ->
end_line_index = _get_markdown_code_block_end(lines, line_index)
if prose_budget_left():
prose_built += 1
- yield _build_markdown_prose_block(block_source(line_index, end_line_index), utf16, occurrences)
+ yield _build_markdown_prose_block(
+ block_source(line_index, end_line_index), utf16, occurrences, claim_anchor_id()
+ )
+ pending_anchor_id = None
consume(line_index, end_line_index)
line_index = end_line_index
continue
@@ -430,7 +463,7 @@ def iter_markdown_blocks(markdown: str, max_prose_blocks: int | None = None) ->
if component is not None:
tag_name, raw, next_line_index = component
yield _build_markdown_component_block(
- tag_name, raw, block_source(line_index, next_line_index), utf16, occurrences
+ tag_name, raw, block_source(line_index, next_line_index), utf16, occurrences, claim_anchor_id()
)
consume(line_index, next_line_index)
line_index = next_line_index
@@ -441,7 +474,10 @@ def iter_markdown_blocks(markdown: str, max_prose_blocks: int | None = None) ->
end_line_index += 1
if prose_budget_left():
prose_built += 1
- yield _build_markdown_prose_block(block_source(line_index, end_line_index), utf16, occurrences)
+ yield _build_markdown_prose_block(
+ block_source(line_index, end_line_index), utf16, occurrences, claim_anchor_id()
+ )
+ pending_anchor_id = None
consume(line_index, end_line_index)
line_index = end_line_index
@@ -450,6 +486,10 @@ def _continues_markdown_prose_block(lines: list[str], line_index: int) -> bool:
stripped = lines[line_index].strip()
if not stripped or stripped.startswith("```"):
return False
+ # An anchor names the block below it. Absorbed into the paragraph above, it would sit inside
+ # that block's reported source, and a caller slicing the span back would not match it.
+ if _MARKDOWN_NODE_ANCHOR_REGEX.match(stripped):
+ return False
return not _opens_markdown_component_block(lines, line_index)
@@ -466,6 +506,17 @@ def _opens_markdown_component_block(lines: list[str], line_index: int) -> bool:
return _read_markdown_component_block(lines, line_index) is not None
+_MARKDOWN_NODE_ANCHOR_REGEX = re.compile(r"^<!--ph:(phb-[A-Za-z0-9._-]{1,124})-->$")
+"""A block id the document stores, written on its own line above the block it names.
+
+Mirrors `NODE_ANCHOR_REGEX` in frontend/src/lib/components/MarkdownNotebook/markdown.ts,
+prefix included. A wider pattern here would read an authorial `<!--ph:note-->` as an anchor
+that the editor reads as a comment, and the two layers would disagree on the block list.
+
+A paragraph has no attribute to carry an id, so a comment is the only place one fits, and it
+renders nowhere.
+"""
+
_MARKDOWN_LINE_SPLIT_REGEX = re.compile(r"\r\n|\r|\n")
@@ -497,14 +548,16 @@ def _utf16_length(text: str) -> int:
return len(text) + sum(1 for character in text if ord(character) > 0xFFFF)
-def _build_markdown_prose_block(source: str, start: int, occurrences: dict[str, int]) -> MarkdownBlock:
+def _build_markdown_prose_block(
+ source: str, start: int, occurrences: dict[str, int], anchor_id: str | None = None
+) -> MarkdownBlock:
occurrence = occurrences.get(source, 0)
occurrences[source] = occurrence + 1
return MarkdownBlock(
kind="prose",
tag_name=None,
- node_id=_create_stable_markdown_prose_id(source, occurrence),
- explicit_node_id=None,
+ node_id=anchor_id or _create_stable_markdown_prose_id(source, occurrence),
+ explicit_node_id=anchor_id,
source=source,
start=start,
end=start + _utf16_length(source),
@@ -517,6 +570,7 @@ def _build_markdown_component_block(
source: str,
start: int,
occurrences: dict[str, int],
+ anchor_id: str | None = None,
) -> MarkdownBlock:
props = _parse_markdown_component_props(raw)
fingerprint = _get_markdown_component_fingerprint(tag_name, props)
@@ -524,6 +578,9 @@ def _build_markdown_component_block(
occurrences[fingerprint] = occurrence + 1
explicit_node_id = props.get("nodeId")
explicit_node_id = explicit_node_id if isinstance(explicit_node_id, str) and explicit_node_id else None
+ # The tag's own prop wins over an anchor above it: a cell added over MCP carries its id
+ # there, and the editor writes no anchor for a tag that already has one.
+ explicit_node_id = explicit_node_id or anchor_id
return MarkdownBlock(
kind="component",
tag_name=tag_name,
diff --git a/services/mcp/src/tools/notebooks/addCell.ts b/services/mcp/src/tools/notebooks/addCell.ts
index 88079e2e76d0..f24bc5bc490b 100644
--- a/services/mcp/src/tools/notebooks/addCell.ts
+++ b/services/mcp/src/tools/notebooks/addCell.ts
@@ -96,6 +96,21 @@ export interface AddCellResult {
*/
const BLOCK_SEPARATOR = '\n\n\n'
+/**
+ * A block id the document stores, written on its own line above the block it names. Mirrors
+ * `serializeNodeAnchor` in frontend/src/lib/components/MarkdownNotebook/markdown.ts.
+ *
+ * A markdown block otherwise has no identity of its own: the backend derives its id from the
+ * block text, so the id dies with the next edit to that text. An anchor gives a block the same
+ * durable id a cell tag carries in its `nodeId` prop.
+ */
+function anchoredMarkdownBlock(nodeId: string, markdown: string): string {
+ return `<!--ph:${nodeId}-->\n${markdown}`
+}
+
+/** Matches `STORED_NODE_ID_PREFIX` in the editor, which writes an anchor back only for these. */
+const STORED_NODE_ID_PREFIX = 'phb-'
+
/**
* 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.
@@ -145,6 +160,12 @@ function locateProseAnchorEnd(markdown: string, anchor: ProseAnchor, version: nu
if (version === anchor.version && markdown.slice(anchor.start, anchor.end) === anchor.source) {
return anchor.end
}
+ // A stored id is written into the document above its block, so it names the block exactly.
+ // Matching on it never confuses two blocks that read the same, which the text search below
+ // can only refuse.
+ if (anchor.nodeId.startsWith(STORED_NODE_ID_PREFIX)) {
+ return locateStoredAnchorEnd(markdown, anchor)
+ }
const matches: number[] = []
for (
let index = markdown.indexOf(anchor.source);
@@ -168,6 +189,42 @@ function locateProseAnchorEnd(markdown: string, anchor: ProseAnchor, version: nu
return matches[0]! + anchor.source.length
}
+const ANCHOR_TERMINATOR = new RegExp(`^${EOL}`)
+
+/**
+ * Where the block under `<!--ph:id-->` ends. The anchor finds the block, and the source the read
+ * reported measures it, because a fenced block holds blank lines and a search for the next one
+ * would end the block inside the fence.
+ */
+function locateStoredAnchorEnd(markdown: string, anchor: ProseAnchor): number {
+ const marker = `<!--ph:${anchor.nodeId}-->`
+ const bodyStarts: number[] = []
+ for (let at = markdown.indexOf(marker); at !== -1; at = markdown.indexOf(marker, at + 1)) {
+ const terminator = ANCHOR_TERMINATOR.exec(markdown.slice(at + marker.length, at + marker.length + 2))
+ if (terminator) {
+ bodyStarts.push(at + marker.length + terminator[0].length)
+ }
+ }
+ if (bodyStarts.length === 0) {
+ throw new Error(
+ `Block ${anchor.nodeId} is no longer 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 (bodyStarts.length > 1) {
+ throw new Error(
+ `Block ${anchor.nodeId} names more than one block in notebook, so it cannot name one of them. Read the notebook again with notebooks-get.`
+ )
+ }
+ const bodyStart = bodyStarts[0]!
+ const bodyEnd = bodyStart + anchor.source.length
+ if (!markdown.startsWith(anchor.source, bodyStart) || !BLOCK_END_BOUNDARY.test(markdown.slice(bodyEnd))) {
+ throw new Error(
+ `Block ${anchor.nodeId} changed since it was read, so a cell cannot be placed after it. Read the notebook again with notebooks-get and retry.`
+ )
+ }
+ return bodyEnd
+}
+
function insertBlock(
markdown: string,
block: string,
@@ -343,10 +400,17 @@ 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").'
)
}
+ const proseNodeId = `${STORED_NODE_ID_PREFIX}${uuidv4()}`
await applyMarkdownEdit(context, params.notebook_id, (markdown, version) =>
- insertBlock(markdown, params.markdown!.trim(), params.after_node_id, proseAnchor, version)
+ insertBlock(
+ markdown,
+ anchoredMarkdownBlock(proseNodeId, params.markdown!.trim()),
+ params.after_node_id,
+ proseAnchor,
+ version
+ )
)
- return {}
+ return { node_id: proseNodeId }
}
const nodeId = uuidv4()
diff --git a/services/mcp/src/tools/notebooks/updateCell.ts b/services/mcp/src/tools/notebooks/updateCell.ts
index 0a52fd48a169..74f76cfec06c 100644
--- a/services/mcp/src/tools/notebooks/updateCell.ts
+++ b/services/mcp/src/tools/notebooks/updateCell.ts
@@ -25,12 +25,14 @@ import { applyMarkdownEdit, fetchMarkdownNotebook, notebookPathFor, saveMarkdown
import { NOTEBOOK_SHORT_ID_DESCRIPTION, notebookIdAliases } from './notebookId'
/**
- * Written by `_create_stable_markdown_prose_id` in `products/notebooks/backend/util.py`.
+ * The two id shapes a markdown block can carry: derived from its text by
+ * `_create_stable_markdown_prose_id` in `products/notebooks/backend/util.py`, or stored in the
+ * document as an anchor above the block.
*
* Only sharpens an error, because the content parameter decides the branch. A prefix change in
* the backend therefore degrades one message and breaks nothing.
*/
-const PROSE_NODE_ID_PREFIX = 'mdp-'
+const PROSE_NODE_ID_PREFIXES = ['mdp-', 'phb-']
const UpdateCellInputSchema = z
.object({
@@ -162,7 +164,15 @@ export const updateCellHandler: ToolBase<
'Pass either code (a SQL or Python cell) or markdown (a markdown cell), not both. The cell type follows from node_id; read it from notebooks-get.'
)
}
- if (params.node_id.startsWith(PROSE_NODE_ID_PREFIX) || params.markdown !== undefined) {
+ // A prefix only hints at the cell type. A tag holds its id in a prop, and nothing stops that
+ // prop from reading like a markdown block id, so the document decides when the two disagree.
+ const looksLikeProse = PROSE_NODE_ID_PREFIXES.some((prefix) => params.node_id.startsWith(prefix))
+ if (looksLikeProse && params.code !== undefined) {
+ const { markdown } = await fetchMarkdownNotebook(context, params.notebook_id)
+ if (!findCellTag(markdown, params.node_id)) {
+ return await updateProseCell(context, params)
+ }
+ } else if (looksLikeProse || params.markdown !== undefined) {
return await updateProseCell(context, params)
}
if (params.code !== undefined && !params.code.trim()) {
diff --git a/services/mcp/tests/unit/notebook-cell-tools.test.ts b/services/mcp/tests/unit/notebook-cell-tools.test.ts
index 3b150498ccc5..d1deaa98aec7 100644
--- a/services/mcp/tests/unit/notebook-cell-tools.test.ts
+++ b/services/mcp/tests/unit/notebook-cell-tools.test.ts
@@ -313,18 +313,18 @@ describe('notebook cell tools', () => {
cell_type: 'markdown',
markdown: 'Some **notes**.',
})
- await addCellHandler(context, {
+ const second = await addCellHandler(context, {
notebook_id: 'aBcD1234',
cell_type: 'markdown',
markdown: 'More notes.',
})
- expect(result).toEqual({})
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.
+ // into a single card in the editor, two keeps them separate. The anchor above each one
+ // gives the block an id that survives a later edit to its text.
expect(state.saveBodies[1].content.content[0].attrs.markdown).toBe(
- '# Doc\n\n\nSome **notes**.\n\n\nMore notes.\n'
+ `# Doc\n\n\n<!--ph:${result.node_id}-->\nSome **notes**.\n\n\n<!--ph:${second.node_id}-->\nMore notes.\n`
)
})
@@ -699,7 +699,7 @@ describe('notebook cell tools', () => {
state.stateCells = [{ ...FIRST, start: FIRST.start + 12, end: FIRST.end + 12 }]
const context = createMockContext(state)
- await addCellHandler(context, {
+ const result = await addCellHandler(context, {
notebook_id: 'aBcD1234',
cell_type: 'markdown',
markdown: 'Inserted note.',
@@ -708,7 +708,7 @@ describe('notebook cell tools', () => {
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}`)
+ expect(inserted).toBe(`${before}\n\n\n<!--ph:${result.node_id}-->\nInserted note.\n\n\n${after}`)
})
it.each([
@@ -740,16 +740,71 @@ describe('notebook cell tools', () => {
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.
+ const FENCE = '```python\nx = 1\n\ny = 2\n```'
+
+ // Every row carries offsets from before an edit above the block, so the lookup cannot take
+ // them and must find the block by its stored id.
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 }) => {
+ {
+ label: 'identical prose sits nearby',
+ doc: '<!--ph:phb-one-->\nShared text.\n\n\nShared text.\n',
+ cell: { node_id: 'phb-one', cell_type: 'markdown', code: 'Shared text.', start: 32, end: 44 },
+ expected: (id: string) =>
+ `<!--ph:phb-one-->\nShared text.\n\n\n<!--ph:${id}-->\nInserted note.\n\n\nShared text.\n`,
+ },
+ {
+ label: 'the document uses CRLF',
+ doc: '<!--ph:phb-one-->\r\nShared text.\r\n\r\n\r\nTail.\r\n',
+ cell: { node_id: 'phb-one', cell_type: 'markdown', code: 'Shared text.', start: 2, end: 14 },
+ expected: (id: string) =>
+ `<!--ph:phb-one-->\r\nShared text.\n\n\n<!--ph:${id}-->\nInserted note.\n\n\nTail.\r\n`,
+ },
+ {
+ label: 'the block is a fence that holds a blank line',
+ doc: `<!--ph:phb-one-->\n${FENCE}\n\n\nTail.\n`,
+ cell: { node_id: 'phb-one', cell_type: 'markdown', code: FENCE, start: 2, end: 2 + FENCE.length },
+ expected: (id: string) =>
+ `<!--ph:phb-one-->\n${FENCE}\n\n\n<!--ph:${id}-->\nInserted note.\n\n\nTail.\n`,
+ },
+ ])('places a cell after a stored id when $label', async ({ doc, cell, expected }) => {
const state = makeState(doc)
- state.stateCells = [FIRST]
+ state.stateCells = [cell]
+ const context = createMockContext(state)
+
+ const result = await addCellHandler(context, {
+ notebook_id: 'aBcD1234',
+ cell_type: 'markdown',
+ markdown: 'Inserted note.',
+ after_node_id: 'phb-one',
+ })
+
+ expect(state.saveBodies[0].content.content[0].attrs.markdown).toBe(expected(result.node_id!))
+ })
+
+ it.each([
+ {
+ label: 'a derived id',
+ doc: '# Doc\n\n\nUpdated First paragraph. Now longer.\n',
+ cell: FIRST,
+ expected: /no longer a block of its own/,
+ },
+ {
+ // 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 it is stale.
+ label: 'a derived id at the same offsets',
+ doc: '# Doc\n\n\nFirst paragraph. Now longer.\n',
+ cell: FIRST,
+ expected: /no longer a block of its own/,
+ },
+ {
+ label: 'a stored id',
+ doc: '# Doc\n\n\n<!--ph:phb-one-->\nFirst paragraph. Now longer.\n',
+ cell: { ...FIRST, node_id: 'phb-one' },
+ expected: /changed since it was read/,
+ },
+ ])('refuses $label whose block outgrew the text that was read', async ({ doc, cell, expected }) => {
+ const state = makeState(doc)
+ state.stateCells = [cell]
state.stateVersion = state.version - 1
const context = createMockContext(state)
@@ -758,9 +813,9 @@ describe('notebook cell tools', () => {
notebook_id: 'aBcD1234',
cell_type: 'markdown',
markdown: 'Inserted note.',
- after_node_id: FIRST.node_id,
+ after_node_id: cell.node_id,
})
- ).rejects.toThrow(/no longer a block of its own/)
+ ).rejects.toThrow(expected)
expect(state.saveBodies).toHaveLength(0)
})
@@ -877,6 +932,22 @@ describe('notebook cell tools', () => {
expect(state.saveBodies).toHaveLength(0)
})
+ // The prefix only hints at the cell type. A tag holding an id that reads like a markdown
+ // block id still owns that id, so a code update must reach the tag.
+ it('updates a cell tag whose own nodeId reads like a markdown block id', async () => {
+ const state = makeState('<SQLV2 nodeId="phb-tagged" code="select 1" returnVariable="df" />')
+ state.runStatusResponses.push(DONE_STATUS)
+ const context = createMockContext(state)
+
+ await updateCellHandler(context, {
+ notebook_id: 'aBcD1234',
+ node_id: 'phb-tagged',
+ code: 'select 2',
+ })
+
+ expect(state.saveBodies[0].content.content[0].attrs.markdown).toContain('code="select 2"')
+ })
+
it('refuses a node_id that names more than one block', async () => {
const state = makeState(DOC)
state.stateCells = [FIRST, { ...FIRST, code: 'A different block that hashed the same.' }]