: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): restore comment actions and markdown cell edits (#116013)
Marius Andra6ceb32d24aca
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.jupyter.test.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.jupyter.test.tsxindex 41c199fb9deb..aaab7379fd6d 100644--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.jupyter.test.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.jupyter.test.tsx@@ -26,6 +26,12 @@ function CodeEditorStandIn({ node }: NotebookComponentRenderProps): JSX.Element}const registry = createMarkdownNotebookRegistry([+ {+ tagName: 'Comment',+ label: 'Comment',+ category: 'Text',+ ViewComponent: () => createElement('div', null, 'A discussion'),+ },{tagName: 'Py',label: 'Python',@@ -95,6 +101,16 @@ async function flushFrames(): Promise<void> {const TWO_CELLS = '# Title\n\nIntro\n\n<Py code="a = 1" />\n\n<Py code="b = 2" />'describe('MarkdownNotebook in Jupyter mode', () => {+ it.each(['Backspace', 'Delete'])('deletes only the focused discussion thread with %s', (key) => {+ const notebook = renderJupyterNotebook(+ '# Title\n\n<Comment ref="note" replies={[]} />\n\nA <ref id="note">useful</ref> paragraph.\n\nAnother paragraph.'+ )+ const thread = notebook.container.querySelector<HTMLElement>('.MarkdownNotebook__component-shell')!+ act(() => thread.focus())+ press(thread, key)+ expect(notebook.latest()).toEqual('# Title\n\nA useful paragraph.\n\nAnother paragraph.')+ })+it.each([['A inserts a cell above',diff --git a/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx b/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsxindex fe01461bea6e..0153622eeebf 100644--- a/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/NotebookComponentShell.tsx@@ -48,7 +48,7 @@ import {NotebookComponentToolbarExtrasContext,withoutNotebookMenuIcons,} from './componentToolbarExtras'-import { getNotebookObjectProp, getNotebookStringProp } from './documentModel'+import { getNotebookObjectProp, getNotebookStringProp, isDiscussionCommentNode } from './documentModel'import { InsertMenuSelectionDirection } from './editorTypes'import { installNotebookJupyterEditorKeys } from './jupyterEditorKeys'import { resolveNotebookJupyterKey, useNotebookJupyterCommands, useNotebookJupyterStoreValue } from './jupyterMode'@@ -360,7 +360,8 @@ export function NotebookComponentShell({return true}- const jupyter = useNotebookJupyterCommands()+ const jupyterCommands = useNotebookJupyterCommands()+ const jupyter = isDiscussionCommentNode(node) ? null : jupyterCommandsconst isJupyterCell = !!jupyter && jupyter.config.cellTagNames.includes(node.tagName)const jupyterStore = isJupyterCell ? jupyter.store : nullconst isJupyterActive = useNotebookJupyterStoreValue((state) => !!jupyter && state.activeCellId === node.id)@@ -566,7 +567,7 @@ export function NotebookComponentShell({}}- if (event.key === 'Backspace') {+ if (event.key === 'Backspace' || (event.key === 'Delete' && isDiscussionCommentNode(node))) {deleteNode()return}diff --git a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookDiscussionComment.tsx b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookDiscussionComment.tsxindex f5aa7e5d870c..c288da4b07f6 100644--- a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookDiscussionComment.tsx+++ b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookDiscussionComment.tsx@@ -1,7 +1,7 @@import { useValues } from 'kea'import { KeyboardEvent, useEffect, useRef, useState } from 'react'-import { IconSend, IconTrash } from '@posthog/icons'+import { IconCheck, IconSend, IconTrash } from '@posthog/icons'import { LemonButton, ProfilePicture } from '@posthog/lemon-ui'import { wasNotebookNodeJustInserted } from 'lib/components/MarkdownNotebook/freshlyInserted'@@ -68,6 +68,7 @@ export function getNotebookDiscussionCommentTitle(node: NotebookComponentBlockNoexport function NotebookDiscussionComment({node,mode,+ notebookMode,updateProps,deleteNode,}: NotebookComponentRenderProps): JSX.Element {@@ -77,7 +78,8 @@ export function NotebookDiscussionComment({const [draft, setDraft] = useState('')const [isHovered, setIsHovered] = useState(false)const repliesRef = useRef<HTMLDivElement | null>(null)- const isEditable = mode === 'edit'+ const isEditable = (notebookMode ?? mode) === 'edit'+ const isResolved = node.props.resolved === trueconst draftText = draft.trim()// Light up the anchored highlight while the cursor is over the thread.@@ -102,7 +104,7 @@ export function NotebookDiscussionComment({}, [replies.length])const submitReply = (): void => {- if (!draftText || !isEditable) {+ if (!draftText || !isEditable || isResolved) {return}@@ -134,6 +136,7 @@ export function NotebookDiscussionComment({data-attr="notebook-discussion-comment"><div className="MarkdownNotebook__discussion-comment-replies" ref={repliesRef}>+ {isResolved ? <div className="text-muted">Resolved</div> : null}{replies.map((reply) => (<div key={reply.id} className="MarkdownNotebook__discussion-comment-reply"><ProfilePicture user={{ first_name: reply.author }} size="sm" />@@ -158,39 +161,49 @@ export function NotebookDiscussionComment({</div>{isEditable ? (<div className="MarkdownNotebook__discussion-comment-composer">- <div className="flex flex-col rounded input-like">- <textarea- className="LemonTextArea MarkdownNotebook__discussion-comment-input w-full rounded"- value={draft}- onChange={(event) => {- event.stopPropagation()- setDraft(event.currentTarget.value)- }}- onKeyDown={handleComposerKeyDown}- placeholder={replies.length ? 'Reply...' : 'Comment...'}- rows={1}- autoFocus={wasNotebookNodeJustInserted(node.id)}- data-attr="notebook-discussion-comment-input"- />- </div>+ {!isResolved ? (+ <div className="flex flex-col rounded input-like">+ <textarea+ className="LemonTextArea MarkdownNotebook__discussion-comment-input w-full rounded"+ value={draft}+ onChange={(event) => {+ event.stopPropagation()+ setDraft(event.currentTarget.value)+ }}+ onKeyDown={handleComposerKeyDown}+ placeholder={replies.length ? 'Reply...' : 'Comment...'}+ rows={1}+ autoFocus={wasNotebookNodeJustInserted(node.id)}+ data-attr="notebook-discussion-comment-input"+ />+ </div>+ ) : null}<div className="MarkdownNotebook__discussion-comment-actions">- {isEditable ? (+ <LemonButton+ size="xsmall"+ icon={<IconCheck />}+ onClick={() => updateProps({ resolved: !isResolved })}+ data-attr="notebook-discussion-comment-resolve"+ >+ {isResolved ? 'Reopen' : 'Resolve'}+ </LemonButton>+ <LemonButton+ size="xsmall"+ icon={<IconTrash />}+ tooltip="Delete thread"+ aria-label="Delete thread"+ onClick={deleteNode}+ />+ {!isResolved ? (<LemonButtonsize="xsmall"- icon={<IconTrash />}- tooltip="Delete thread"- aria-label="Delete thread"- onClick={deleteNode}+ type="primary"+ icon={<IconSend />}+ onClick={submitReply}+ disabledReason={draftText ? undefined : 'Write a reply first'}+ aria-label="Send reply"/>) : null}- <LemonButton- size="xsmall"- type="primary"- icon={<IconSend />}- onClick={submitReply}- disabledReason={draftText ? undefined : 'Write a reply first'}- aria-label="Send reply"- /></div></div>) : null}diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsxindex 233c4dabeba4..83c10ad5d477 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx@@ -2,6 +2,7 @@ import { fireEvent, render, screen, within } from '@testing-library/react'import {buildInsertCommands,+ MarkdownNotebook,getMarkdownNotebookDefaultRegistry,mergeMarkdownNotebookRegistries,omitInsertCommands,@@ -153,7 +154,39 @@ describe('markdownNotebookRegistry', () => {})describe('discussion comment composer', () => {- const renderCommentShell = (componentPanels: ComponentPanelVisibility): ReturnType<typeof render> => {+ it('persists replies and resolution after reopening, and deletes only the thread', () => {+ const onChange = jest.fn()+ const markdown =+ '# Notes\n\n<Comment ref="note" replies={[]} />\n\nA <ref id="note">useful</ref> paragraph.'+ const { container, unmount } = render(+ <MarkdownNotebook value={markdown} onChange={onChange} registry={NOTEBOOK_MARKDOWN_REGISTRY} />+ )+ fireEvent.change(container.querySelector('textarea[data-attr="notebook-discussion-comment-input"]')!, {+ target: { value: 'Please review.' },+ })+ fireEvent.click(container.querySelector('[aria-label="Send reply"]')!)+ fireEvent.click(screen.getByText('Resolve'))+ const saved = onChange.mock.calls.at(-1)![0] as string+ expect(saved).toContain('Please review.')+ expect(parseMarkdownNotebook(saved).nodes.find((node) => node.type === 'component')).toMatchObject({+ props: { resolved: true },+ })+ unmount()++ const reopened = render(+ <MarkdownNotebook value={saved} onChange={onChange} registry={NOTEBOOK_MARKDOWN_REGISTRY} />+ )+ expect(reopened.container.querySelector('[data-attr="notebook-discussion-comment-input"]')).toBeNull()+ fireEvent.click(screen.getByText('Reopen'))+ expect(reopened.container.querySelector('[data-attr="notebook-discussion-comment-input"]')).not.toBeNull()+ fireEvent.click(reopened.container.querySelector('[aria-label="Delete thread"]')!)+ expect(onChange.mock.calls.at(-1)![0]).toBe('# Notes\n\nA useful paragraph.')+ })++ const renderCommentShell = (+ componentPanels: ComponentPanelVisibility,+ mode: 'edit' | 'view'+ ): ReturnType<typeof render> => {// No `showFilters` in props: composer visibility is driven by the transient panel// state, so the open state never has to be written into the shared document markdown.const node: NotebookComponentBlockNode = {@@ -165,7 +198,7 @@ describe('markdownNotebookRegistry', () => {return render(<NotebookComponentShellnode={node}- mode="edit"+ mode={mode}componentPanels={componentPanels}persistComponentPanelVisibility={false}isSelected={false}@@ -183,14 +216,12 @@ describe('markdownNotebookRegistry', () => {)}- // The edit panel is what makes the composer editable, so a thread renders its composer- // when that panel is open and the read-only view branch (no composer) when it is closed.- // Insertion opens the panel transiently, so the composer never depends on a persisted prop.it.each([- ['renders the composer when the edit panel is open', { filters: true, results: true }, true],- ['renders no composer when the edit panel is closed', { filters: false, results: true }, false],- ])('%s', (_label, componentPanels, expectComposer) => {- const { container } = renderCommentShell(componentPanels)+ ['new thread', { filters: true, results: true }, 'edit', true],+ ['reopened thread', { filters: false, results: true }, 'edit', true],+ ['read-only notebook', { filters: false, results: true }, 'view', false],+ ] as const)('uses notebook permissions for a %s', (_label, componentPanels, mode, expectComposer) => {+ const { container } = renderCommentShell(componentPanels, mode)const composer = container.querySelector('[data-attr="notebook-discussion-comment-input"]')expect(composer !== null).toBe(expectComposer)})diff --git a/products/notebooks/backend/sql_v2_state.py b/products/notebooks/backend/sql_v2_state.pyindex d02715a67d30..9b90a36f80cb 100644--- a/products/notebooks/backend/sql_v2_state.py+++ b/products/notebooks/backend/sql_v2_state.py@@ -330,7 +330,9 @@ def _merge_prose_cells(cells: list[NotebookCellState], content: Any) -> list[Notby_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):+ for block in iter_markdown_blocks(+ markdown, max_prose_blocks=MAX_ADDRESSABLE_PROSE_BLOCKS, group_anchored_prose=True+ ):if block.kind == "prose":ordered.append(NotebookCellState(diff --git a/products/notebooks/backend/test/test_sql_v2_state.py b/products/notebooks/backend/test/test_sql_v2_state.pyindex 9617e5c3dcc5..198a5a62ed07 100644--- a/products/notebooks/backend/test/test_sql_v2_state.py+++ b/products/notebooks/backend/test/test_sql_v2_state.py@@ -174,6 +174,34 @@ def cells_markdown(count: int) -> dict[str, Any]:class TestMarkdownBlockSpans(SimpleTestCase):+ @parameterized.expand(+ [+ ("paragraphs", "First paragraph.\n\nSecond paragraph."),+ ("headings_and_table", "## Summary\n\n| A | B |\n| --- | --- |\n| 1 | 2 |\n\nClosing note."),+ ("fenced_example", "```python\nx = 1\n\n\n<!--ph:phb-example-->\n```\n\nExplanation."),+ ]+ )+ def test_anchored_cell_includes_all_its_markdown(self, _name: str, source: str) -> None:+ markdown = f"# Title\n\n\n<!--ph:phb-cell-->\n{source}\n\n\nNext cell."+ blocks = list(iter_markdown_blocks(markdown, group_anchored_prose=True))+ assert [block.source for block in blocks] == ["# Title", source, "Next cell."]+ assert blocks[1].node_id == "phb-cell"+ assert markdown[blocks[1].start : blocks[1].end] == source++ @parameterized.expand(+ [+ ("anchor", "<!--ph:phb-next-->\nNext cell."),+ ("component", '<SQLV2 nodeId="next" code="select 1" />'),+ ("comment", '<Comment ref="note" replies={[]} />'),+ ]+ )+ def test_anchored_cell_stops_before_other_addressable_content(self, _name: str, following: str) -> None:+ blocks = list(+ iter_markdown_blocks(f"<!--ph:phb-cell-->\nFirst.\n\nSecond.\n\n{following}", group_anchored_prose=True)+ )+ assert len(blocks) == 2+ assert blocks[0].source == "First.\n\nSecond."+MARKDOWN = ("# Title\n\n""Some prose.\nA second line.\n\n"@@ -459,7 +487,8 @@ class TestNotebookCellState(APIBaseTest):def test_state_endpoint_returns_cells_and_kernel(self, _mock_enabled) -> None:notebook = self._notebook('<SQLV2 nodeId="s" code="select 1" returnVariable="df" />\n\n'- '<PythonV2 nodeId="p" code="x = df.head()" returnVariable="x" />'+ '<PythonV2 nodeId="p" code="x = df.head()" returnVariable="x" />\n\n\n'+ "<!--ph:phb-note-->\nFirst paragraph.\n\nSecond paragraph.")notebook.variables = [{"name": "limit", "type": "number", "value": 10}]notebook.save()@@ -478,5 +507,6 @@ class TestNotebookCellState(APIBaseTest):assert by_node["s"]["dependents"] == ["p"]assert by_node["p"]["status"] == "never_run"assert by_node["p"]["depends_on"] == ["s"]+ assert by_node["phb-note"]["code"] == "First paragraph.\n\nSecond paragraph."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.pyindex e50a40147651..b4f589aafeeb 100644--- a/products/notebooks/backend/util.py+++ b/products/notebooks/backend/util.py@@ -372,13 +372,38 @@ class MarkdownBlock:end: int-def iter_markdown_blocks(markdown: str, max_prose_blocks: int | None = None) -> Iterator[MarkdownBlock]:+def _get_anchored_markdown_cell_end(lines: list[str], start: int) -> int:+ end = start+ while end < len(lines):+ stripped = lines[end].strip()+ if _MARKDOWN_NODE_ANCHOR_REGEX.match(stripped) or _opens_markdown_component_block(lines, end):+ break+ if not stripped:+ if end + 1 >= len(lines) or not lines[end + 1].strip():+ break+ end += 1+ continue+ if stripped.startswith("```"):+ end = _get_markdown_code_block_end(lines, end)+ else:+ end += 1+ while end > start and not lines[end - 1].strip():+ end -= 1+ return end+++def iter_markdown_blocks(+ markdown: str, max_prose_blocks: int | None = None, *, group_anchored_prose: bool = False+) -> Iterator[MarkdownBlock]:"""Walk every block of a markdown notebook, prose included.A block whose document carries an anchor above it takes that stored id, which survives anedit to the block. A block without one falls back to an id derived from its own content, sothe id changes when the block changes and a caller must resolve it against the read it edits.+ `group_anchored_prose` keeps an anchored markdown cell's paragraphs together until a card+ boundary, another anchor, or a component, so cell edits replace all of its prose.+`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-characterblocks, so an unbounded walk lets one request allocate for minutes. The walk continues past@@ -453,6 +478,23 @@ def iter_markdown_blocks(markdown: str, max_prose_blocks: int | None = None) ->line_index += 1continue+ if (+ group_anchored_prose+ and pending_anchor_id is not None+ and pending_anchor_id not in claimed_anchor_ids+ and not _opens_markdown_component_block(lines, line_index)+ ):+ end_line_index = _get_anchored_markdown_cell_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, claim_anchor_id()+ )+ pending_anchor_id = None+ consume(line_index, end_line_index)+ line_index = end_line_index+ continue+if lines[line_index].strip().startswith("```"):end_line_index = _get_markdown_code_block_end(lines, line_index)if prose_budget_left():diff --git a/services/mcp/src/tools/notebooks/deleteCell.ts b/services/mcp/src/tools/notebooks/deleteCell.tsindex 6c716418973a..3907a3f9a3ef 100644--- a/services/mcp/src/tools/notebooks/deleteCell.ts+++ b/services/mcp/src/tools/notebooks/deleteCell.ts@@ -4,7 +4,7 @@ import { withInformationalResponse } from '@/tools/tool-utils'import type { Context, ToolBase } from '@/tools/types'import { directDependents, findCellTag, parseCellTags, removeCellTag } from './cellTags'-import { applyMarkdownEdit, fetchMarkdownNotebook } from './markdownDoc'+import { applyMarkdownEdit, fetchMarkdownNotebook, replaceMarkdownCell } from './markdownDoc'import { NOTEBOOK_SHORT_ID_DESCRIPTION, notebookIdAliases } from './notebookId'const DeleteCellInputSchema = z@@ -28,7 +28,8 @@ export const deleteCellHandler: ToolBase<typeof NotebooksDeleteCellSchema, Deletconst initial = await fetchMarkdownNotebook(context, params.notebook_id)const existing = findCellTag(initial.markdown, params.node_id)if (!existing) {- throw new Error(`No cell with node_id ${params.node_id} in notebook ${params.notebook_id}.`)+ await replaceMarkdownCell(context, params.notebook_id, params.node_id, '')+ return withInformationalResponse({ deleted: true as const, orphaned_dependents: [] }, 'notebook-cell-refs')}// Computed before the delete: dependents reference the doomed cell's dataframe and will// break (or silently run against its last result) until the agent rewrites or removes them.diff --git a/services/mcp/src/tools/notebooks/markdownDoc.ts b/services/mcp/src/tools/notebooks/markdownDoc.tsindex dcd2be30c034..05a05559a4df 100644--- a/services/mcp/src/tools/notebooks/markdownDoc.ts+++ b/services/mcp/src/tools/notebooks/markdownDoc.ts@@ -120,3 +120,61 @@ export async function applyMarkdownEdit(}throw lastError}++export async function replaceMarkdownCell(+ context: Context,+ notebookId: string,+ nodeId: string,+ replacement: string+): Promise<void> {+ 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 block = state.cells.find((cell) => cell.node_id === nodeId)+ if (!block) {+ throw new Error(+ `No cell with node_id ${nodeId} in notebook ${notebookId}. Read the current ids with notebooks-get.`+ )+ }+ if (block.cell_type !== 'markdown') {+ throw new Error(`Cell ${nodeId} 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 === nodeId)+ if (sameId.length > 1) {+ throw new Error(+ `Cell ${nodeId} names ${sameId.length} blocks in notebook ${notebookId}, 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, notebookId)+ if (notebook.version !== state.version) {+ throw new Error(+ `Notebook ${notebookId} changed since cell ${nodeId} 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 ${nodeId} is not where the read placed it in notebook ${notebookId}. Read it again with notebooks-get and retry with the id it returns.`+ )+ }++ let start = block.start+ if (!replacement) {+ const anchor = /<!--ph:(phb-[A-Za-z0-9._-]{1,124})-->(?:\r\n|\r|\n)$/.exec(notebook.markdown.slice(0, start))+ if (anchor?.[1] === nodeId) {+ start = anchor.index+ }+ }+ const nextMarkdown = notebook.markdown.slice(0, start) + replacement + notebook.markdown.slice(block.end)+ await saveMarkdown(context, notebook, nextMarkdown)+}diff --git a/services/mcp/src/tools/notebooks/updateCell.ts b/services/mcp/src/tools/notebooks/updateCell.tsindex 74f76cfec06c..cf5730469f5d 100644--- a/services/mcp/src/tools/notebooks/updateCell.ts+++ b/services/mcp/src/tools/notebooks/updateCell.ts@@ -1,6 +1,5 @@import { z } from 'zod'-import type { Schemas } from '@/api/generated'import type { Context, ToolBase } from '@/tools/types'import {@@ -21,7 +20,7 @@ import {startsComponentTag,upsertProp,} from './cellTags'-import { applyMarkdownEdit, fetchMarkdownNotebook, notebookPathFor, saveMarkdown } from './markdownDoc'+import { applyMarkdownEdit, fetchMarkdownNotebook, notebookPathFor, replaceMarkdownCell } from './markdownDoc'import { NOTEBOOK_SHORT_ID_DESCRIPTION, notebookIdAliases } from './notebookId'/**@@ -109,49 +108,7 @@ async function updateProseCell(}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)+ await replaceMarkdownCell(context, params.notebook_id, params.node_id, next.trim())return { node_id: params.node_id, updated: true }}diff --git a/services/mcp/tests/unit/notebook-cell-tools.test.ts b/services/mcp/tests/unit/notebook-cell-tools.test.tsindex 86703b8ae0b7..dfff8ba4e133 100644--- a/services/mcp/tests/unit/notebook-cell-tools.test.ts+++ b/services/mcp/tests/unit/notebook-cell-tools.test.ts@@ -854,6 +854,62 @@ describe('notebook cell tools', () => {})describe('markdown cells', () => {+ it.each(['update', 'delete'] as const)(+ '%s preserves neighboring cells and operates on the full markdown span',+ async (operation) => {+ const source = '## Overview\n\nFirst paragraph.\n\nSecond paragraph.'+ const prefix = '# Title\n\n\n<!--ph:phb-note-->\n'+ const suffix = '\n\n\nA separate cell.'+ const state = makeState(prefix + source + suffix)+ state.stateCells = [+ {+ node_id: 'phb-note',+ cell_type: 'markdown',+ code: source,+ start: prefix.length,+ end: prefix.length + source.length,+ },+ ]+ const context = createMockContext(state)+ if (operation === 'update') {+ await updateCellHandler(context, {+ notebook_id: 'aBcD1234',+ node_id: 'phb-note',+ markdown: 'Replacement.',+ })+ expect(state.markdown).toBe(prefix + 'Replacement.' + suffix)+ } else {+ await deleteCellHandler(context, { notebook_id: 'aBcD1234', node_id: 'phb-note' })+ expect(state.markdown).toBe('# Title\n\n\n' + suffix)+ }+ expect(state.runBodies).toEqual([])+ }+ )++ it.each(['version', 'span', 'duplicate'] as const)(+ 'refuses to delete a markdown cell with a mismatched %s',+ async (mismatch) => {+ const state = makeState('First paragraph.')+ const cell = {+ node_id: 'mdp-note-0',+ cell_type: 'markdown',+ code: 'First paragraph.',+ start: 0,+ end: 16,+ }+ state.stateCells = mismatch === 'duplicate' ? [cell, cell] : [cell]+ if (mismatch === 'version') {+ state.stateVersion = state.version + 1+ } else if (mismatch === 'span') {+ cell.start = 1+ }+ await expect(+ deleteCellHandler(createMockContext(state), { notebook_id: 'aBcD1234', node_id: cell.node_id })+ ).rejects.toThrow()+ expect(state.saveBodies).toEqual([])+ }+ )+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 }