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): let agents edit markdown cells over MCP (#98596)

Sinan Kucukkoseler50c1a9954cc4
diff --git a/products/notebooks/backend/sql_v2_serializers.py b/products/notebooks/backend/sql_v2_serializers.py
index f70bef2280da..2f741ad96bb1 100644
--- a/products/notebooks/backend/sql_v2_serializers.py
+++ b/products/notebooks/backend/sql_v2_serializers.py
@@ -419,13 +419,33 @@ class NotebookCellLastRunSerializer(serializers.Serializer):
class NotebookCellStateSerializer(serializers.Serializer):
node_id = serializers.CharField(help_text="Durable cell identity, used by the cell run and edit endpoints.")
cell_type = serializers.CharField(
- help_text="Cell kind: 'sql', 'python', or 'saved_insight' (embedded insight, never runs)."
+ help_text=(
+ "Cell kind: 'sql', 'python', 'saved_insight' (embedded insight, never runs), or "
+ "'markdown' (prose, a heading, or a fenced block; never runs and joins no dependency graph)."
+ )
)
dataframe_name = serializers.CharField(
allow_blank=True,
help_text="Name other cells reference this cell's result by; blank means display-only.",
)
- code = serializers.CharField(allow_blank=True, help_text="The cell's source, truncated with a marker past 8KB.")
+ code = serializers.CharField(
+ allow_blank=True,
+ help_text=(
+ "The cell's source, truncated with a marker past 8KB. For a markdown cell this is the block's markdown."
+ ),
+ )
+ start = serializers.IntegerField(
+ help_text=(
+ "Offset where the cell's source starts in the notebook's markdown, in UTF-16 code "
+ "units, the same unit the collaboration diffs use."
+ )
+ )
+ end = serializers.IntegerField(
+ help_text=(
+ "Offset just past the cell's source, in UTF-16 code units, excluding the blank lines "
+ "that separate it from the next cell."
+ )
+ )
status = serializers.CharField(
help_text=(
"Derived cell state: 'never_run', 'running', 'done', 'failed', 'interrupted', or 'stale' — "
diff --git a/products/notebooks/backend/sql_v2_state.py b/products/notebooks/backend/sql_v2_state.py
index a2336b8b6485..a9514d9fe2d1 100644
--- a/products/notebooks/backend/sql_v2_state.py
+++ b/products/notebooks/backend/sql_v2_state.py
@@ -31,10 +31,18 @@ from products.notebooks.backend.util import (
_get_markdown_notebook_markdown,
_iter_markdown_component_blocks,
_parse_markdown_component_props,
+ iter_markdown_blocks,
)
_CELL_TAGS = {"SQLV2": "sql", "PythonV2": "python", "Query": "saved_insight"}
+# Prose sits outside the runnable-cell ceiling below, so this is the only bound on how many
+# cells one save can turn into. The reader is an agent that pays context for every block it is
+# handed, on top of the `markdown` this response already carries, so the budget is a response an
+# agent can still afford rather than the largest one a worker survives. Past the cap a notebook
+# stays readable through `markdown`; only its trailing prose loses an id to edit by.
+MAX_ADDRESSABLE_PROSE_BLOCKS = 500
+
# The most cells one notebook may hold. A cell is the expensive unit: a SQL or Python cell is a
# ClickHouse query or a sandbox execution, and the MCP tools let an agent add one and run it in
# the same call, in a loop, with nothing between it and storage. Counted the way `extract_cells`
@@ -46,7 +54,9 @@ _DATAFRAME_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
_CODE_PREVIEW_CHARS = 8_000
-@dataclass
+# Built in stages: `build_dependency_edges` fills the graph edges, `annotate_run_state` the run
+# status, and `_merge_prose_cells` the document span.
+@dataclass(frozen=False)
class NotebookCellState:
node_id: str
cell_type: str
@@ -56,6 +66,8 @@ class NotebookCellState:
depends_on: list[str] = field(default_factory=list)
dependents: list[str] = field(default_factory=list)
last_run: dict[str, Any] | None = None
+ start: int = 0
+ end: int = 0
def extract_cells(content: Any) -> list[NotebookCellState]:
@@ -235,4 +247,40 @@ def build_notebook_cell_state(team_id: int, notebook: Any) -> list[NotebookCellS
for cell in cells:
if len(cell.code) > _CODE_PREVIEW_CHARS:
cell.code = cell.code[:_CODE_PREVIEW_CHARS] + "\n… [truncated]"
- return cells
+ # Prose is added after the truncation above, and must stay that way. An editor that edits a
+ # block by id compares the source it read against the document to find the block again when
+ # the offsets no longer fit. A truncated source never matches, so the edit fails.
+ return _merge_prose_cells(cells, notebook.content)
+
+
+def _merge_prose_cells(cells: list[NotebookCellState], content: Any) -> list[NotebookCellState]:
+ """Return every cell in document order, with the notebook's prose blocks added.
+
+ Prose carries no run state and no dataframe, so it takes no part in the dependency graph.
+ It is listed so a caller can address a paragraph, a heading, or a fenced block by id.
+ """
+ markdown = _get_markdown_notebook_markdown(content)
+ if markdown is None:
+ return cells
+
+ by_node_id = {cell.node_id: cell for cell in cells}
+ ordered: list[NotebookCellState] = []
+ for block in iter_markdown_blocks(markdown, max_prose_blocks=MAX_ADDRESSABLE_PROSE_BLOCKS):
+ if block.kind == "prose":
+ ordered.append(
+ NotebookCellState(
+ node_id=block.node_id,
+ cell_type="markdown",
+ code=block.source,
+ start=block.start,
+ end=block.end,
+ )
+ )
+ continue
+ cell = by_node_id.get(block.node_id)
+ if cell is None:
+ continue
+ cell.start = block.start
+ cell.end = block.end
+ ordered.append(cell)
+ return ordered
diff --git a/products/notebooks/backend/test/test_sql_v2_state.py b/products/notebooks/backend/test/test_sql_v2_state.py
index a97fcfe7f59e..9b446bf242b6 100644
--- a/products/notebooks/backend/test/test_sql_v2_state.py
+++ b/products/notebooks/backend/test/test_sql_v2_state.py
@@ -11,6 +11,7 @@ from rest_framework import status
from products.notebooks.backend.models import Notebook, NotebookNodeRun
from products.notebooks.backend.sql_v2_references import resolve_sql_v2_references
from products.notebooks.backend.sql_v2_state import (
+ MAX_ADDRESSABLE_PROSE_BLOCKS,
MAX_NOTEBOOK_CELLS,
NotebookCellLimitExceeded,
build_dependency_edges,
@@ -23,6 +24,7 @@ from products.notebooks.backend.sql_v2_variables import (
substitute_duckdb_variables,
substitute_hogql_variables,
)
+from products.notebooks.backend.util import iter_markdown_blocks
def markdown_content(markdown: str) -> dict[str, Any]:
@@ -125,6 +127,56 @@ def cells_markdown(count: int) -> dict[str, Any]:
)
+class TestMarkdownBlockSpans(SimpleTestCase):
+ MARKDOWN = (
+ "# Title\n\n"
+ "Some prose.\nA second line.\n\n"
+ '<SQLV2 nodeId="s1" code="select 1" returnVariable="df" />\n\n'
+ "```python\nx = 1\n\ny = 2\n```\n\n"
+ "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]
+
+ def test_a_fenced_block_stays_whole_across_its_blank_line(self) -> None:
+ sources = [block.source for block in iter_markdown_blocks(self.MARKDOWN)]
+ assert "```python\nx = 1\n\ny = 2\n```" in sources
+
+ def test_editing_one_block_leaves_the_other_ids_unchanged(self) -> None:
+ before = {block.node_id for block in iter_markdown_blocks(self.MARKDOWN)}
+ edited = self.MARKDOWN.replace("Closing paragraph.", "Rewritten paragraph.")
+ after = {block.node_id for block in iter_markdown_blocks(edited)}
+ assert len(before - after) == 1
+ assert len(after - before) == 1
+
+ def test_spans_are_utf16_offsets(self) -> None:
+ markdown = "Chart 📊 here.\n\nSecond paragraph."
+ blocks = list(iter_markdown_blocks(markdown))
+ encoded = markdown.encode("utf-16-le")
+ assert [encoded[block.start * 2 : block.end * 2].decode("utf-16-le") for block in blocks] == [
+ block.source for block in blocks
+ ]
+
+ @parameterized.expand(
+ [
+ ("lone_cr", "Intro.\r"),
+ ("crlf", "Intro.\r\n\r\n"),
+ ]
+ )
+ def test_a_tag_after_a_carriage_return_is_a_cell_in_both_walkers(self, _name: str, prefix: str) -> None:
+ # `extract_cells` collapses carriage returns before it splits. A walker that split on
+ # newlines alone would call this prose and drop the cell from the state response.
+ markdown = f'{prefix}<SQLV2 nodeId="s1" code="select 1" returnVariable="df" />'
+ blocks = iter_markdown_blocks(markdown)
+ assert [block.node_id for block in blocks if block.kind == "component"] == ["s1"]
+
+ def test_identical_prose_blocks_get_distinct_ids(self) -> None:
+ blocks = list(iter_markdown_blocks("Same text.\n\nSame text."))
+ assert len({block.node_id for block in blocks}) == 2
+
+
class TestCellCountLimit(SimpleTestCase):
@parameterized.expand(
[
@@ -149,6 +201,21 @@ class TestCellCountLimit(SimpleTestCase):
over = MAX_NOTEBOOK_CELLS + 5
validate_cell_count(cells_markdown(over), cells_markdown(over + delta))
+ def test_prose_stops_being_addressable_past_its_own_cap(self) -> None:
+ markdown = "\n\n".join(f"Paragraph {index}." for index in range(MAX_ADDRESSABLE_PROSE_BLOCKS + 50))
+ blocks = list(iter_markdown_blocks(markdown, max_prose_blocks=MAX_ADDRESSABLE_PROSE_BLOCKS))
+ assert len(blocks) == MAX_ADDRESSABLE_PROSE_BLOCKS
+
+ def test_a_cell_after_the_prose_cap_is_still_reported(self) -> None:
+ prose = "\n\n".join(f"Paragraph {index}." for index in range(MAX_ADDRESSABLE_PROSE_BLOCKS + 50))
+ markdown = f'{prose}\n\n<SQLV2 nodeId="s1" code="select 1" returnVariable="df" />'
+ blocks = iter_markdown_blocks(markdown, max_prose_blocks=MAX_ADDRESSABLE_PROSE_BLOCKS)
+ assert [block.node_id for block in blocks if block.kind == "component"] == ["s1"]
+
+ def test_prose_does_not_count_toward_the_ceiling(self) -> None:
+ prose = "\n\n".join(f"Paragraph {index}." for index in range(MAX_NOTEBOOK_CELLS * 2))
+ validate_cell_count(None, markdown_content(prose))
+
def test_a_notebook_already_over_the_ceiling_still_cannot_grow(self) -> None:
over = MAX_NOTEBOOK_CELLS + 5
with self.assertRaises(NotebookCellLimitExceeded):
@@ -308,3 +375,4 @@ class TestNotebookCellState(APIBaseTest):
assert by_node["p"]["status"] == "never_run"
assert by_node["p"]["depends_on"] == ["s"]
assert by_node["s"]["last_run"]["run_id"]
+ assert data["markdown"][by_node["s"]["start"] : by_node["s"]["end"]].startswith('<SQLV2 nodeId="s"')
diff --git a/products/notebooks/backend/util.py b/products/notebooks/backend/util.py
index fbc768399c38..4e3378263dcb 100644
--- a/products/notebooks/backend/util.py
+++ b/products/notebooks/backend/util.py
@@ -2,6 +2,7 @@ import re
import html
import json
import uuid
+import hashlib
from collections.abc import Iterator
from typing import Any
@@ -344,6 +345,195 @@ def iter_markdown_query_nodes(content: Any) -> Iterator[tuple[str, dict[str, Any
yield node_id, query
+@frozen
+class MarkdownBlock:
+ """One addressable span of a markdown notebook, in document order.
+
+ Blocks never overlap and never include the blank lines between them, so replacing the
+ span `[start, end)` keeps the separators that group cells into cards.
+ """
+
+ kind: str
+ tag_name: str | None
+ node_id: str
+ explicit_node_id: str | None
+ source: str
+ start: int
+ end: int
+
+
+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.
+
+ `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
+ blocks, so an unbounded walk lets one request allocate for minutes. The walk continues past
+ the cap without building the extra prose, because component tags carry the cells that run
+ and must stay addressable wherever they sit in the document.
+ """
+ lines = _split_markdown_lines(markdown)
+ occurrences: dict[str, int] = {}
+ line_index = 0
+ prose_built = 0
+ # 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
+ utf16 = 0
+
+ def prose_budget_left() -> bool:
+ return max_prose_blocks is None or prose_built < max_prose_blocks
+
+ def span_code_points(start_line: int, end_line: int) -> int:
+ """Width of lines `[start_line, end_line)`, each with the terminator that closes it."""
+ width = 0
+ for index in range(start_line, end_line):
+ width += len(lines[index])
+ width += _markdown_terminator_width(markdown, code_points + width)
+ return width
+
+ def 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]
+
+ def consume(start_line: int, end_line: int) -> None:
+ nonlocal code_points, utf16
+ width = span_code_points(start_line, end_line)
+ utf16 += _utf16_length(markdown[code_points : code_points + width])
+ code_points += width
+
+ while line_index < len(lines):
+ if not lines[line_index].strip():
+ consume(line_index, line_index + 1)
+ line_index += 1
+ continue
+
+ if lines[line_index].strip().startswith("```"):
+ 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)
+ consume(line_index, end_line_index)
+ line_index = end_line_index
+ continue
+
+ component = (
+ _read_markdown_component_block(lines, line_index)
+ if _opens_markdown_component_block(lines, line_index)
+ else 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
+ )
+ consume(line_index, next_line_index)
+ line_index = next_line_index
+ continue
+
+ end_line_index = line_index + 1
+ while end_line_index < len(lines) and _continues_markdown_prose_block(lines, end_line_index):
+ 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)
+ consume(line_index, end_line_index)
+ line_index = end_line_index
+
+
+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
+ return not _opens_markdown_component_block(lines, line_index)
+
+
+def _opens_markdown_component_block(lines: list[str], line_index: int) -> bool:
+ """Whether a component block starts at this line.
+
+ The `<` test runs first because it settles every prose line with one string comparison. The
+ regex scan behind it costs enough to dominate the walk of a large document when every line
+ pays it.
+ """
+ stripped = lines[line_index].lstrip()
+ if not stripped.startswith("<") and not stripped.startswith("\\<"):
+ return False
+ return _read_markdown_component_block(lines, line_index) is not None
+
+
+_MARKDOWN_LINE_SPLIT_REGEX = re.compile(r"\r\n|\r|\n")
+
+
+def _split_markdown_lines(markdown: str) -> list[str]:
+ """Lines, split on the terminators `_iter_markdown_component_blocks` collapses before it splits.
+
+ A walk that split on `\n` alone would read different block boundaries than the component
+ walker, so a tag after a lone `\r` would be prose here and a live cell there.
+
+ Only the lines are materialized, matching what the component walker already allocates. A
+ terminator's width comes from `_markdown_terminator_width` at the offset the walk holds,
+ because a second list of that length costs as much again on a document of millions of lines.
+ """
+ return _MARKDOWN_LINE_SPLIT_REGEX.split(markdown)
+
+
+def _markdown_terminator_width(markdown: str, offset: int) -> int:
+ if offset >= len(markdown):
+ return 0
+ return 2 if markdown.startswith("\r\n", offset) else 1
+
+
+def _utf16_length(text: str) -> int:
+ """Length in UTF-16 code units, the unit the collaboration protocol and JavaScript both use.
+
+ Python counts code points, so an astral character is one here and two there. Reporting code
+ points would put every offset after an emoji two apart from where a JavaScript caller slices.
+ """
+ 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:
+ 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,
+ source=source,
+ start=start,
+ end=start + _utf16_length(source),
+ )
+
+
+def _build_markdown_component_block(
+ tag_name: str,
+ raw: str,
+ source: str,
+ start: int,
+ occurrences: dict[str, int],
+) -> MarkdownBlock:
+ props = _parse_markdown_component_props(raw)
+ fingerprint = _get_markdown_component_fingerprint(tag_name, props)
+ occurrence = occurrences.get(fingerprint, 0)
+ 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
+ return MarkdownBlock(
+ kind="component",
+ tag_name=tag_name,
+ node_id=explicit_node_id or _create_stable_markdown_node_id(fingerprint, occurrence),
+ explicit_node_id=explicit_node_id,
+ source=source,
+ start=start,
+ end=start + _utf16_length(source),
+ )
+
+
def _get_markdown_notebook_markdown(content: Any) -> str | None:
if not isinstance(content, dict):
return None
@@ -716,6 +906,17 @@ def _create_stable_markdown_node_id(fingerprint: str, occurrence: int) -> str:
return f"mdn-{_hash_markdown_node_id_seed(fingerprint)}-{occurrence}"
+def _create_stable_markdown_prose_id(source: str, occurrence: int) -> str:
+ # A separate prefix from `mdn-` keeps prose ids and component ids in disjoint spaces, so a
+ # caller can route an id to the right lookup without inspecting the document.
+ #
+ # This does not reuse `_hash_markdown_node_id_seed`, whose 32 bits mirror the frontend's own
+ # hash for component ids. Two prose blocks that collide there share an id, and an edit meant
+ # for one lands on the other, so prose takes a width where a collision cannot be constructed.
+ digest = hashlib.blake2b(source.encode("utf-8"), digest_size=8).digest()
+ return f"mdp-{_to_base36(int.from_bytes(digest, 'big'))}-{occurrence}"
+
+
def _hash_markdown_node_id_seed(value: str) -> str:
hash_value = 5381
encoded = value.encode("utf-16-le", "surrogatepass")
diff --git a/products/notebooks/frontend/generated/api.schemas.ts b/products/notebooks/frontend/generated/api.schemas.ts
index 9f5a15faf1ea..238873d35a99 100644
--- a/products/notebooks/frontend/generated/api.schemas.ts
+++ b/products/notebooks/frontend/generated/api.schemas.ts
@@ -600,12 +600,16 @@ export interface NotebookCellLastRunApi {
export interface NotebookCellStateApi {
/** Durable cell identity, used by the cell run and edit endpoints. */
node_id: string
- /** Cell kind: 'sql', 'python', or 'saved_insight' (embedded insight, never runs). */
+ /** Cell kind: 'sql', 'python', 'saved_insight' (embedded insight, never runs), or 'markdown' (prose, a heading, or a fenced block; never runs and joins no dependency graph). */
cell_type: string
/** Name other cells reference this cell's result by; blank means display-only. */
dataframe_name: string
- /** The cell's source, truncated with a marker past 8KB. */
+ /** The cell's source, truncated with a marker past 8KB. For a markdown cell this is the block's markdown. */
code: string
+ /** Offset where the cell's source starts in the notebook's markdown, in UTF-16 code units, the same unit the collaboration diffs use. */
+ start: number
+ /** Offset just past the cell's source, in UTF-16 code units, excluding the blank lines that separate it from the next cell. */
+ end: number
/** Derived cell state: 'never_run', 'running', 'done', 'failed', 'interrupted', or 'stale' — stale means re-running now would execute different code than the last completed run (the cell or an upstream dependency changed). */
status: string
/** node_ids of cells whose dataframes this cell's code references. */
diff --git a/products/notebooks/mcp/tools.yaml b/products/notebooks/mcp/tools.yaml
index c44a10fab670..88fc77512d6c 100644
--- a/products/notebooks/mcp/tools.yaml
+++ b/products/notebooks/mcp/tools.yaml
@@ -149,16 +149,19 @@ tools:
description: >
The full notebook view: title, markdown source, the notebook's variables (name, type, value; a SQL cell
reads one as `{name}`, a Python cell as a global — change them with notebooks-set-variables), and every cell
- with its code, dataframe name, depends_on/dependents edges, and derived status — 'stale' means re-running
- the cell now would execute different code than its last completed run (the cell changed, an upstream
- changed, or, for a SQL cell that ran on ClickHouse, a variable it reads changed), so its displayed result is
- outdated. A changed variable value does not make a Python cell, or a SQL cell that reads a Python-created
- dataframe, stale: on those, 'done' means the code is current, not the values it ran with. Re-run them from
- the stale_cells list notebooks-set-variables returns, and re-run before trusting a result whose values may
- have changed since. Use this to read or orient in a notebook, find which cells need re-running after edits,
- and decide re-run order (walk stale cells in dependency order with notebooks-update-cell, omitting code).
- Legacy rich-text notebooks return their raw document in content instead of markdown. When you do not have
- the notebook's short_id, find it with notebooks-list.
+ (the notebook's markdown prose included, as cell_type 'markdown') with its code, dataframe name,
+ depends_on/dependents edges, and derived status — 'stale' means re-running the cell now would execute
+ different code than its last completed run (the cell changed, an upstream changed, or, for a SQL cell that
+ ran on ClickHouse, a variable it reads changed), so its displayed result is outdated. A changed variable
+ value does not make a Python cell, or a SQL cell that reads a Python-created dataframe, stale: on those,
+ 'done' means the code is current, not the values it ran with. Re-run them from the stale_cells list
+ notebooks-set-variables returns, and re-run before trusting a result whose values may have changed since.
+ Use this to read or orient in a notebook, find which cells need re-running after edits, and decide re-run
+ order (walk stale cells in dependency order with notebooks-update-cell, omitting code). Each cell carries
+ start and end: the character span of its source in markdown. A markdown cell's id is derived from its text,
+ so edit it with notebooks-update-cell against the same read that returned it. Legacy rich-text notebooks
+ return their raw document in content instead of markdown. When you do not have the notebook's short_id, find
+ it with notebooks-list.
param_overrides:
short_id:
description: >
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index ed7bb34afc63..37792b9adad8 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -8443,7 +8443,7 @@
}
},
"notebooks-get": {
- "description": "The full notebook view: title, markdown source, the notebook's variables (name, type, value; a SQL cell reads one as `{name}`, a Python cell as a global — change them with notebooks-set-variables), and every cell with its code, dataframe name, depends_on/dependents edges, and derived status — 'stale' means re-running the cell now would execute different code than its last completed run (the cell changed, an upstream changed, or, for a SQL cell that ran on ClickHouse, a variable it reads changed), so its displayed result is outdated. A changed variable value does not make a Python cell, or a SQL cell that reads a Python-created dataframe, stale: on those, 'done' means the code is current, not the values it ran with. Re-run them from the stale_cells list notebooks-set-variables returns, and re-run before trusting a result whose values may have changed since. Use this to read or orient in a notebook, find which cells need re-running after edits, and decide re-run order (walk stale cells in dependency order with notebooks-update-cell, omitting code). Legacy rich-text notebooks return their raw document in content instead of markdown. When you do not have the notebook's short_id, find it with notebooks-list.",
+ "description": "The full notebook view: title, markdown source, the notebook's variables (name, type, value; a SQL cell reads one as `{name}`, a Python cell as a global — change them with notebooks-set-variables), and every cell (the notebook's markdown prose included, as cell_type 'markdown') with its code, dataframe name, depends_on/dependents edges, and derived status — 'stale' means re-running the cell now would execute different code than its last completed run (the cell changed, an upstream changed, or, for a SQL cell that ran on ClickHouse, a variable it reads changed), so its displayed result is outdated. A changed variable value does not make a Python cell, or a SQL cell that reads a Python-created dataframe, stale: on those, 'done' means the code is current, not the values it ran with. Re-run them from the stale_cells list notebooks-set-variables returns, and re-run before trusting a result whose values may have changed since. Use this to read or orient in a notebook, find which cells need re-running after edits, and decide re-run order (walk stale cells in dependency order with notebooks-update-cell, omitting code). Each cell carries start and end: the character span of its source in markdown. A markdown cell's id is derived from its text, so edit it with notebooks-update-cell against the same read that returned it. Legacy rich-text notebooks return their raw document in content instead of markdown. When you do not have the notebook's short_id, find it with notebooks-list.",
"category": "Notebooks",
"feature": "notebooks",
"summary": "Get notebook",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 01cd29906b09..0b5c010ae137 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -8900,7 +8900,7 @@
}
},
"notebooks-get": {
- "description": "The full notebook view: title, markdown source, the notebook's variables (name, type, value; a SQL cell reads one as `{name}`, a Python cell as a global — change them with notebooks-set-variables), and every cell with its code, dataframe name, depends_on/dependents edges, and derived status — 'stale' means re-running the cell now would execute different code than its last completed run (the cell changed, an upstream changed, or, for a SQL cell that ran on ClickHouse, a variable it reads changed), so its displayed result is outdated. A changed variable value does not make a Python cell, or a SQL cell that reads a Python-created dataframe, stale: on those, 'done' means the code is current, not the values it ran with. Re-run them from the stale_cells list notebooks-set-variables returns, and re-run before trusting a result whose values may have changed since. Use this to read or orient in a notebook, find which cells need re-running after edits, and decide re-run order (walk stale cells in dependency order with notebooks-update-cell, omitting code). Legacy rich-text notebooks return their raw document in content instead of markdown. When you do not have the notebook's short_id, find it with notebooks-list.",
+ "description": "The full notebook view: title, markdown source, the notebook's variables (name, type, value; a SQL cell reads one as `{name}`, a Python cell as a global — change them with notebooks-set-variables), and every cell (the notebook's markdown prose included, as cell_type 'markdown') with its code, dataframe name, depends_on/dependents edges, and derived status — 'stale' means re-running the cell now would execute different code than its last completed run (the cell changed, an upstream changed, or, for a SQL cell that ran on ClickHouse, a variable it reads changed), so its displayed result is outdated. A changed variable value does not make a Python cell, or a SQL cell that reads a Python-created dataframe, stale: on those, 'done' means the code is current, not the values it ran with. Re-run them from the stale_cells list notebooks-set-variables returns, and re-run before trusting a result whose values may have changed since. Use this to read or orient in a notebook, find which cells need re-running after edits, and decide re-run order (walk stale cells in dependency order with notebooks-update-cell, omitting code). Each cell carries start and end: the character span of its source in markdown. A markdown cell's id is derived from its text, so edit it with notebooks-update-cell against the same read that returned it. Legacy rich-text notebooks return their raw document in content instead of markdown. When you do not have the notebook's short_id, find it with notebooks-list.",
"category": "Notebooks",
"feature": "notebooks",
"summary": "Get notebook",
@@ -9023,7 +9023,7 @@
}
},
"notebooks-update-cell": {
- "description": "Update a SQL or Python cell's code and re-run it, or re-run it unchanged by omitting code (how you refresh a stale cell). Waits up to ~45s and returns the result like notebooks-add-cell, plus stale_dependents: the downstream cells whose inputs this run invalidated. Nothing re-runs automatically — inspect each dependent and re-run it with this tool (no code) or fix it first, walking the graph one hop at a time. The run binds the notebook's current variables, so re-running (no code) is also how a cell picks up a changed variable value. Re-running a Python cell provisions the notebook's sandbox when none is running, and the user pays for it while it runs, so tell them its hourly_price the first time a run starts one.",
+ "description": "Update a cell by node_id. For a SQL or Python cell pass `code` to replace its source and re-run it, or omit code to re-run it unchanged (how you refresh a stale cell). For a markdown cell (cell_type 'markdown' in notebooks-get: prose, a heading, a table, a fenced block) pass `markdown` instead: it replaces that block only, runs nothing, and leaves every other cell untouched. That is how you fix wording in a notebook you already shared, instead of appending a correction or recreating it under a new URL. Read the ids with notebooks-get and edit against that same read, because a markdown cell's id is derived from its text and changes once the text changes. Waits up to ~45s and returns the result like notebooks-add-cell, plus stale_dependents: the downstream cells whose inputs this run invalidated. Nothing re-runs automatically — inspect each dependent and re-run it with this tool (no code) or fix it first, walking the graph one hop at a time. The run binds the notebook's current variables, so re-running (no code) is also how a cell picks up a changed variable value. Re-running a Python cell provisions the notebook's sandbox when none is running, and the user pays for it while it runs, so tell them its hourly_price the first time a run starts one.",
"category": "Notebooks",
"feature": "notebooks",
"summary": "Update a cell's code and re-run it.",
diff --git a/services/mcp/schema/tool-definitions.json b/services/mcp/schema/tool-definitions.json
index 80fb037640fc..4a53d38172df 100644
--- a/services/mcp/schema/tool-definitions.json
+++ b/services/mcp/schema/tool-definitions.json
@@ -319,7 +319,7 @@
}
},
"notebooks-update-cell": {
- "description": "Update a SQL or Python cell's code and re-run it, or re-run it unchanged by omitting code (how you refresh a stale cell). Waits up to ~45s and returns the result like notebooks-add-cell, plus stale_dependents: the downstream cells whose inputs this run invalidated. Nothing re-runs automatically — inspect each dependent and re-run it with this tool (no code) or fix it first, walking the graph one hop at a time. The run binds the notebook's current variables, so re-running (no code) is also how a cell picks up a changed variable value. Re-running a Python cell provisions the notebook's sandbox when none is running, and the user pays for it while it runs, so tell them its hourly_price the first time a run starts one.",
+ "description": "Update a cell by node_id. For a SQL or Python cell pass `code` to replace its source and re-run it, or omit code to re-run it unchanged (how you refresh a stale cell). For a markdown cell (cell_type 'markdown' in notebooks-get: prose, a heading, a table, a fenced block) pass `markdown` instead: it replaces that block only, runs nothing, and leaves every other cell untouched. That is how you fix wording in a notebook you already shared, instead of appending a correction or recreating it under a new URL. Read the ids with notebooks-get and edit against that same read, because a markdown cell's id is derived from its text and changes once the text changes. Waits up to ~45s and returns the result like notebooks-add-cell, plus stale_dependents: the downstream cells whose inputs this run invalidated. Nothing re-runs automatically — inspect each dependent and re-run it with this tool (no code) or fix it first, walking the graph one hop at a time. The run binds the notebook's current variables, so re-running (no code) is also how a cell picks up a changed variable value. Re-running a Python cell provisions the notebook's sandbox when none is running, and the user pays for it while it runs, so tell them its hourly_price the first time a run starts one.",
"category": "Notebooks",
"feature": "notebooks",
"summary": "Update a cell's code and re-run it.",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 2529e5589c36..a66573723dc7 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -54265,12 +54265,16 @@ export namespace Schemas {
export interface NotebookCellState {
/** Durable cell identity, used by the cell run and edit endpoints. */
node_id: string;
- /** Cell kind: 'sql', 'python', or 'saved_insight' (embedded insight, never runs). */
+ /** Cell kind: 'sql', 'python', 'saved_insight' (embedded insight, never runs), or 'markdown' (prose, a heading, or a fenced block; never runs and joins no dependency graph). */
cell_type: string;
/** Name other cells reference this cell's result by; blank means display-only. */
dataframe_name: string;
- /** The cell's source, truncated with a marker past 8KB. */
+ /** The cell's source, truncated with a marker past 8KB. For a markdown cell this is the block's markdown. */
code: string;
+ /** Offset where the cell's source starts in the notebook's markdown, in UTF-16 code units, the same unit the collaboration diffs use. */
+ start: number;
+ /** Offset just past the cell's source, in UTF-16 code units, excluding the blank lines that separate it from the next cell. */
+ end: number;
/** Derived cell state: 'never_run', 'running', 'done', 'failed', 'interrupted', or 'stale' — stale means re-running now would execute different code than the last completed run (the cell or an upstream dependency changed). */
status: string;
/** node_ids of cells whose dataframes this cell's code references. */
diff --git a/services/mcp/src/tools/notebooks/cellTags.ts b/services/mcp/src/tools/notebooks/cellTags.ts
index 5c8cbdec85ca..8f5f284c86b9 100644
--- a/services/mcp/src/tools/notebooks/cellTags.ts
+++ b/services/mcp/src/tools/notebooks/cellTags.ts
@@ -27,6 +27,7 @@ export interface CellTagBlock {
export const DATAFRAME_NAME_REGEX = /^[A-Za-z_][A-Za-z0-9_]*$/
const TAG_START_REGEX = /^<([A-Z][A-Za-z0-9]*)(?=[\s/>])/
+const ESCAPED_TAG_START_REGEX = /^\\<([A-Z][A-Za-z0-9]*)(?=[\s/>])/
// A JSON string literal: quote-delimited with backslash escapes.
const JSON_STRING = '"(?:[^"\\\\]|\\\\.)*"'
@@ -120,6 +121,29 @@ export function buildCellTag(tagName: string, props: Record<string, unknown>): s
* starts at a line beginning with `<TagName` and runs until a line ending in `/>` (or a
* closing tag) — a blank line terminates an unclosed tag without swallowing the document.
*/
+/**
+ * Lexical on purpose. `parseCellTags` reports nothing for a tag that never terminates, and that
+ * is the case that corrupts a document, so a guard built on the parser would pass exactly the
+ * input it must reject.
+ */
+/**
+ * Characters Python's `str.strip()` and `\s` treat as whitespace and JavaScript's do not. The
+ * backend parses the tag grammar, so a line it reads as `<Tag …` must not read as prose here.
+ */
+const PYTHON_ONLY_WHITESPACE = /[\x1c-\x1f\x85]/g
+
+/** A line as the backend's whitespace grammar sees it, so both sides agree on what it opens. */
+export function normalizeForTagScan(line: string): string {
+ return line.replace(PYTHON_ONLY_WHITESPACE, ' ').trim()
+}
+
+export function startsComponentTag(line: string): boolean {
+ const normalized = normalizeForTagScan(line)
+ // The backend recovers a multiline tag written as `\<Tag …>`, so the escaped form opens a
+ // runnable cell exactly like the bare one.
+ return TAG_START_REGEX.test(normalized) || ESCAPED_TAG_START_REGEX.test(normalized)
+}
+
export function parseCellTags(markdown: string): CellTagBlock[] {
const blocks: CellTagBlock[] = []
const lines = markdown.split('\n')
diff --git a/services/mcp/src/tools/notebooks/updateCell.ts b/services/mcp/src/tools/notebooks/updateCell.ts
index adb8ef18987a..0a52fd48a169 100644
--- a/services/mcp/src/tools/notebooks/updateCell.ts
+++ b/services/mcp/src/tools/notebooks/updateCell.ts
@@ -1,5 +1,6 @@
import { z } from 'zod'
+import type { Schemas } from '@/api/generated'
import type { Context, ToolBase } from '@/tools/types'
import {
@@ -10,10 +11,27 @@ import {
wrapRunResultAsInformational,
type ShapedRunResult,
} from './cellRuns'
-import { collectRunRefs, directDependents, findCellTag, parseCellTags, replaceCellTag, upsertProp } from './cellTags'
-import { applyMarkdownEdit, fetchMarkdownNotebook, notebookPathFor } from './markdownDoc'
+import {
+ collectRunRefs,
+ directDependents,
+ findCellTag,
+ parseCellTags,
+ replaceCellTag,
+ normalizeForTagScan,
+ startsComponentTag,
+ upsertProp,
+} from './cellTags'
+import { applyMarkdownEdit, fetchMarkdownNotebook, notebookPathFor, saveMarkdown } from './markdownDoc'
import { NOTEBOOK_SHORT_ID_DESCRIPTION, notebookIdAliases } from './notebookId'
+/**
+ * Written by `_create_stable_markdown_prose_id` in `products/notebooks/backend/util.py`.
+ *
+ * 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 UpdateCellInputSchema = z
.object({
notebook_id: z.string().describe(NOTEBOOK_SHORT_ID_DESCRIPTION),
@@ -22,6 +40,12 @@ const UpdateCellInputSchema = z
.string()
.optional()
.describe('New SQL or Python source. Omit to re-run the cell as-is (e.g. a stale cell).'),
+ markdown: z
+ .string()
+ .optional()
+ .describe(
+ 'New markdown for a markdown cell: prose, a heading, a table, or a fenced block. Use this instead of `code` when notebooks-get reports the cell as cell_type "markdown". Pass the replacement only; the surrounding cells are untouched.'
+ ),
})
.strict()
@@ -33,10 +57,114 @@ export interface UpdateCellResult {
stale_dependents: { node_id: string; dataframe_name?: string }[]
}
-export const updateCellHandler: ToolBase<typeof NotebooksUpdateCellSchema, UpdateCellResult>['handler'] = async (
+export interface UpdateProseCellResult {
+ node_id: string
+ updated: true
+}
+
+/** Reject markdown that opens a component tag, so a cell can only be added by the tool that owns runs and identity. */
+function assertNoComponentTag(markdown: string): void {
+ let insideFence = false
+ // The backend collapses `\r\n` and a lone `\r` to a newline before it looks for tags, so a
+ // payload split only on `\n` hides a tag from this guard that the backend later reads as a
+ // live cell.
+ for (const line of markdown.replace(/\r\n/g, '\n').replace(/\r/g, '\n').split('\n')) {
+ // Fence detection normalizes the same characters as the tag check. Python strips them,
+ // so a control-prefixed fence opens a block there and reads as prose here, which moves
+ // every tag after it in or out of the fence.
+ if (normalizeForTagScan(line).startsWith('```')) {
+ insideFence = !insideFence
+ continue
+ }
+ // Both walkers read fenced content as inert, so a tag written as an example there opens
+ // no cell and the guard would reject a legitimate edit.
+ if (insideFence || !startsComponentTag(line)) {
+ continue
+ }
+ throw new Error(
+ `markdown must not contain a component tag (found ${line.trim().slice(0, 40)}). Add cells with notebooks-add-cell, which assigns identity, names the dataframe, and runs the cell. To show a tag as an example, put it in a fenced code block.`
+ )
+ }
+ // An unclosed fence flips the fence state of everything after this block, which decides
+ // whether the tags already in the document open cells.
+ if (insideFence) {
+ throw new Error('markdown must not leave a code fence open. Close every ``` block in the replacement.')
+ }
+}
+
+async function updateProseCell(
context: Context,
params: z.infer<typeof NotebooksUpdateCellSchema>
-) => {
+): Promise<UpdateProseCellResult> {
+ if (params.code !== undefined) {
+ throw new Error(
+ `Cell ${params.node_id} is a markdown cell. Pass its replacement as \`markdown\`, not \`code\`.`
+ )
+ }
+ const next = params.markdown
+ if (next === undefined || !next.trim()) {
+ throw new Error('markdown must be non-empty. Remove a cell with notebooks-delete-cell.')
+ }
+ assertNoComponentTag(next)
+
+ const projectId = await context.stateManager.getProjectId()
+ const state = await context.api.request<{ version: number | null; cells: Schemas.NotebookCellState[] }>({
+ method: 'GET',
+ path: `${notebookPathFor(projectId, params.notebook_id)}sql_v2/state/`,
+ })
+ const block = state.cells.find((cell) => cell.node_id === params.node_id)
+ if (!block) {
+ throw new Error(
+ `No cell with node_id ${params.node_id} in notebook ${params.notebook_id}. Read the current ids with notebooks-get.`
+ )
+ }
+ if (block.cell_type !== 'markdown') {
+ throw new Error(`Cell ${params.node_id} is a ${block.cell_type} cell. Pass its replacement as \`code\`.`)
+ }
+ // A prose id counts occurrences of identical text, so a block that duplicates another one's
+ // text is only pinned by the position it held when the caller read it. A write arrives after
+ // that read, and an identical block inserted above in between shifts every later occurrence
+ // by one. The id would still resolve, and the fresh offsets would still validate, so the edit
+ // would land on a block the caller never saw.
+ const sameId = state.cells.filter((cell) => cell.node_id === params.node_id)
+ if (sameId.length > 1) {
+ throw new Error(
+ `Cell ${params.node_id} names ${sameId.length} blocks in notebook ${params.notebook_id}, so it cannot name one of them. Re-read the notebook with notebooks-get.`
+ )
+ }
+ // The edit is bound to the document the caller read, rather than hunted for again in a newer
+ // one. Re-resolving needs the backend's block grammar, and this side does not have it: a tag
+ // `parseCellTags` cannot see is prose here and a live cell there, so a miss rewrites a cell.
+ // A changed document is therefore reported, and the caller reads again.
+ const notebook = await fetchMarkdownNotebook(context, params.notebook_id)
+ if (notebook.version !== state.version) {
+ throw new Error(
+ `Notebook ${params.notebook_id} changed since cell ${params.node_id} was read. Read it again with notebooks-get and retry with the id it returns.`
+ )
+ }
+ if (notebook.markdown.slice(block.start, block.end) !== block.code) {
+ throw new Error(
+ `Cell ${params.node_id} is not where the read placed it in notebook ${params.notebook_id}. Read it again with notebooks-get and retry with the id it returns.`
+ )
+ }
+
+ const nextMarkdown = notebook.markdown.slice(0, block.start) + next.trim() + notebook.markdown.slice(block.end)
+ await saveMarkdown(context, notebook, nextMarkdown)
+ return { node_id: params.node_id, updated: true }
+}
+
+export const updateCellHandler: ToolBase<
+ typeof NotebooksUpdateCellSchema,
+ UpdateCellResult | UpdateProseCellResult
+>['handler'] = async (context: Context, params: z.infer<typeof NotebooksUpdateCellSchema>) => {
+ if (params.code !== undefined && params.markdown !== undefined) {
+ throw new Error(
+ '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) {
+ return await updateProseCell(context, params)
+ }
if (params.code !== undefined && !params.code.trim()) {
throw new Error('code must be non-empty; omit it to re-run the cell unchanged.')
}
@@ -105,7 +233,7 @@ export const updateCellHandler: ToolBase<typeof NotebooksUpdateCellSchema, Updat
})
}
-const tool = (): ToolBase<typeof NotebooksUpdateCellSchema, UpdateCellResult> => ({
+const tool = (): ToolBase<typeof NotebooksUpdateCellSchema, UpdateCellResult | UpdateProseCellResult> => ({
name: 'notebooks-update-cell',
schema: NotebooksUpdateCellSchema,
handler: updateCellHandler,
diff --git a/services/mcp/tests/unit/notebook-cell-tools.test.ts b/services/mcp/tests/unit/notebook-cell-tools.test.ts
index c392ffc6ad14..c61a929b1cd4 100644
--- a/services/mcp/tests/unit/notebook-cell-tools.test.ts
+++ b/services/mcp/tests/unit/notebook-cell-tools.test.ts
@@ -24,6 +24,12 @@ interface MockState {
runStatusResponses: any[]
createBodies: any[]
patchBodies: any[]
+ // Cells the sql_v2 state endpoint reports. Supplied per test: the spans are the backend's
+ // job, and `test_sql_v2_state.py` covers how it derives them.
+ stateCells?: any[]
+ // Version the state endpoint reports. Set it apart from `version` to model a notebook that
+ // moved between the caller's read and its write.
+ stateVersion?: number
}
function markdownContent(markdown: string): Record<string, unknown> {
@@ -43,6 +49,14 @@ function createMockContext(state: MockState): Context {
}
return next
}
+ if (opts.method === 'GET' && path.endsWith('/sql_v2/state/')) {
+ return {
+ notebook_id: 'aBcD1234',
+ version: state.stateVersion ?? state.version,
+ markdown: state.markdown,
+ cells: state.stateCells ?? [],
+ }
+ }
if (opts.method === 'GET') {
return {
short_id: 'aBcD1234',
@@ -447,7 +461,7 @@ describe('notebook cell tools', () => {
expect(state.saveBodies[0].content.content[0].attrs.markdown).toContain('code="select 2"')
expect(state.runBodies[0]).toMatchObject({ node_id: 'target', code: 'select 2' })
expect(state.runBodies[0]).not.toHaveProperty('variables')
- expect(result.stale_dependents).toEqual([{ node_id: 'reader', dataframe_name: 'out' }])
+ expect(result).toMatchObject({ stale_dependents: [{ node_id: 'reader', dataframe_name: 'out' }] })
// Write-back replaces the stale runId in place.
const writtenBack = state.saveBodies[1].content.content[0].attrs.markdown
expect(writtenBack).toContain('runId="run-1"')
@@ -588,4 +602,166 @@ describe('notebook cell tools', () => {
],
})
})
+ describe('markdown cells', () => {
+ const DOC = ['# Title', '', 'First paragraph.', '', 'Second paragraph.'].join('\n')
+ // Spans of "First paragraph." in DOC, as the backend reports them.
+ const FIRST = { node_id: 'mdp-abc-0', cell_type: 'markdown', code: 'First paragraph.', start: 9, end: 25 }
+
+ it('replaces the addressed block and leaves its neighbours untouched', async () => {
+ const state = makeState(DOC)
+ state.stateCells = [FIRST]
+ const context = createMockContext(state)
+
+ const result = await updateCellHandler(context, {
+ notebook_id: 'aBcD1234',
+ node_id: FIRST.node_id,
+ markdown: 'Rewritten paragraph.',
+ })
+
+ expect(result).toMatchObject({ node_id: FIRST.node_id, updated: true })
+ expect(state.saveBodies[0].content.content[0].attrs.markdown).toBe(
+ ['# Title', '', 'Rewritten paragraph.', '', 'Second paragraph.'].join('\n')
+ )
+ })
+
+ it.each([
+ ['terminated', '<SQLV2 nodeId="x" code="select 1" />'],
+ // parseCellTags reports nothing for this one, which is why the guard is lexical.
+ ['unterminated', '<PythonV2 nodeId="x" code="a\n\nb" />'],
+ // The backend recovers this form as a live cell, so `<` alone is not the whole guard.
+ ['escaped multiline', '\\<PythonV2 nodeId="x" code="# hi\nout = 1" />'],
+ // Python strips \\x1c-\\x1f and JavaScript's trim() does not, so the backend reads
+ // these as tags while a trim-based guard reads them as prose.
+ ['control-prefixed', '\x1c<SQLV2 nodeId="x" code="select 1" />'],
+ ['control-separated', '<SQLV2\x1cnodeId="x" code="select 1" />'],
+ ['lone carriage return', 'Intro.\r<SQLV2 nodeId="x" code="select 1" />'],
+ ['crlf', 'Intro.\r\n<SQLV2 nodeId="x" code="select 1" />'],
+ ])('refuses markdown carrying a %s component tag', async (_name, injected) => {
+ const state = makeState(DOC)
+ state.stateCells = [FIRST]
+ const context = createMockContext(state)
+
+ await expect(
+ updateCellHandler(context, {
+ notebook_id: 'aBcD1234',
+ node_id: FIRST.node_id,
+ markdown: `Intro.\n${injected}`,
+ })
+ ).rejects.toThrow(/notebooks-add-cell/)
+ expect(state.saveBodies).toHaveLength(0)
+ })
+
+ it('refuses a fence opened behind a control character', async () => {
+ // Python strips U+001C, so this opens a code block there and reads as prose here,
+ // which swallows the cells that follow it.
+ const state = makeState(DOC)
+ state.stateCells = [FIRST]
+ const context = createMockContext(state)
+
+ await expect(
+ updateCellHandler(context, {
+ notebook_id: 'aBcD1234',
+ node_id: FIRST.node_id,
+ markdown: 'Intro.\n\n\x1c```',
+ })
+ ).rejects.toThrow(/fence open/)
+ expect(state.saveBodies).toHaveLength(0)
+ })
+
+ it('accepts a component tag shown inside a code fence', async () => {
+ // Both walkers read fenced content as inert, so this opens no cell.
+ const state = makeState(DOC)
+ state.stateCells = [FIRST]
+ const context = createMockContext(state)
+
+ await updateCellHandler(context, {
+ notebook_id: 'aBcD1234',
+ node_id: FIRST.node_id,
+ markdown: 'Example:\n\n```\n<SQLV2 nodeId="x" code="select 1" />\n```',
+ })
+
+ expect(state.saveBodies[0].content.content[0].attrs.markdown).toContain('<SQLV2')
+ })
+
+ it('refuses markdown that leaves a fence open', async () => {
+ const state = makeState(DOC)
+ state.stateCells = [FIRST]
+ const context = createMockContext(state)
+
+ await expect(
+ updateCellHandler(context, {
+ notebook_id: 'aBcD1234',
+ node_id: FIRST.node_id,
+ markdown: 'Example:\n\n```\nselect 1',
+ })
+ ).rejects.toThrow(/leave a code fence open/)
+ expect(state.saveBodies).toHaveLength(0)
+ })
+
+ 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.' }]
+ const context = createMockContext(state)
+
+ await expect(
+ updateCellHandler(context, {
+ notebook_id: 'aBcD1234',
+ node_id: FIRST.node_id,
+ markdown: 'Rewritten.',
+ })
+ ).rejects.toThrow(/names 2 blocks/)
+ expect(state.saveBodies).toHaveLength(0)
+ })
+
+ it('edits the right one of two blocks that read the same', async () => {
+ const doc = ['Same text.', '', 'Middle.', '', 'Same text.'].join('\n')
+ const state = makeState(doc)
+ state.stateCells = [
+ { node_id: 'mdp-a-0', cell_type: 'markdown', code: 'Same text.', start: 0, end: 10 },
+ { node_id: 'mdp-a-1', cell_type: 'markdown', code: 'Same text.', start: 21, end: 31 },
+ ]
+ const context = createMockContext(state)
+
+ await updateCellHandler(context, {
+ notebook_id: 'aBcD1234',
+ node_id: 'mdp-a-1',
+ markdown: 'Rewritten.',
+ })
+
+ expect(state.saveBodies[0].content.content[0].attrs.markdown).toBe(
+ ['Same text.', '', 'Middle.', '', 'Rewritten.'].join('\n')
+ )
+ })
+
+ it('refuses when the notebook moved between the read and the write', async () => {
+ const state = makeState(DOC)
+ state.stateCells = [FIRST]
+ state.stateVersion = state.version - 1
+ const context = createMockContext(state)
+
+ await expect(
+ updateCellHandler(context, {
+ notebook_id: 'aBcD1234',
+ node_id: FIRST.node_id,
+ markdown: 'Rewritten.',
+ })
+ ).rejects.toThrow(/changed since cell/)
+ expect(state.saveBodies).toHaveLength(0)
+ })
+
+ it.each([
+ ['code on a markdown cell', { node_id: FIRST.node_id, code: 'select 1' }, /is a markdown cell/],
+ ['markdown on a runnable cell', { node_id: 'target', markdown: 'text' }, /is a sql cell/],
+ ['both content parameters', { node_id: 'target', code: 'select 1', markdown: 'text' }, /not both/],
+ ])('routes %s to the right parameter', async (_name, params, expected) => {
+ const state = makeState(['<SQLV2 nodeId="target" code="select 1" returnVariable="df" />'].join('\n'))
+ state.stateCells = [FIRST, { node_id: 'target', cell_type: 'sql', code: 'select 1', start: 0, end: 58 }]
+ const context = createMockContext(state)
+
+ await expect(updateCellHandler(context, { notebook_id: 'aBcD1234', ...params } as any)).rejects.toThrow(
+ expected
+ )
+ expect(state.saveBodies).toHaveLength(0)
+ })
+ })
})