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): comment threads, mentions, downgrade path, drag-to-reorder, conflict diffs (#63257)

Marius Andra6015426506c5
diff --git a/frontend/src/lib/components/MarkdownNotebook/COMPONENTS.md b/frontend/src/lib/components/MarkdownNotebook/COMPONENTS.md
index 8dfcf4a84bd3..e90ef1abd1a5 100644
--- a/frontend/src/lib/components/MarkdownNotebook/COMPONENTS.md
+++ b/frontend/src/lib/components/MarkdownNotebook/COMPONENTS.md
@@ -184,6 +184,8 @@ If the node type does not exist yet, create the notebook node first under `front
Do not reuse the tags of the default registry (`registry.tsx`): `Query`, `Image`, `Divider`, `Embed`, `Latex`, `Python`, `DuckSQL`, `HogQLSQL`, `RecordingPlaylist`, `FeatureFlag`, `Experiment`, `Survey`, `Person`, `Group`, `Cohort`, `Map`.
The internal AI tags `Prompt` and `Chat` are also reserved (registered by the notebooks scene).
`Image` and `Divider` are special: they serialize back to plain markdown (`![alt](src)` and `---`) rather than component-tag syntax.
+`Comment` is special too: its authorial-note flavor (`text` prop) serializes as a markdown `<!-- … -->` comment, while its discussion flavor (`ref` + `replies` props, a Google Docs-style thread anchored to an inline `<ref id="…">` highlight) serializes as a regular `<Comment … />` tag.
+The lowercase inline tags `<ref>` and `<mention>` are part of the inline grammar, not components — component tags must start with an uppercase letter.
Choose a specific tag name that describes the persisted block.
## Testing checklist
diff --git a/frontend/src/lib/components/MarkdownNotebook/FormattingToolbar.tsx b/frontend/src/lib/components/MarkdownNotebook/FormattingToolbar.tsx
index aa3c1dd41413..c59ccb7cef03 100644
--- a/frontend/src/lib/components/MarkdownNotebook/FormattingToolbar.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/FormattingToolbar.tsx
@@ -1,7 +1,7 @@
import clsx from 'clsx'
import { type CSSProperties, useEffect, useLayoutEffect, useRef, useState } from 'react'
-import { IconCode, IconCopy, IconQuote, IconSparkles } from '@posthog/icons'
+import { IconCode, IconComment, IconCopy, IconQuote, IconSparkles } from '@posthog/icons'
import { LemonButton, LemonInput } from '@posthog/lemon-ui'
import { IconBold, IconItalic, IconLink } from 'lib/lemon-ui/icons'
@@ -44,6 +44,7 @@ export function FormattingToolbar({
setBlockStyle,
copySelection,
askAIAboutSelection,
+ startInlineCommentAtSelection,
lockPosition,
}: {
selectedBlockStyle: TextBlockStyle | null
@@ -58,6 +59,7 @@ export function FormattingToolbar({
setBlockStyle: (style: TextBlockStyle) => void
copySelection: () => void
askAIAboutSelection?: () => void
+ startInlineCommentAtSelection?: () => void
lockPosition: () => void
}): JSX.Element {
const [isLinkEditorOpen, setIsLinkEditorOpen] = useState(initialLinkEditorOpen)
@@ -243,6 +245,15 @@ export function FormattingToolbar({
/>
</>
) : null}
+ {showInlineActions && startInlineCommentAtSelection ? (
+ <LemonButton
+ size="xsmall"
+ icon={<IconComment />}
+ tooltip="Comment"
+ aria-label="Comment on selection"
+ onClick={startInlineCommentAtSelection}
+ />
+ ) : null}
{showInlineActions && askAIAboutSelection ? (
<LemonButton
size="xsmall"
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss
index 0e61eeeec8ce..a01c0222b259 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss
@@ -23,6 +23,7 @@
var(--markdown-notebook-inline-control-width) + var(--markdown-notebook-inline-control-gap)
);
--markdown-notebook-canvas-max-width: 56rem;
+ --markdown-notebook-comment-gutter: 19rem;
width: 100%;
min-height: 100%;
@@ -271,6 +272,129 @@
opacity: 1;
}
+.MarkdownNotebook__drag-handle {
+ position: absolute;
+ top: 0.25rem;
+ left: 0;
+ z-index: var(--z-raised);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: var(--markdown-notebook-inline-control-width);
+ height: 1.25rem;
+ color: var(--color-text-secondary);
+ cursor: grab;
+ user-select: none;
+ opacity: 0;
+ transition: opacity 120ms ease;
+}
+
+.MarkdownNotebook__drag-handle svg {
+ width: 1rem;
+ height: 1rem;
+}
+
+.MarkdownNotebook__row:hover .MarkdownNotebook__drag-handle {
+ opacity: 0.5;
+}
+
+.MarkdownNotebook__drag-handle:hover,
+.MarkdownNotebook__drag-handle:focus-visible {
+ opacity: 1;
+}
+
+.MarkdownNotebook__drag-handle:active {
+ cursor: grabbing;
+ opacity: 1;
+}
+
+/* Inside a text card the rows are already offset by the group's margin, so the handle
+ reaches back into the canvas gutter, mirroring the inline insert menu hit area. */
+.MarkdownNotebook__text-group .MarkdownNotebook__drag-handle {
+ left: calc(var(--markdown-notebook-content-offset) * -1 - 1rem);
+}
+
+.MarkdownNotebook__blockquote-group .MarkdownNotebook__drag-handle {
+ left: calc(var(--markdown-notebook-content-offset) * -1 - 1rem - var(--markdown-notebook-quote-indent));
+}
+
+/* Blank rows show the inline + button in the same gutter slot: the handle sits beside it. */
+.MarkdownNotebook__row:has(.MarkdownNotebook__line-insert-menu-hit-area) .MarkdownNotebook__drag-handle {
+ transform: translateX(var(--markdown-notebook-inline-control-width));
+}
+
+/* The block comment button occupies the gutter slot left of the drag handle. */
+.MarkdownNotebook__block-comment-button {
+ position: absolute;
+ top: 0.25rem;
+ left: calc(var(--markdown-notebook-inline-control-width) * -1);
+ z-index: var(--z-raised);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: var(--markdown-notebook-inline-control-width);
+ height: 1.25rem;
+ color: var(--color-text-secondary);
+ cursor: pointer;
+ user-select: none;
+ opacity: 0;
+ transition: opacity 120ms ease;
+}
+
+.MarkdownNotebook__block-comment-button svg {
+ width: 1rem;
+ height: 1rem;
+}
+
+.MarkdownNotebook__row:hover .MarkdownNotebook__block-comment-button {
+ opacity: 0.5;
+}
+
+.MarkdownNotebook__block-comment-button:hover,
+.MarkdownNotebook__block-comment-button:focus-visible {
+ opacity: 1;
+}
+
+.MarkdownNotebook__text-group .MarkdownNotebook__block-comment-button {
+ left: calc(var(--markdown-notebook-content-offset) * -1 - 1rem - var(--markdown-notebook-inline-control-width));
+}
+
+.MarkdownNotebook__blockquote-group .MarkdownNotebook__block-comment-button {
+ left: calc(
+ var(--markdown-notebook-content-offset) * -1 -
+ 1rem - var(--markdown-notebook-quote-indent) - var(--markdown-notebook-inline-control-width)
+ );
+}
+
+.MarkdownNotebook__row:has(.MarkdownNotebook__line-insert-menu-hit-area) .MarkdownNotebook__block-comment-button {
+ transform: translateX(var(--markdown-notebook-inline-control-width));
+}
+
+.MarkdownNotebook__row--dragging {
+ opacity: 0.4;
+}
+
+.MarkdownNotebook__drop-indicator {
+ position: absolute;
+ top: -0.125rem;
+ right: 0;
+ left: var(--markdown-notebook-content-offset);
+ z-index: var(--z-raised);
+ height: 0.1875rem;
+ pointer-events: none;
+ background: var(--primary);
+ border-radius: 999px;
+}
+
+.MarkdownNotebook__drop-indicator--after {
+ top: auto;
+ bottom: -0.125rem;
+}
+
+.MarkdownNotebook__text-group .MarkdownNotebook__drop-indicator {
+ left: 0;
+}
+
.MarkdownNotebook__insert-boundary {
position: relative;
width: 100%;
@@ -1586,3 +1710,151 @@ button.MarkdownNotebook__component-title:focus-visible {
.MarkdownNotebook__real-node-content--resizeable {
resize: vertical;
}
+
+/* Inline ref highlights: text a chat thread is anchored to. */
+.MarkdownNotebook__ref {
+ background: var(--color-bg-fill-highlight-100, rgb(235 145 0 / 15%));
+ border-bottom: 2px solid var(--color-border-warning, rgb(235 145 0 / 60%));
+ border-radius: 2px;
+}
+
+.MarkdownNotebook__ref--active,
+.MarkdownNotebook__ref:hover {
+ background: var(--color-bg-fill-highlight-200, rgb(235 145 0 / 30%));
+}
+
+/* Inline mentions keep their person id in the markdown; the text is the display label. */
+.MarkdownNotebook__mention {
+ padding: 0 0.125rem;
+ font-weight: 500;
+ background: var(--color-bg-fill-highlight-100);
+ border-radius: 0.25rem;
+}
+
+/* Clicking the <ref> highlight flashes the thread it anchors. */
+.MarkdownNotebook__component-shell--comment-flash .MarkdownNotebook__discussion-comment {
+ border-color: var(--color-border-warning, rgb(235 145 0 / 80%));
+ box-shadow: 0 0 0 3px rgb(235 145 0 / 20%);
+ transition:
+ box-shadow 0.2s ease,
+ border-color 0.2s ease;
+}
+
+/* The comment card carries its own chrome (composer, delete) -- the shell toolbar is noise. */
+.MarkdownNotebook__row--margin-comment .MarkdownNotebook__component-toolbar {
+ display: none;
+}
+
+.MarkdownNotebook__row--margin-comment .MarkdownNotebook__component-shell {
+ padding: 0;
+ background: none;
+ border: none;
+ box-shadow: none;
+}
+
+/* The gutter widens the effective canvas, so the source button must shift along with it
+ instead of floating over the comment column. */
+.MarkdownNotebook--comments-margin .MarkdownNotebook__debug-toolbar {
+ right: calc(
+ max(
+ calc((100% - var(--markdown-notebook-canvas-max-width) - var(--markdown-notebook-comment-gutter)) / 2),
+ 0px
+ ) +
+ 0.5rem
+ );
+}
+
+/* With comment threads present and enough room, the canvas reserves a right gutter wide
+ enough for the whole thread column, pushing the text content left. */
+.MarkdownNotebook--comments-margin .MarkdownNotebook__canvas {
+ max-width: calc(var(--markdown-notebook-canvas-max-width) + var(--markdown-notebook-comment-gutter));
+ padding-right: var(--markdown-notebook-comment-gutter);
+}
+
+/* A thread row sits right above the block it refers to and keeps zero height, so the
+ absolutely positioned card naturally aligns with the top of the highlighted content. */
+.MarkdownNotebook--comments-margin .MarkdownNotebook__row--margin-comment {
+ z-index: 1;
+ height: 0;
+
+ .MarkdownNotebook__component-shell {
+ position: absolute;
+ top: 0;
+ left: calc(100% + 1rem);
+ width: calc(var(--markdown-notebook-comment-gutter) - 2rem);
+ }
+}
+
+/* Without a wide-enough container the thread flows inline as a right-aligned card. */
+.MarkdownNotebook--comments-inline .MarkdownNotebook__row--margin-comment .MarkdownNotebook__component-shell {
+ max-width: 24rem;
+ margin-left: auto;
+}
+
+.MarkdownNotebook__discussion-comment {
+ display: flex;
+ flex-direction: column;
+ gap: 0.5rem;
+ padding: 0.5rem;
+ font-size: 0.8125rem;
+ background: var(--color-bg-surface-primary);
+ border: 1px solid var(--color-border-primary);
+ border-radius: 0.375rem;
+ box-shadow: 0 1px 2px rgb(0 0 0 / 5%);
+}
+
+.MarkdownNotebook__discussion-comment-replies {
+ display: flex;
+ flex-direction: column;
+ gap: 0.5rem;
+
+ /* Long threads cap out and scroll, keeping the composer reachable. */
+ max-height: 14rem;
+ overflow-y: auto;
+}
+
+.MarkdownNotebook__discussion-comment-reply {
+ display: flex;
+ gap: 0.5rem;
+ align-items: flex-start;
+}
+
+.MarkdownNotebook__discussion-comment-reply-body {
+ min-width: 0;
+}
+
+.MarkdownNotebook__discussion-comment-reply-meta {
+ display: flex;
+ gap: 0.375rem;
+ align-items: baseline;
+}
+
+.MarkdownNotebook__discussion-comment-reply-author {
+ font-weight: 600;
+}
+
+.MarkdownNotebook__discussion-comment-reply-time {
+ font-size: 0.6875rem;
+ color: var(--color-text-secondary);
+}
+
+.MarkdownNotebook__discussion-comment-reply-text {
+ overflow-wrap: anywhere;
+ white-space: pre-wrap;
+}
+
+.MarkdownNotebook__discussion-comment-empty {
+ color: var(--color-text-secondary);
+}
+
+.MarkdownNotebook__discussion-comment-composer {
+ display: flex;
+ flex-direction: column;
+ gap: 0.375rem;
+}
+
+.MarkdownNotebook__discussion-comment-actions {
+ display: flex;
+ gap: 0.375rem;
+ justify-content: flex-end;
+}
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
index 72ba96544d37..1512a4424d19 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
@@ -2206,6 +2206,84 @@ Tail paragraph`
expect(container.querySelectorAll('[data-placeholder="Start writing..."]')).toHaveLength(0)
})
+ it('records keystrokes, mouse events, and commits into a downloadable debug log', async () => {
+ const createObjectURL = jest.fn((_blob: Blob) => 'blob:notebook-debug-log')
+ const revokeObjectURL = jest.fn()
+ Object.defineProperty(window.URL, 'createObjectURL', { value: createObjectURL, configurable: true })
+ Object.defineProperty(window.URL, 'revokeObjectURL', { value: revokeObjectURL, configurable: true })
+ const anchorClick = jest.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
+
+ try {
+ const { container } = render(
+ createElement(MarkdownNotebook, { value: withNotebookTitle('Hello there'), showDebug: true })
+ )
+ fireEvent.click(container.querySelector('button[aria-label="Edit markdown source"]') as HTMLButtonElement)
+ const logButton = container.querySelector(
+ '[data-attr="markdown-notebook-debug-log-toggle"]'
+ ) as HTMLButtonElement
+ expect(logButton.textContent).toEqual('Log')
+
+ fireEvent.click(logButton)
+ expect(logButton.textContent).toEqual('Stop')
+
+ const textBlock = getBodyTextBlock(container)
+ fireEvent.keyDown(textBlock, { key: 'a' })
+ fireEvent.mouseDown(textBlock, { clientX: 10, clientY: 20 })
+ updateContentEditableText(textBlock, 'Hello there friend')
+
+ fireEvent.click(logButton)
+ expect(logButton.textContent).toEqual('Log')
+ expect(anchorClick).toHaveBeenCalledTimes(1)
+ expect(createObjectURL).toHaveBeenCalledTimes(1)
+
+ const blob = createObjectURL.mock.calls[0][0]
+ // jsdom's Blob has no .text()
+ const blobText = await new Promise<string>((resolve, reject) => {
+ const reader = new FileReader()
+ reader.onload = () => resolve(String(reader.result))
+ reader.onerror = () => reject(reader.error as Error)
+ reader.readAsText(blob)
+ })
+ const entries = blobText
+ .trim()
+ .split('\n')
+ .map((line) => JSON.parse(line) as Record<string, unknown>)
+ const entryTypes = entries.map((entry) => entry.type)
+
+ expect(entryTypes[0]).toEqual('start')
+ expect(entryTypes[entryTypes.length - 1]).toEqual('stop')
+ expect(entryTypes).toContain('keydown')
+ expect(entryTypes).toContain('mousedown')
+ expect(entryTypes).toContain('input')
+ expect(entryTypes).toContain('commit')
+ expect(entries[0].markdown).toEqual(withNotebookTitle('Hello there'))
+ const commitEntry = entries.find((entry) => entry.type === 'commit')
+ expect(commitEntry?.markdown).toEqual(withNotebookTitle('Hello there friend'))
+ const keydownEntry = entries.find((entry) => entry.type === 'keydown')
+ expect(keydownEntry?.key).toEqual('a')
+ } finally {
+ anchorClick.mockRestore()
+ }
+ })
+
+ it('scrolls to and flashes the comment thread when its ref highlight is clicked', () => {
+ const { container } = render(
+ createElement(MarkdownNotebook, {
+ value: withNotebookTitle(
+ '<Comment ref="banana" replies={[]} />\n\nNumbers <ref id="banana">look off</ref> here'
+ ),
+ })
+ )
+ const refSpan = container.querySelector('[data-notebook-ref="banana"]') as HTMLElement
+ expect(refSpan).toBeInstanceOf(HTMLElement)
+
+ fireEvent.click(refSpan)
+
+ const flashedShell = container.querySelector('.MarkdownNotebook__component-shell--comment-flash')
+ expect(flashedShell).toBeInstanceOf(HTMLElement)
+ expect(flashedShell?.closest('.MarkdownNotebook__row--margin-comment')).toBeInstanceOf(HTMLElement)
+ })
+
it('opens a synced markdown source drawer from the source button', async () => {
const { container } = render(createElement(MarkdownNotebook, { value: 'First paragraph', showDebug: true }))
const debugButton = container.querySelector('button[aria-label="Edit markdown source"]')
@@ -3635,6 +3713,118 @@ aXbc
- **Second item**`)
})
+ it('creates a comment thread above the block from a single-block selection', () => {
+ const onChange = jest.fn()
+ const { container } = render(
+ createElement(MarkdownNotebook, {
+ value: withNotebookTitle('Numbers look off here'),
+ onChange,
+ })
+ )
+ const paragraph = getBodyTextBlock(container)
+
+ selectTextAcrossNodes(getFirstTextNode(paragraph), 8, getFirstTextNode(paragraph), 'Numbers look'.length, true)
+ fireEvent.click(container.querySelector('button[aria-label="Comment on selection"]') as HTMLButtonElement)
+
+ const markdown = onChange.mock.calls[onChange.mock.calls.length - 1][0] as string
+ const refId = markdown.match(/<Comment ref="([^"]+)" replies={\[\]} \/>/)?.[1]
+ expect(refId).toBeTruthy()
+ expect(markdown).toEqual(`${TEST_NOTEBOOK_TITLE_MARKDOWN}
+
+<Comment ref="${refId}" replies={[]} />
+
+Numbers <ref id="${refId}">look</ref> off here`)
+ })
+
+ it('places a comment on the title row below it, keeping the heading first', () => {
+ const onChange = jest.fn()
+ const { container } = render(
+ createElement(MarkdownNotebook, {
+ value: withNotebookTitle('Body text'),
+ onChange,
+ })
+ )
+ const titleBlock = container.querySelector(NOTEBOOK_TEST_EDITABLE_SELECTOR) as HTMLElement
+
+ selectTextAcrossNodes(getFirstTextNode(titleBlock), 0, getFirstTextNode(titleBlock), 5, true)
+ fireEvent.click(container.querySelector('button[aria-label="Comment on selection"]') as HTMLButtonElement)
+
+ const markdown = onChange.mock.calls[onChange.mock.calls.length - 1][0] as string
+ const refId = markdown.match(/<Comment ref="([^"]+)" replies={\[\]} \/>/)?.[1]
+ expect(refId).toBeTruthy()
+ expect(markdown).toEqual(`# <ref id="${refId}">Noteb</ref>ook title
+
+<Comment ref="${refId}" replies={[]} />
+
+Body text`)
+ })
+
+ it('creates a block comment thread above a component from the gutter button', () => {
+ const onChange = jest.fn()
+ const { container } = render(
+ createElement(MarkdownNotebook, {
+ value: withNotebookTitle('<Query query={{"kind":"DataTableNode"}} />'),
+ onChange,
+ })
+ )
+ const commentButtons = Array.from(
+ container.querySelectorAll('[data-attr="markdown-notebook-block-comment-button"]')
+ )
+ expect(commentButtons).toHaveLength(1)
+
+ fireEvent.click(commentButtons[0] as HTMLElement)
+
+ expect(onChange).toHaveBeenLastCalledWith(`${TEST_NOTEBOOK_TITLE_MARKDOWN}
+
+<Comment replies={[]} />
+
+<Query query={{"kind":"DataTableNode"}} />`)
+ })
+
+ it('does not offer the block comment button in view mode', () => {
+ const { container } = render(
+ createElement(MarkdownNotebook, {
+ value: withNotebookTitle('<Query query={{"kind":"DataTableNode"}} />'),
+ mode: 'view',
+ })
+ )
+
+ expect(container.querySelectorAll('[data-attr="markdown-notebook-block-comment-button"]')).toHaveLength(0)
+ })
+
+ it('creates one comment thread spanning a multi-block selection', () => {
+ const onChange = jest.fn()
+ const { container } = render(
+ createElement(MarkdownNotebook, {
+ value: withNotebookTitle('Intro paragraph\n\n- First item\n- Second item'),
+ onChange,
+ })
+ )
+ const paragraph = getBodyTextBlock(container)
+ const listItems = getEditableListItems(container)
+
+ selectTextAcrossNodes(
+ getFirstTextNode(paragraph),
+ 0,
+ getFirstTextNode(listItems[1]),
+ 'Second item'.length,
+ true
+ )
+ fireEvent.click(container.querySelector('button[aria-label="Comment on selection"]') as HTMLButtonElement)
+
+ const markdown = onChange.mock.calls[onChange.mock.calls.length - 1][0] as string
+ const refId = markdown.match(/<Comment ref="([^"]+)" replies={\[\]} \/>/)?.[1]
+ expect(refId).toBeTruthy()
+ expect(markdown).toEqual(`${TEST_NOTEBOOK_TITLE_MARKDOWN}
+
+<Comment ref="${refId}" replies={[]} />
+
+<ref id="${refId}">Intro paragraph</ref>
+
+- <ref id="${refId}">First item</ref>
+- <ref id="${refId}">Second item</ref>`)
+ })
+
it('round-trips lists inside blockquotes as quoted lists', () => {
const markdown = `> Quote intro
> - First item
@@ -7981,4 +8171,181 @@ After component`,
expect(query).toContain(expectedBlock)
})
+
+ type DataTransferStub = {
+ setData: jest.Mock
+ getData: jest.Mock
+ setDragImage: jest.Mock
+ effectAllowed: string
+ dropEffect: string
+ }
+
+ function createDataTransferStub(): DataTransferStub {
+ return {
+ setData: jest.fn(),
+ getData: jest.fn(),
+ setDragImage: jest.fn(),
+ effectAllowed: '',
+ dropEffect: '',
+ }
+ }
+
+ /** jsdom has no MouseEvent-based DragEvent, so clientY/dataTransfer must be defined by hand. */
+ function fireDragEvent(
+ element: Element,
+ type: 'dragstart' | 'dragover' | 'drop' | 'dragend',
+ init: { dataTransfer: DataTransferStub; clientY?: number }
+ ): void {
+ const event = new Event(type, { bubbles: true, cancelable: true })
+ Object.defineProperties(event, {
+ dataTransfer: { value: init.dataTransfer },
+ clientY: { value: init.clientY ?? 0 },
+ })
+ fireEvent(element, event)
+ }
+
+ /** jsdom rects are all zeros: stack each row 40px tall so pointer math against row midpoints works. */
+ function mockNotebookRowRects(container: HTMLElement, rowHeight = 40): HTMLElement[] {
+ const rows = Array.from(container.querySelectorAll('.MarkdownNotebook__row')) as HTMLElement[]
+ rows.forEach((row, index) => {
+ const top = index * rowHeight
+ Object.defineProperty(row, 'getBoundingClientRect', {
+ configurable: true,
+ value: () => ({
+ top,
+ bottom: top + rowHeight,
+ height: rowHeight,
+ left: 0,
+ right: 800,
+ width: 800,
+ x: 0,
+ y: top,
+ toJSON: () => ({}),
+ }),
+ })
+ })
+ return rows
+ }
+
+ function getRowDragHandle(row: HTMLElement): HTMLElement {
+ const handle = row.querySelector('.MarkdownNotebook__drag-handle')
+
+ expect(handle).toBeInstanceOf(HTMLElement)
+
+ return handle as HTMLElement
+ }
+
+ it('moves a block below another block with drag and drop', () => {
+ const onChange = jest.fn()
+ const { container } = render(createElement(MarkdownNotebook, { value: '# Title\n\nAlpha\n\nBravo', onChange }))
+ const canvas = container.querySelector('.MarkdownNotebook__canvas') as HTMLElement
+ const rows = mockNotebookRowRects(container)
+ const dataTransfer = createDataTransferStub()
+
+ // Rows stack at 0-40 (title), 40-80 (Alpha), 80-120 (Bravo).
+ fireDragEvent(getRowDragHandle(rows[1]), 'dragstart', { dataTransfer })
+
+ expect(dataTransfer.setData).toHaveBeenCalledWith('text/plain', expect.any(String))
+ expect(dataTransfer.effectAllowed).toEqual('move')
+ expect(rows[1].classList.contains('MarkdownNotebook__row--dragging')).toBe(true)
+
+ fireDragEvent(canvas, 'dragover', { dataTransfer, clientY: 115 })
+
+ expect(container.querySelector('.MarkdownNotebook__drop-indicator')).toBeInstanceOf(HTMLElement)
+
+ fireDragEvent(canvas, 'drop', { dataTransfer, clientY: 115 })
+
+ expect(onChange).toHaveBeenLastCalledWith('# Title\n\nBravo\n\nAlpha')
+ expect(container.querySelector('.MarkdownNotebook__drop-indicator')).toBeNull()
+ expect(container.querySelector('.MarkdownNotebook__row--dragging')).toBeNull()
+ })
+
+ it('moves a block above an earlier block with drag and drop', () => {
+ const onChange = jest.fn()
+ const { container } = render(
+ createElement(MarkdownNotebook, { value: '# Title\n\nAlpha\n\nBravo\n\nCharlie', onChange })
+ )
+ const canvas = container.querySelector('.MarkdownNotebook__canvas') as HTMLElement
+ const rows = mockNotebookRowRects(container)
+ const dataTransfer = createDataTransferStub()
+
+ // Drag Charlie (120-160) above Alpha's midpoint (60): boundary right after the title.
+ fireDragEvent(getRowDragHandle(rows[3]), 'dragstart', { dataTransfer })
+ fireDragEvent(canvas, 'dragover', { dataTransfer, clientY: 50 })
+ fireDragEvent(canvas, 'drop', { dataTransfer, clientY: 50 })
+
+ expect(onChange).toHaveBeenLastCalledWith('# Title\n\nCharlie\n\nAlpha\n\nBravo')
+ })
+
+ it('does not render a drag handle for the title row or in view mode', () => {
+ const { container } = render(createElement(MarkdownNotebook, { value: '# Title\n\nAlpha' }))
+ const rows = Array.from(container.querySelectorAll('.MarkdownNotebook__row')) as HTMLElement[]
+
+ expect(rows[0].querySelector('.MarkdownNotebook__drag-handle')).toBeNull()
+ expect(rows[1].querySelector('.MarkdownNotebook__drag-handle')).toBeInstanceOf(HTMLElement)
+
+ const { container: viewContainer } = render(
+ createElement(MarkdownNotebook, { value: '# Title\n\nAlpha', mode: 'view' })
+ )
+
+ expect(viewContainer.querySelector('.MarkdownNotebook__drag-handle')).toBeNull()
+ })
+
+ it('keeps the document unchanged when a block is dropped at its current position', () => {
+ const onChange = jest.fn()
+ const { container } = render(createElement(MarkdownNotebook, { value: '# Title\n\nAlpha\n\nBravo', onChange }))
+ const canvas = container.querySelector('.MarkdownNotebook__canvas') as HTMLElement
+ const rows = mockNotebookRowRects(container)
+ const dataTransfer = createDataTransferStub()
+
+ // Dropping Alpha right back onto its own boundary is a no-op.
+ fireDragEvent(getRowDragHandle(rows[1]), 'dragstart', { dataTransfer })
+ fireDragEvent(canvas, 'dragover', { dataTransfer, clientY: 50 })
+ fireDragEvent(canvas, 'drop', { dataTransfer, clientY: 50 })
+
+ expect(onChange).not.toHaveBeenCalled()
+ expect(container.querySelector('.MarkdownNotebook__row--dragging')).toBeNull()
+
+ // Dropping above the title clamps to the first body boundary: still a no-op for Alpha.
+ fireDragEvent(getRowDragHandle(rows[1]), 'dragstart', { dataTransfer })
+ fireDragEvent(canvas, 'dragover', { dataTransfer, clientY: 5 })
+ fireDragEvent(canvas, 'drop', { dataTransfer, clientY: 5 })
+
+ expect(onChange).not.toHaveBeenCalled()
+ })
+
+ it('never lets a dragged block land before the title row', () => {
+ const onChange = jest.fn()
+ const { container } = render(createElement(MarkdownNotebook, { value: '# Title\n\nAlpha\n\nBravo', onChange }))
+ const canvas = container.querySelector('.MarkdownNotebook__canvas') as HTMLElement
+ const rows = mockNotebookRowRects(container)
+ const dataTransfer = createDataTransferStub()
+
+ // Dragging Bravo above the title clamps the drop to just after the title.
+ fireDragEvent(getRowDragHandle(rows[2]), 'dragstart', { dataTransfer })
+ fireDragEvent(canvas, 'dragover', { dataTransfer, clientY: 5 })
+ fireDragEvent(canvas, 'drop', { dataTransfer, clientY: 5 })
+
+ expect(onChange).toHaveBeenLastCalledWith('# Title\n\nBravo\n\nAlpha')
+ })
+
+ it('clears the drop indicator when the drag ends without a drop', () => {
+ const onChange = jest.fn()
+ const { container } = render(createElement(MarkdownNotebook, { value: '# Title\n\nAlpha\n\nBravo', onChange }))
+ const canvas = container.querySelector('.MarkdownNotebook__canvas') as HTMLElement
+ const rows = mockNotebookRowRects(container)
+ const dataTransfer = createDataTransferStub()
+ const handle = getRowDragHandle(rows[1])
+
+ fireDragEvent(handle, 'dragstart', { dataTransfer })
+ fireDragEvent(canvas, 'dragover', { dataTransfer, clientY: 115 })
+
+ expect(container.querySelector('.MarkdownNotebook__drop-indicator')).toBeInstanceOf(HTMLElement)
+
+ fireDragEvent(handle, 'dragend', { dataTransfer })
+
+ expect(container.querySelector('.MarkdownNotebook__drop-indicator')).toBeNull()
+ expect(container.querySelector('.MarkdownNotebook__row--dragging')).toBeNull()
+ expect(onChange).not.toHaveBeenCalled()
+ })
})
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
index ef856646e549..17eb35021577 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
@@ -3,6 +3,7 @@ import './MarkdownNotebook.scss'
import clsx from 'clsx'
import {
ClipboardEvent as ReactClipboardEvent,
+ DragEvent as ReactDragEvent,
FocusEvent as ReactFocusEvent,
FormEvent,
Fragment,
@@ -19,7 +20,7 @@ import {
useState,
} from 'react'
-import { IconCode } from '@posthog/icons'
+import { IconCode, IconComment, IconDrag } from '@posthog/icons'
import { LemonButton } from '@posthog/lemon-ui'
import { Spinner } from 'lib/lemon-ui/Spinner'
@@ -51,10 +52,14 @@ import {
getSlashCommandQuery,
getTextBlockShortcutReplacement,
hasNotebookContent,
+ getDiscussionCommentRefId,
isBlankInsertMenuButtonRow,
+ isDiscussionCommentNode,
isPromptComponentNode,
isTextBlockNode,
makeEmptyNotebookTitle,
+ removeNotebookNodesWithRefCleanup,
+ stripNotebookRefMarksFromNodes,
mapRestoreSelectionThroughDocumentChange,
readSystemClipboardText,
rekeyNotebookNodes,
@@ -123,6 +128,7 @@ import {
plainTextToInlineNodes,
setInlineLinkMark,
setInlineMark,
+ setInlineRefMark,
splitInlineNodesAt,
} from './inlineContent'
import {
@@ -280,6 +286,71 @@ function createDefaultAIChatId(): string {
return makeEmptyParagraph('ai-chat').id
}
+/** Below this container width, comment threads render inline instead of in the margin. */
+const COMMENT_GUTTER_MIN_CONTAINER_WIDTH_PX = 960
+
+/** Vertical spacing between stacked comment threads in the gutter. */
+const GUTTER_COMMENT_GAP_PX = 8
+
+/** Short, human-skimmable id shared by a `<ref>` highlight and its `<Comment ref>` thread. */
+function createNotebookRefId(): string {
+ if (typeof window !== 'undefined' && window.crypto?.randomUUID) {
+ return window.crypto.randomUUID().replace(/-/g, '').slice(0, 8)
+ }
+ return Math.random().toString(36).slice(2, 10)
+}
+
+/** A debug recording session: JSONL entries downloaded as a .log file on stop. */
+type NotebookDebugLog = {
+ startedAt: number
+ entries: string[]
+ lastSelectionSummary: string | null
+}
+
+function truncateForDebugLog(value: string | null | undefined, maxLength: number): string | undefined {
+ if (value === null || value === undefined) {
+ return undefined
+ }
+ return value.length > maxLength ? `${value.slice(0, maxLength)}…(${String(value.length)} chars)` : value
+}
+
+function getDebugTargetInfo(target: EventTarget | null): Record<string, unknown> {
+ if (!(target instanceof Element)) {
+ return {}
+ }
+ const block = target.closest('[data-markdown-notebook-node-id]')
+ const className = typeof target.className === 'string' ? target.className.split(' ')[0] : ''
+ return {
+ target: `${target.tagName.toLowerCase()}${className ? `.${className}` : ''}`,
+ ...(block instanceof HTMLElement && block.dataset.markdownNotebookNodeId
+ ? { nodeId: block.dataset.markdownNotebookNodeId }
+ : {}),
+ }
+}
+
+function getDebugSelectionSummary(): Record<string, unknown> {
+ const selection = window.getSelection()
+ if (!selection || selection.rangeCount === 0) {
+ return { selection: null }
+ }
+
+ const describePoint = (node: Node | null, offset: number): Record<string, unknown> => {
+ const element = node instanceof Element ? node : node?.parentElement
+ const block = element?.closest('[data-markdown-notebook-node-id]')
+ return {
+ nodeId: block instanceof HTMLElement ? block.dataset.markdownNotebookNodeId : undefined,
+ offset,
+ }
+ }
+
+ return {
+ collapsed: selection.isCollapsed,
+ anchor: describePoint(selection.anchorNode, selection.anchorOffset),
+ focus: describePoint(selection.focusNode, selection.focusOffset),
+ text: truncateForDebugLog(selection.toString(), 200),
+ }
+}
+
export function MarkdownNotebook({
value,
onChange,
@@ -314,9 +385,16 @@ export function MarkdownNotebook({
const [activeRowIndex, setActiveRowIndex] = useState<number | null>(null)
const [activeBoundaryIndex, setActiveBoundaryIndex] = useState<number | null>(null)
const [focusedRowIndex, setFocusedRowIndex] = useState<number | null>(null)
+ const [draggingNodeId, setDraggingNodeId] = useState<string | null>(null)
+ const [dropBoundaryIndex, setDropBoundaryIndex] = useState<number | null>(null)
const [selectedComponentNodeIds, setSelectedComponentNodeIds] = useState<Set<string>>(() => new Set())
const [componentPanelCache, setComponentPanelCache] = useState<Record<string, ComponentPanelCacheEntry>>({})
const [isDebugOpen, setIsDebugOpen] = useState(false)
+ const [isDebugLogging, setIsDebugLogging] = useState(false)
+ const debugLogRef = useRef<NotebookDebugLog | null>(null)
+ // Margin layout needs the container to fit the text column plus the full comment
+ // gutter; below that, threads flow inline instead of hanging off-screen.
+ const [fitsCommentGutter, setFitsCommentGutter] = useState(true)
const [debugMarkdown, setDebugMarkdown] = useState(() => serializeMarkdownNotebook(document))
const debugDrawerId = useId()
const notebookRef = useRef<HTMLDivElement | null>(null)
@@ -327,6 +405,7 @@ export function MarkdownNotebook({
const listItemRefs = useRef<Record<string, HTMLElement | null>>({})
const tableCellRefs = useRef<Record<string, HTMLElement | null>>({})
const rootEditableInputHtmlByNodeIdRef = useRef<Record<string, string>>({})
+ const blockDragNodeIdRef = useRef<string | null>(null)
const isTextSelectionPointerActiveRef = useRef(false)
const floatingToolbarRevealTimeoutRef = useRef<number | null>(null)
const floatingToolbarRevealAfterRef = useRef(0)
@@ -370,6 +449,192 @@ export function MarkdownNotebook({
}))
}, [])
+ const hasDiscussionComments = useMemo(() => document.nodes.some(isDiscussionCommentNode), [document])
+
+ useLayoutEffect(() => {
+ const element = mainRef.current
+ if (!hasDiscussionComments || !element || typeof ResizeObserver === 'undefined') {
+ return
+ }
+
+ const updateFitsCommentGutter = (): void => {
+ setFitsCommentGutter(element.clientWidth >= COMMENT_GUTTER_MIN_CONTAINER_WIDTH_PX)
+ }
+ updateFitsCommentGutter()
+ const resizeObserver = new ResizeObserver(updateFitsCommentGutter)
+ resizeObserver.observe(element)
+ return () => resizeObserver.disconnect()
+ }, [hasDiscussionComments])
+
+ const logDebugEntry = useCallback((type: string, payload: Record<string, unknown> = {}): void => {
+ const log = debugLogRef.current
+ if (!log) {
+ return
+ }
+ log.entries.push(JSON.stringify({ t: Date.now() - log.startedAt, type, ...payload }))
+ }, [])
+
+ const startDebugLogging = (): void => {
+ debugLogRef.current = { startedAt: Date.now(), entries: [], lastSelectionSummary: null }
+ logDebugEntry('start', {
+ markdown: lastSerializedValueRef.current,
+ remoteVersion: remoteVersionRef.current,
+ mode,
+ userAgent: typeof navigator === 'undefined' ? undefined : navigator.userAgent,
+ })
+ setIsDebugLogging(true)
+ }
+
+ const stopDebugLoggingAndDownload = (): void => {
+ const log = debugLogRef.current
+ logDebugEntry('stop', { markdown: lastSerializedValueRef.current })
+ debugLogRef.current = null
+ setIsDebugLogging(false)
+ if (!log) {
+ return
+ }
+
+ const blob = new Blob([log.entries.join('\n') + '\n'], { type: 'text/plain' })
+ const url = URL.createObjectURL(blob)
+ const anchor = window.document.createElement('a')
+ anchor.href = url
+ anchor.download = `markdown-notebook-debug-${new Date().toISOString().replace(/[:.]/g, '-')}.log`
+ anchor.click()
+ URL.revokeObjectURL(url)
+ }
+
+ // While recording, capture-phase listeners mirror every keyboard, mouse, input, and
+ // clipboard event into the log, plus deduplicated selection snapshots — together with
+ // the commit entries this reconstructs an editing session for offline debugging.
+ useEffect(() => {
+ const root = notebookRef.current
+ if (!isDebugLogging || !root) {
+ return
+ }
+
+ const logKeyboardEvent = (event: globalThis.KeyboardEvent): void => {
+ logDebugEntry(event.type, {
+ key: event.key,
+ code: event.code,
+ meta: event.metaKey || undefined,
+ ctrl: event.ctrlKey || undefined,
+ alt: event.altKey || undefined,
+ shift: event.shiftKey || undefined,
+ repeat: event.repeat || undefined,
+ ...getDebugTargetInfo(event.target),
+ })
+ }
+ const logMouseEvent = (event: globalThis.MouseEvent): void => {
+ logDebugEntry(event.type, {
+ button: event.button,
+ x: Math.round(event.clientX),
+ y: Math.round(event.clientY),
+ detail: event.detail,
+ ...getDebugTargetInfo(event.target),
+ })
+ }
+ const logInputEvent = (event: Event): void => {
+ const inputEvent = event as InputEvent
+ logDebugEntry(event.type, {
+ inputType: inputEvent.inputType,
+ data: truncateForDebugLog(inputEvent.data, 200),
+ ...getDebugTargetInfo(event.target),
+ })
+ }
+ const logClipboardEvent = (event: globalThis.ClipboardEvent): void => {
+ logDebugEntry(event.type, {
+ text: truncateForDebugLog(event.clipboardData?.getData('text/plain'), 500),
+ ...getDebugTargetInfo(event.target),
+ })
+ }
+ const logSelectionChange = (): void => {
+ const log = debugLogRef.current
+ if (!log) {
+ return
+ }
+ const summary = getDebugSelectionSummary()
+ const serializedSummary = JSON.stringify(summary)
+ if (serializedSummary === log.lastSelectionSummary) {
+ return
+ }
+ log.lastSelectionSummary = serializedSummary
+ logDebugEntry('selectionchange', summary)
+ }
+
+ // `beforeinput` is missing from HTMLElementEventMap in our TS lib, hence the
+ // EventListener casts.
+ const listenersByEventType: [string, EventListener][] = [
+ ['keydown', logKeyboardEvent as EventListener],
+ ['keyup', logKeyboardEvent as EventListener],
+ ['mousedown', logMouseEvent as EventListener],
+ ['mouseup', logMouseEvent as EventListener],
+ ['click', logMouseEvent as EventListener],
+ ['dblclick', logMouseEvent as EventListener],
+ ['contextmenu', logMouseEvent as EventListener],
+ ['beforeinput', logInputEvent],
+ ['input', logInputEvent],
+ ['cut', logClipboardEvent as EventListener],
+ ['copy', logClipboardEvent as EventListener],
+ ['paste', logClipboardEvent as EventListener],
+ ]
+ listenersByEventType.forEach(([type, listener]) => root.addEventListener(type, listener, true))
+ window.document.addEventListener('selectionchange', logSelectionChange)
+
+ return () => {
+ listenersByEventType.forEach(([type, listener]) => root.removeEventListener(type, listener, true))
+ window.document.removeEventListener('selectionchange', logSelectionChange)
+ }
+ }, [isDebugLogging, logDebugEntry])
+
+ // Stack margin comment threads in the gutter so neighbors never overlap: each thread
+ // starts at its anchor row's top unless the previous thread reaches below it, in which
+ // case it is pushed down just past that thread.
+ useLayoutEffect(() => {
+ if (!hasDiscussionComments || !fitsCommentGutter) {
+ return
+ }
+
+ const commentNodeIds = document.nodes.filter(isDiscussionCommentNode).map((node) => node.id)
+ const layoutGutterComments = (): void => {
+ let nextAvailableTop = -Infinity
+ for (const nodeId of commentNodeIds) {
+ const shell = blockRefs.current[nodeId]
+ const row = shell?.closest('.MarkdownNotebook__row')
+ if (!shell || !(row instanceof HTMLElement)) {
+ continue
+ }
+ const rowTop = row.getBoundingClientRect().top
+ const offset = Math.max(0, nextAvailableTop - rowTop)
+ shell.style.top = `${offset}px`
+ nextAvailableTop = rowTop + offset + shell.offsetHeight + GUTTER_COMMENT_GAP_PX
+ }
+ }
+
+ layoutGutterComments()
+ if (typeof ResizeObserver === 'undefined') {
+ return
+ }
+ const resizeObserver = new ResizeObserver(layoutGutterComments)
+ if (canvasRef.current) {
+ resizeObserver.observe(canvasRef.current)
+ }
+ commentNodeIds.forEach((nodeId) => {
+ const shell = blockRefs.current[nodeId]
+ if (shell) {
+ resizeObserver.observe(shell)
+ }
+ })
+ return () => {
+ resizeObserver.disconnect()
+ commentNodeIds.forEach((nodeId) => {
+ const shell = blockRefs.current[nodeId]
+ if (shell) {
+ shell.style.top = ''
+ }
+ })
+ }
+ }, [document, hasDiscussionComments, fitsCommentGutter])
+
const clearFloatingToolbarRevealTimeout = useCallback((): void => {
if (floatingToolbarRevealTimeoutRef.current === null) {
return
@@ -454,6 +719,7 @@ export function MarkdownNotebook({
// reverting only this user's edits.
rebaseHistoryThroughDocumentChange(previousDocument, reconciledDocument)
mapRemoteCaretAnchors(previousDocument, reconciledDocument)
+ logDebugEntry('external-value', { markdown: value })
documentRef.current = reconciledDocument
setDocument(reconciledDocument)
if (restoreSelectionRequest) {
@@ -593,13 +859,18 @@ export function MarkdownNotebook({
mapRemoteCaretAnchors(previousDocument, editableDocument, options.remoteMergeVersion)
const serialized = serializeMarkdownNotebook(editableDocument)
+ logDebugEntry('commit', {
+ addToHistory: options.addToHistory ?? true,
+ ...(options.remoteMergeVersion !== undefined ? { remoteMergeVersion: options.remoteMergeVersion } : {}),
+ markdown: serialized,
+ })
documentRef.current = editableDocument
lastSerializedValueRef.current = serialized
setDebugMarkdown(serialized)
setDocument(editableDocument)
onChange?.(serialized)
},
- [onChange, pushHistoryEntry, mapRemoteCaretAnchors]
+ [onChange, pushHistoryEntry, mapRemoteCaretAnchors, logDebugEntry]
)
const applyRemoteValue = useCallback(
@@ -607,6 +878,7 @@ export function MarkdownNotebook({
if (nextRemoteValue === lastSerializedValueRef.current) {
// The remote state caught up with local edits (autosave echo): fully synced,
// nothing changes locally — undo history must survive autosaves.
+ logDebugEntry('remote-echo', {})
lastRemoteValueRef.current = nextRemoteValue
lastBaseValueRef.current = nextRemoteValue
return
@@ -617,6 +889,12 @@ export function MarkdownNotebook({
localMarkdown: lastSerializedValueRef.current,
remoteMarkdown: nextRemoteValue,
})
+ logDebugEntry('remote-merge', {
+ baseMarkdown: lastBaseValueRef.current,
+ localMarkdown: lastSerializedValueRef.current,
+ remoteMarkdown: nextRemoteValue,
+ conflicts: mergeResult.conflicts,
+ })
const previousDocument = documentRef.current
const reconciledDocument = ensureEditableNotebookDocument(
reconcileNotebookDocuments(previousDocument, mergeResult.document).document
@@ -671,7 +949,7 @@ export function MarkdownNotebook({
onConflict?.(mergeResult.conflicts)
}
},
- [commitDocument, onConflict, onCaretChange, rebaseHistoryThroughDocumentChange]
+ [commitDocument, onConflict, onCaretChange, rebaseHistoryThroughDocumentChange, logDebugEntry]
)
useEffect(() => {
@@ -968,9 +1246,16 @@ export function MarkdownNotebook({
setSelectedComponentNodeIds(new Set())
floatingToolbarPositionLockRef.current = null
setFloatingToolbar(null)
+ const survivingIds = new Set(nextNodes.map((node) => node.id))
+ const removedRefIds = new Set(
+ selectedEntries
+ .filter((entry) => !survivingIds.has(entry.node.id))
+ .map((entry) => getDiscussionCommentRefId(entry.node))
+ .filter((refId): refId is string => !!refId)
+ )
commitDocument({
...currentDocument,
- nodes: nextNodes,
+ nodes: stripNotebookRefMarksFromNodes(nextNodes, removedRefIds),
})
return true
},
@@ -1855,6 +2140,15 @@ export function MarkdownNotebook({
[updateNode]
)
+ // Deleting a discussion comment also unwraps its `<ref>` highlight; deleting anything
+ // else is a plain removal.
+ const deleteNodeWithRefCleanup = useCallback(
+ (nodeId: string): void => {
+ commitDocument(removeNotebookNodesWithRefCleanup(documentRef.current, new Set([nodeId])))
+ },
+ [commitDocument]
+ )
+
const replaceNodeWithInsertedComponent = useCallback(
(nodeId: string, nextNode: NotebookComponentBlockNode): void => {
const definition = getMarkdownNotebookComponentDefinition(mergedRegistry, nextNode.tagName)
@@ -2883,6 +3177,121 @@ export function MarkdownNotebook({
})
}
+ // Comments need at least one markable range; code blocks can't carry inline marks, so
+ // a selection of only code offers nothing.
+ const canStartInlineCommentAtSelection = (): boolean => {
+ if (!floatingToolbar) {
+ return false
+ }
+ return floatingToolbar.textRanges.length + floatingToolbar.listItemRanges.length >= 1
+ }
+
+ const startInlineCommentAtSelection = (): void => {
+ if (!floatingToolbar || !canStartInlineCommentAtSelection()) {
+ return
+ }
+
+ const textRangesByNodeId = new Map(floatingToolbar.textRanges.map((entry) => [entry.node.id, entry]))
+ const listItemRangesByNodeId = new Map<string, FloatingToolbarListItemRange[]>()
+ floatingToolbar.listItemRanges.forEach((entry) => {
+ listItemRangesByNodeId.set(entry.node.id, [...(listItemRangesByNodeId.get(entry.node.id) ?? []), entry])
+ })
+
+ const currentDocument = documentRef.current
+ const nodes = currentDocument.nodes.length ? currentDocument.nodes : [emptyNodeRef.current]
+ const firstSelectedIndex = nodes.findIndex(
+ (node) => textRangesByNodeId.has(node.id) || listItemRangesByNodeId.has(node.id)
+ )
+ if (firstSelectedIndex === -1) {
+ return
+ }
+
+ const refId = createNotebookRefId()
+ // The thread sits above the first block it refers to, so its zero-height margin row
+ // naturally aligns with the top of the highlighted content. The title row is the
+ // one exception: the `# ` heading always stays first, so a title comment goes
+ // right below it instead.
+ const commentNode: NotebookComponentBlockNode = {
+ id: makeEmptyParagraph(`comment-${nodes[firstSelectedIndex].id}`).id,
+ type: 'component',
+ tagName: 'Comment',
+ props: { ref: refId, replies: [] },
+ }
+ const nextNodes = nodes.flatMap((node, index): NotebookBlockNode[] => {
+ let updatedNode = node
+ const textRange = textRangesByNodeId.get(node.id)
+ const listItemRanges = listItemRangesByNodeId.get(node.id)
+ if (textRange && isTextBlockNode(node)) {
+ updatedNode = { ...node, children: setInlineRefMark(node.children, textRange.range, refId) }
+ } else if (listItemRanges && node.type === 'list') {
+ updatedNode = {
+ ...node,
+ items: node.items.map((item, itemIndex) => {
+ const itemRange = listItemRanges.find((entry) => entry.itemIndex === itemIndex)
+ return itemRange
+ ? { ...item, children: setInlineRefMark(item.children, itemRange.range, refId) }
+ : item
+ }),
+ }
+ }
+ if (index !== firstSelectedIndex) {
+ return [updatedNode]
+ }
+ return index === 0 ? [updatedNode, commentNode] : [commentNode, updatedNode]
+ })
+
+ markNotebookNodeFreshlyInserted(commentNode.id)
+ floatingToolbarPositionLockRef.current = null
+ setFloatingToolbar(null)
+ window.getSelection()?.removeAllRanges()
+ commitDocument({ ...currentDocument, nodes: nextNodes })
+ }
+
+ // Clicking a `<ref>` highlight scrolls its comment thread into view and flashes it.
+ const focusDiscussionCommentForRef = (refId: string): void => {
+ const commentNode = documentRef.current.nodes.find((node) => getDiscussionCommentRefId(node) === refId)
+ const element = commentNode ? blockRefs.current[commentNode.id] : null
+ if (!element) {
+ return
+ }
+
+ scrollNotebookElementIntoView(element)
+ element.classList.add('MarkdownNotebook__component-shell--comment-flash')
+ window.setTimeout(() => element.classList.remove('MarkdownNotebook__component-shell--comment-flash'), 1600)
+ }
+
+ const handleCanvasClick = (event: ReactMouseEvent<HTMLDivElement>): void => {
+ const refElement = event.target instanceof Element ? event.target.closest('[data-notebook-ref]') : null
+ const refId = refElement?.getAttribute('data-notebook-ref')
+ if (refId) {
+ focusDiscussionCommentForRef(refId)
+ }
+ }
+
+ // A block comment has no `<ref>` highlight: the thread anchors purely by sitting right
+ // above the block it discusses (below it for the title row, which always stays first).
+ const startBlockCommentForNode = (nodeId: string): void => {
+ const currentDocument = documentRef.current
+ const nodes = currentDocument.nodes.length ? currentDocument.nodes : [emptyNodeRef.current]
+ const targetIndex = nodes.findIndex((node) => node.id === nodeId)
+ if (targetIndex === -1) {
+ return
+ }
+
+ const commentNode: NotebookComponentBlockNode = {
+ id: makeEmptyParagraph(`comment-${nodeId}`).id,
+ type: 'component',
+ tagName: 'Comment',
+ props: { replies: [] },
+ }
+ const insertIndex = Math.max(targetIndex, 1)
+ markNotebookNodeFreshlyInserted(commentNode.id)
+ commitDocument({
+ ...currentDocument,
+ nodes: [...nodes.slice(0, insertIndex), commentNode, ...nodes.slice(insertIndex)],
+ })
+ }
+
const copyFloatingToolbarSelection = (): void => {
if (!floatingToolbar?.selectedMarkdown) {
return
@@ -3728,6 +4137,115 @@ export function MarkdownNotebook({
setActiveBoundaryIndex(null)
}
+ const clearBlockDragState = (): void => {
+ blockDragNodeIdRef.current = null
+ setDraggingNodeId(null)
+ setDropBoundaryIndex(null)
+ }
+
+ const getDropBoundaryIndexFromPointer = (clientY: number): number => {
+ let boundaryIndex = renderedNodes.length
+ for (let index = 0; index < renderedNodes.length; index++) {
+ const node = renderedNodes[index]
+ // Margin comments render as zero-height rows anchored elsewhere — not drop positions.
+ if (isDiscussionCommentNode(node)) {
+ continue
+ }
+
+ const blockElement = blockRefs.current[node.id]
+ const rowElement = blockElement?.closest('.MarkdownNotebook__row') ?? blockElement
+ if (!rowElement) {
+ continue
+ }
+
+ const rect = rowElement.getBoundingClientRect()
+ if (clientY < rect.top + rect.height / 2) {
+ boundaryIndex = index
+ break
+ }
+ }
+ // The title block always stays first: nothing may drop before it.
+ return Math.max(1, Math.min(boundaryIndex, renderedNodes.length))
+ }
+
+ const moveBlockToBoundary = (nodeId: string, boundaryIndex: number): void => {
+ const currentDocument = documentRef.current
+ const nodes = currentDocument.nodes.length ? currentDocument.nodes : [emptyNodeRef.current]
+ const fromIndex = nodes.findIndex((node) => node.id === nodeId)
+ if (fromIndex <= 0) {
+ return
+ }
+
+ const clampedBoundaryIndex = Math.max(1, Math.min(boundaryIndex, nodes.length))
+ if (clampedBoundaryIndex === fromIndex || clampedBoundaryIndex === fromIndex + 1) {
+ return
+ }
+
+ const nextNodes = [...nodes]
+ const [movedNode] = nextNodes.splice(fromIndex, 1)
+ nextNodes.splice(
+ clampedBoundaryIndex > fromIndex ? clampedBoundaryIndex - 1 : clampedBoundaryIndex,
+ 0,
+ movedNode
+ )
+ commitDocument({ ...currentDocument, nodes: nextNodes })
+ }
+
+ const handleBlockDragStart = (event: ReactDragEvent<HTMLDivElement>, nodeId: string): void => {
+ event.stopPropagation()
+ blockDragNodeIdRef.current = nodeId
+ setDraggingNodeId(nodeId)
+ if (event.dataTransfer) {
+ event.dataTransfer.setData('text/plain', nodeId)
+ event.dataTransfer.effectAllowed = 'move'
+ const rowElement = blockRefs.current[nodeId]?.closest('.MarkdownNotebook__row')
+ if (rowElement instanceof HTMLElement && typeof event.dataTransfer.setDragImage === 'function') {
+ event.dataTransfer.setDragImage(rowElement, 0, rowElement.getBoundingClientRect().height / 2)
+ }
+ }
+ }
+
+ const handleBlockDragEnd = (): void => {
+ clearBlockDragState()
+ }
+
+ const handleCanvasDragOver = (event: ReactDragEvent<HTMLDivElement>): void => {
+ if (!blockDragNodeIdRef.current) {
+ return
+ }
+
+ // preventDefault both allows dropping and suppresses the contentEditable native text drag.
+ event.preventDefault()
+ if (event.dataTransfer) {
+ event.dataTransfer.dropEffect = 'move'
+ }
+ setDropBoundaryIndex(getDropBoundaryIndexFromPointer(event.clientY))
+ }
+
+ const handleCanvasDrop = (event: ReactDragEvent<HTMLDivElement>): void => {
+ const nodeId = blockDragNodeIdRef.current
+ if (!nodeId) {
+ return
+ }
+
+ event.preventDefault()
+ const boundaryIndex = getDropBoundaryIndexFromPointer(event.clientY)
+ clearBlockDragState()
+ moveBlockToBoundary(nodeId, boundaryIndex)
+ }
+
+ const handleCanvasDragLeave = (event: ReactDragEvent<HTMLDivElement>): void => {
+ if (!blockDragNodeIdRef.current) {
+ return
+ }
+
+ const nextTarget = event.relatedTarget
+ if (nextTarget instanceof Node && event.currentTarget.contains(nextTarget)) {
+ return
+ }
+ setDropBoundaryIndex(null)
+ }
+
const handleRootEditableInput = (event: FormEvent<HTMLDivElement>): void => {
if (event.target !== event.currentTarget) {
return
@@ -4204,6 +4722,15 @@ export function MarkdownNotebook({
insertMenu?.detached ? insertMenu.nodeId : undefined
)
+ const dropIndicatorTarget: { index: number; position: 'before' | 'after' } | null =
+ draggingNodeId !== null && dropBoundaryIndex !== null
+ ? dropBoundaryIndex < renderedNodes.length
+ ? { index: dropBoundaryIndex, position: 'before' }
+ : renderedNodes.length
+ ? { index: renderedNodes.length - 1, position: 'after' }
+ : null
+ : null
+
const renderInsertBoundaryButton = (
boundaryIndex: number,
options: { isGapClickable?: boolean } = {}
@@ -4255,14 +4782,67 @@ export function MarkdownNotebook({
insertMenu.query.length > 0 &&
getFilteredInsertCommands(insertCommands, insertMenu.query).length === 0
+ const isDraggableRow = mode === 'edit' && !isTitleRow && !isDiscussionCommentNode(node)
+
return (
<div
- className={clsx('MarkdownNotebook__row', isInsertMenuOpen && 'MarkdownNotebook__row--insert-menu-open')}
+ className={clsx(
+ 'MarkdownNotebook__row',
+ isInsertMenuOpen && 'MarkdownNotebook__row--insert-menu-open',
+ isDiscussionCommentNode(node) && 'MarkdownNotebook__row--margin-comment',
+ draggingNodeId === node.id && 'MarkdownNotebook__row--dragging'
+ )}
onMouseEnter={(event) => updateActiveBoundaryFromRow(event, index)}
onMouseMove={(event) => updateActiveBoundaryFromRow(event, index)}
onFocusCapture={() => handleRowFocus(index)}
onBlurCapture={(event) => handleRowBlur(event, index)}
>
+ {isDraggableRow ? (
+ <div
+ className="MarkdownNotebook__drag-handle"
+ contentEditable={false}
+ draggable
+ role="button"
+ aria-label="Drag to move block"
+ data-attr="markdown-notebook-drag-handle"
+ onMouseDown={(event) => event.stopPropagation()}
+ onClick={(event) => {
+ event.preventDefault()
+ event.stopPropagation()
+ }}
+ onDragStart={(event) => handleBlockDragStart(event, node.id)}
+ onDragEnd={handleBlockDragEnd}
+ >
+ <IconDrag />
+ </div>
+ ) : null}
+ {isDraggableRow ? (
+ <div
+ className="MarkdownNotebook__block-comment-button"
+ contentEditable={false}
+ role="button"
+ aria-label="Comment on block"
+ title="Comment"
+ data-attr="markdown-notebook-block-comment-button"
+ onMouseDown={(event) => event.stopPropagation()}
+ onClick={(event) => {
+ event.preventDefault()
+ event.stopPropagation()
+ startBlockCommentForNode(node.id)
+ }}
+ >
+ <IconComment />
+ </div>
+ ) : null}
+ {dropIndicatorTarget?.index === index ? (
+ <div
+ className={clsx(
+ 'MarkdownNotebook__drop-indicator',
+ dropIndicatorTarget.position === 'after' && 'MarkdownNotebook__drop-indicator--after'
+ )}
+ contentEditable={false}
+ />
+ ) : null}
{renderNode({
node,
nodeIndex: index,
@@ -4317,10 +4897,10 @@ export function MarkdownNotebook({
},
updateNode,
replaceNodeWithNodes,
- deleteNode: () => updateNode(node.id, () => null),
+ deleteNode: () => deleteNodeWithRefCleanup(node.id),
deleteNodeAndFocusAdjacent: () => {
requestFocusAfterRemovingNode(node.id)
- updateNode(node.id, () => null)
+ deleteNodeWithRefCleanup(node.id)
},
deleteNodeAndFocusPrevious,
deleteSelectedNotebookBlocks,
@@ -4387,7 +4967,13 @@ export function MarkdownNotebook({
return (
<div
- className={clsx('MarkdownNotebook', isDebugOpen && 'MarkdownNotebook--debug-open', className)}
+ className={clsx(
+ 'MarkdownNotebook',
+ isDebugOpen && 'MarkdownNotebook--debug-open',
+ hasDiscussionComments &&
+ (fitsCommentGutter ? 'MarkdownNotebook--comments-margin' : 'MarkdownNotebook--comments-inline'),
+ className
+ )}
data-attr={dataAttr}
ref={notebookRef}
onCopy={handleCopy}
@@ -4427,6 +5013,10 @@ export function MarkdownNotebook({
onInput={handleRootEditableInput}
onKeyDown={handleRootEditableKeyDown}
onMouseLeave={handleCanvasMouseLeave}
+ onClick={handleCanvasClick}
+ onDragOver={handleCanvasDragOver}
+ onDrop={handleCanvasDrop}
+ onDragLeave={handleCanvasDragLeave}
>
{renderInsertBoundaryButton(0)}
{renderedNodeGroups.map((group) => {
@@ -4523,6 +5113,9 @@ export function MarkdownNotebook({
setBlockStyle={setSelectedBlockStyle}
copySelection={copyFloatingToolbarSelection}
askAIAboutSelection={onAskAI ? askAIAboutSelection : undefined}
+ startInlineCommentAtSelection={
+ canStartInlineCommentAtSelection() ? startInlineCommentAtSelection : undefined
+ }
lockPosition={lockFloatingToolbarPosition}
/>
) : null}
@@ -4531,9 +5124,25 @@ export function MarkdownNotebook({
<aside className="MarkdownNotebook__debug-drawer" id={debugDrawerId}>
<div className="MarkdownNotebook__debug-drawer-header">
<span>Markdown</span>
- <LemonButton size="xsmall" onClick={() => setIsDebugOpen(false)}>
- Close
- </LemonButton>
+ <div className="flex items-center gap-1">
+ <LemonButton
+ size="xsmall"
+ type="secondary"
+ status={isDebugLogging ? 'danger' : undefined}
+ tooltip={
+ isDebugLogging
+ ? 'Stop recording and download the log'
+ : 'Record keystrokes, mouse events, and document changes into a downloadable log'
+ }
+ onClick={isDebugLogging ? stopDebugLoggingAndDownload : startDebugLogging}
+ data-attr="markdown-notebook-debug-log-toggle"
+ >
+ {isDebugLogging ? 'Stop' : 'Log'}
+ </LemonButton>
+ <LemonButton size="xsmall" onClick={() => setIsDebugOpen(false)}>
+ Close
+ </LemonButton>
+ </div>
</div>
<div className="MarkdownNotebook__debug-markdown" aria-label="Markdown debug output">
<Suspense
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownTextDiff.test.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownTextDiff.test.tsx
new file mode 100644
index 000000000000..4aeb5871c23f
--- /dev/null
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownTextDiff.test.tsx
@@ -0,0 +1,56 @@
+import { render } from '@testing-library/react'
+
+import { MarkdownTextDiff } from './MarkdownTextDiff'
+
+function getTexts(container: HTMLElement, selector: 'del' | 'ins'): string[] {
+ return Array.from(container.querySelectorAll(selector)).map((element) => element.textContent ?? '')
+}
+
+describe('MarkdownTextDiff', () => {
+ it('renders a pure insert as <ins> only', () => {
+ const { container } = render(<MarkdownTextDiff before="abc" after="abcdef" />)
+ expect(getTexts(container, 'del')).toEqual([])
+ expect(getTexts(container, 'ins').join('')).toEqual('def')
+ expect(container.textContent).toEqual('abcdef')
+ })
+
+ it('renders a pure delete as <del> only', () => {
+ const { container } = render(<MarkdownTextDiff before="abcdef" after="abc" />)
+ expect(getTexts(container, 'ins')).toEqual([])
+ expect(getTexts(container, 'del').join('')).toEqual('def')
+ expect(container.textContent).toEqual('abcdef')
+ })
+
+ it('renders a mixed replace as <del> plus <ins>', () => {
+ const { container } = render(<MarkdownTextDiff before="the cat sat" after="the car sat" />)
+ expect(getTexts(container, 'del').join('')).toEqual('t')
+ expect(getTexts(container, 'ins').join('')).toEqual('r')
+ expect(container.textContent).toEqual('the catr sat')
+ })
+
+ it('renders identical strings without <del> or <ins>', () => {
+ const { container } = render(<MarkdownTextDiff before="same text" after="same text" />)
+ expect(getTexts(container, 'del')).toEqual([])
+ expect(getTexts(container, 'ins')).toEqual([])
+ expect(container.textContent).toEqual('same text')
+ })
+
+ it('renders an empty before as everything inserted', () => {
+ const { container } = render(<MarkdownTextDiff before="" after="brand new" />)
+ expect(getTexts(container, 'del')).toEqual([])
+ expect(getTexts(container, 'ins')).toEqual(['brand new'])
+ })
+
+ it('renders an empty after as everything deleted', () => {
+ const { container } = render(<MarkdownTextDiff before="all gone" after="" />)
+ expect(getTexts(container, 'ins')).toEqual([])
+ expect(getTexts(container, 'del')).toEqual(['all gone'])
+ })
+
+ it('keeps whitespace-only insertions visible via pre-wrap', () => {
+ const { container } = render(<MarkdownTextDiff before="ab" after="a b" />)
+ expect(getTexts(container, 'ins')).toEqual([' '])
+ const wrapper = container.firstElementChild as HTMLElement
+ expect(wrapper.className).toContain('whitespace-pre-wrap')
+ })
+})
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownTextDiff.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownTextDiff.tsx
new file mode 100644
index 000000000000..bf0cf2114eab
--- /dev/null
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownTextDiff.tsx
@@ -0,0 +1,44 @@
+import { getTextChanges } from './textChanges'
+
+export interface MarkdownTextDiffProps {
+ before: string
+ after: string
+}
+
+/**
+ * Inline word/character-level diff between two strings: unchanged text is rendered plain,
+ * deleted spans as <del> and inserted spans as <ins>. Generic on purpose so it can also
+ * back AI suggestion previews and other before/after text displays.
+ */
+export function MarkdownTextDiff({ before, after }: MarkdownTextDiffProps): JSX.Element {
+ const changes = getTextChanges(before, after)
+ const segments: JSX.Element[] = []
+ let cursor = 0
+
+ changes.forEach((change, index) => {
+ if (change.start > cursor) {
+ segments.push(<span key={`unchanged-${index}`}>{before.slice(cursor, change.start)}</span>)
+ }
+ if (change.end > change.start) {
+ segments.push(
+ <del key={`deleted-${index}`} className="text-danger bg-danger-highlight line-through">
+ {before.slice(change.start, change.end)}
+ </del>
+ )
+ }
+ if (change.text) {
+ segments.push(
+ <ins key={`inserted-${index}`} className="text-success bg-success-highlight no-underline">
+ {change.text}
+ </ins>
+ )
+ }
+ cursor = change.end
+ })
+
+ if (cursor < before.length) {
+ segments.push(<span key="unchanged-tail">{before.slice(cursor)}</span>)
+ }
+
+ return <span className="whitespace-pre-wrap">{segments}</span>
+}
diff --git a/frontend/src/lib/components/MarkdownNotebook/README.md b/frontend/src/lib/components/MarkdownNotebook/README.md
index f063a97b19a1..242eca79ed99 100644
--- a/frontend/src/lib/components/MarkdownNotebook/README.md
+++ b/frontend/src/lib/components/MarkdownNotebook/README.md
@@ -24,7 +24,7 @@ See [COMPONENTS.md](./COMPONENTS.md) for how to register embeddable components (
## Supported markdown
-Inline: bold (`**`/`__`), italic (`*`/`_`, underscores only at word boundaries), underline (`<u>`), strikethrough (`~~`), inline code, links (http/https only; balanced parentheses in hrefs supported), and hard breaks. Blocks: paragraphs, headings (`#`–`######` parse and round-trip; the UI offers H1–H3), blockquotes (including quoted lists), ordered/unordered lists with nesting, GFM tables with column alignment (header and body rows must start with `|`), fenced code blocks (language tag preserved; the serializer picks a fence longer than any backtick run in the content), dividers (`---`/`***`/`___`, stored as a reserved `Divider` component tag), images (`![alt](src)`, stored as the `Image` component), and JSX-like component tags.
+Inline: bold (`**`/`__`), italic (`*`/`_`, underscores only at word boundaries), underline (`<u>`), strikethrough (`~~`), inline code, links (http/https only; balanced parentheses in hrefs supported), hard breaks, ref anchors (`<ref id="x">highlighted text</ref>`, lowercase inline tags so they can never collide with uppercase component tags), and mentions (`<mention id="5">@Name</mention>`; the text is the display label, the id is the member). Blocks: paragraphs, headings (`#`–`######` parse and round-trip; the UI offers H1–H3), blockquotes (including quoted lists), ordered/unordered lists with nesting, GFM tables with column alignment (header and body rows must start with `|`), fenced code blocks (language tag preserved; the serializer picks a fence longer than any backtick run in the content), dividers (`---`/`***`/`___`, stored as a reserved `Divider` component tag), images (`![alt](src)`, stored as the `Image` component), and JSX-like component tags.
### Round-trip guarantee
@@ -59,3 +59,15 @@ The component receives two props: `value` (the local content owned by the caller
When `remoteValue` changes it is merged with `mergeNotebookMarkdownChanges({ base, local, remote })`, and the merged document is committed without touching the merge base (the merge result still contains unsaved local changes). When `remoteValue` catches up with the local serialization (autosave echo), the component is fully synced; undo history is intentionally preserved in that case.
Save conflicts (HTTP 409) are resolved through the same path: `notebookLogic` reloads the fresh server content, which flows in as `remoteValue`, the editor merges and re-emits, and the save is retried against the new version.
+
+## Debug session recorder
+
+The debug drawer (`showDebug`) has a Log button that records an editing session as JSONL: every keystroke, mouse, input, and clipboard event on the notebook (capture phase), deduplicated selection snapshots, and every document commit with the resulting markdown — plus remote merges with their base/local/remote inputs and conflicts. Stop downloads the session as a `.log` file, built to be handed to an agent (or a human) to reconstruct exactly what the editor did and why.
+
+## Inline discussion comments
+
+A Google Docs-style comment thread is two paired pieces of markdown: an inline `<ref id="banana">highlighted text</ref>` anchor (a multi-block selection wraps each block's range in the same id) and a `<Comment ref="banana" replies={[…]} />` block placed right above the first block holding the highlight. When threads are present and the container is wide enough, the canvas reserves a right gutter (`--markdown-notebook-comment-gutter`) and pushes the text column left; each thread row keeps zero height so the card hangs in the gutter level with its content. Below `COMMENT_GUTTER_MIN_CONTAINER_WIDTH_PX` the threads flow inline as right-aligned cards. Replies live in the markdown itself as an id-keyed array, so two people replying at the same time merge by union (`mergeIdKeyedArrayPropValues` in `collaboration.ts`) instead of clobbering each other.
+
+Deletion is intentionally asymmetric (`removeNotebookNodesWithRefCleanup` in `documentModel.ts`): deleting the comment thread also unwraps its `<ref>` highlight, but removing the highlight (or the text holding it) leaves the thread in place — it contains people's replies and must be deleted on its own.
+
+The `Comment` tag also has an authorial-note flavor (`text` prop) that serializes as a plain `<!-- … -->` markdown comment; `isDiscussionCommentProps` in `markdown.ts` is the discriminator.
diff --git a/frontend/src/lib/components/MarkdownNotebook/TODO.md b/frontend/src/lib/components/MarkdownNotebook/TODO.md
index 86a0a688ac54..c35518cc0563 100644
--- a/frontend/src/lib/components/MarkdownNotebook/TODO.md
+++ b/frontend/src/lib/components/MarkdownNotebook/TODO.md
@@ -8,12 +8,12 @@ The markdown notebook rewrite (markdown storage, custom component tags, conflict
- Decide and implement the default-on path: create new notebooks as markdown notebooks once the flag ramps.
- Batch conversion of existing notebooks (`convertNotebookContentToMarkdown`) needs migration validation fixtures built from real production notebook shapes, beyond the unit-test coverage in `notebookUpgradeDialog.test.tsx`.
- Verify notebook history and sharing behavior survive the upgrade (history diffs against TipTap JSON snapshots predating the conversion).
-- Define fallback/rollback behavior: there is currently no downgrade path from a markdown notebook back to TipTap content.
+- Rollback: `convertMarkdownToNotebookContent` (markdownNotebookDowngrade.ts) converts markdown back to TipTap content. Known one-way losses are documented in its module docstring (discussion reply threads, AI chats/prompts, table alignments) — wire it into a user-facing rollback flow if needed.
## Editor gaps
-- Block movement: rows and components cannot be dragged to reorder; the only way to move a block is cut/paste.
- Accessibility: the formatting toolbar, insert menu, and component insertion flow need keyboard navigation and screen-reader coverage (focus management, roving tabindex, ARIA roles beyond the current labels).
+- Inline comments: selections inside code blocks can't be commented (code carries no inline marks).
## Open questions
diff --git a/frontend/src/lib/components/MarkdownNotebook/collaboration.test.ts b/frontend/src/lib/components/MarkdownNotebook/collaboration.test.ts
index 5236de7da04c..435008e24f2f 100644
--- a/frontend/src/lib/components/MarkdownNotebook/collaboration.test.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/collaboration.test.ts
@@ -230,6 +230,63 @@ describe('mergeNotebookMarkdownChanges', () => {
expect(result.mergedMarkdown).toContain('remote-chat')
})
+ it('merges concurrent replies to the same comment thread by reply id', () => {
+ const base = '<Comment ref="banana" replies={[{"id":"r1","author":"Ann","text":"First"}]} />'
+ const result = mergeNotebookMarkdownChanges({
+ baseMarkdown: base,
+ localMarkdown:
+ '<Comment ref="banana" replies={[{"id":"r1","author":"Ann","text":"First"},{"id":"r2","author":"Bob","text":"Local reply"}]} />',
+ remoteMarkdown:
+ '<Comment ref="banana" replies={[{"id":"r1","author":"Ann","text":"First"},{"id":"r3","author":"Cay","text":"Remote reply"}]} />',
+ })
+
+ expect(result.conflicts).toEqual([])
+ expect(result.mergedMarkdown).toContain('"id":"r1"')
+ expect(result.mergedMarkdown).toContain('Local reply')
+ expect(result.mergedMarkdown).toContain('Remote reply')
+ })
+
+ it('keeps a reply deletion deleted when the other side merely replied', () => {
+ const base =
+ '<Comment ref="banana" replies={[{"id":"r1","author":"Ann","text":"First"},{"id":"r2","author":"Bob","text":"Oops"}]} />'
+ const result = mergeNotebookMarkdownChanges({
+ baseMarkdown: base,
+ localMarkdown: '<Comment ref="banana" replies={[{"id":"r1","author":"Ann","text":"First"}]} />',
+ remoteMarkdown:
+ '<Comment ref="banana" replies={[{"id":"r1","author":"Ann","text":"First"},{"id":"r2","author":"Bob","text":"Oops"},{"id":"r3","author":"Cay","text":"New"}]} />',
+ })
+
+ expect(result.conflicts).toEqual([])
+ expect(result.mergedMarkdown).not.toContain('Oops')
+ expect(result.mergedMarkdown).toContain('New')
+ })
+
+ it('takes the edited version of a reply edited on one side only', () => {
+ const base = '<Comment ref="banana" replies={[{"id":"r1","author":"Ann","text":"Tpyo"}]} />'
+ const result = mergeNotebookMarkdownChanges({
+ baseMarkdown: base,
+ localMarkdown: '<Comment ref="banana" replies={[{"id":"r1","author":"Ann","text":"Tpyo"}]} />',
+ remoteMarkdown: '<Comment ref="banana" replies={[{"id":"r1","author":"Ann","text":"Typo"}]} />',
+ })
+
+ expect(result.conflicts).toEqual([])
+ expect(result.mergedMarkdown).toContain('Typo')
+ expect(result.mergedMarkdown).not.toContain('Tpyo')
+ })
+
+ it('merges replies added concurrently to a thread that was empty in the base', () => {
+ const base = '<Comment ref="banana" replies={[]} />'
+ const result = mergeNotebookMarkdownChanges({
+ baseMarkdown: base,
+ localMarkdown: '<Comment ref="banana" replies={[{"id":"r1","author":"Ann","text":"Mine"}]} />',
+ remoteMarkdown: '<Comment ref="banana" replies={[{"id":"r2","author":"Bob","text":"Theirs"}]} />',
+ })
+
+ expect(result.conflicts).toEqual([])
+ expect(result.mergedMarkdown).toContain('Mine')
+ expect(result.mergedMarkdown).toContain('Theirs')
+ })
+
it('keeps non-string prop edits atomic per prop', () => {
const result = mergeNotebookMarkdownChanges({
baseMarkdown: '<Query query={{"kind":"TrendsQuery","interval":"day"}} />',
diff --git a/frontend/src/lib/components/MarkdownNotebook/collaboration.ts b/frontend/src/lib/components/MarkdownNotebook/collaboration.ts
index b35eead845c3..143a7a4fad23 100644
--- a/frontend/src/lib/components/MarkdownNotebook/collaboration.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/collaboration.ts
@@ -1,7 +1,13 @@
import { parseMarkdownNotebook, serializeMarkdownNotebook, serializeNode } from './markdown'
import { getStableComponentKey, reconcileNotebookDocuments } from './reconcile'
import { applyTextChanges, getTextChanges, transformTextChanges, tryApplyTextChanges } from './textChanges'
-import { NotebookBlockNode, NotebookCollaborationConflict, NotebookComponentBlockNode, NotebookDocument } from './types'
+import {
+ NotebookBlockNode,
+ NotebookCollaborationConflict,
+ NotebookComponentBlockNode,
+ NotebookDocument,
+ NotebookPropValue,
+} from './types'
import { cloneNotebookNode, getNodeFingerprint, getNodeSignature } from './utils'
export type { TextChange } from './textChanges'
@@ -387,10 +393,15 @@ function mergeNotebookComponentNodes(
const remoteChanged = !arePropValuesEqual(remoteValue, baseValue)
let mergedValue: NotebookComponentBlockNode['props'][string] | undefined
+ const idArrayMerge = !localChanged
+ ? null
+ : mergeIdKeyedArrayPropValues(baseValue ?? [], localValue, remoteValue)
if (!localChanged) {
mergedValue = remoteValue
} else if (!remoteChanged || arePropValuesEqual(localValue, remoteValue)) {
mergedValue = localValue
+ } else if (idArrayMerge) {
+ mergedValue = idArrayMerge
} else if (typeof baseValue === 'string' && typeof localValue === 'string' && typeof remoteValue === 'string') {
const textMerge = mergeTextChanges(baseValue, localValue, remoteValue)
if (textMerge.conflicted) {
@@ -415,6 +426,100 @@ function mergeNotebookComponentNodes(
}
}
+type IdKeyedEntry = { [key: string]: NotebookPropValue } & { id: string }
+
+/**
+ * Three-way merge for array props whose entries are objects keyed by a unique string `id`
+ * (chat `replies` being the motivating case). Two people replying to the same chat at the
+ * same time must both keep their replies: entries added on either side survive, entries
+ * deleted on one side stay deleted, and an entry edited on one side takes that side's
+ * version. Returns null when the shape doesn't qualify — the caller falls back to its
+ * other strategies.
+ */
+function mergeIdKeyedArrayPropValues(
+ baseValue: NotebookPropValue | undefined,
+ localValue: NotebookPropValue | undefined,
+ remoteValue: NotebookPropValue | undefined
+): NotebookPropValue[] | null {
+ const base = asIdKeyedArray(baseValue)
+ const local = asIdKeyedArray(localValue)
+ const remote = asIdKeyedArray(remoteValue)
+ if (!base || !local || !remote) {
+ return null
+ }
+
+ const baseById = new Map(base.map((entry) => [entry.id, entry]))
+ const localById = new Map(local.map((entry) => [entry.id, entry]))
+ const merged: IdKeyedEntry[] = []
+ const mergedIds = new Set<string>()
+ const push = (entry: IdKeyedEntry): void => {
+ if (!mergedIds.has(entry.id)) {
+ merged.push(entry)
+ mergedIds.add(entry.id)
+ }
+ }
+
+ for (const localEntry of local) {
+ const baseEntry = baseById.get(localEntry.id)
+ const remoteEntry = remote.find((entry) => entry.id === localEntry.id)
+
+ if (baseEntry && !remoteEntry) {
+ // Deleted remotely; a concurrent deletion must not resurrect on every merge.
+ continue
+ }
+ if (remoteEntry && baseEntry && arePropValuesEqual(localEntry, baseEntry)) {
+ push(remoteEntry)
+ continue
+ }
+ push(localEntry)
+ }
+
+ // Entries the remote side added (or that local deleted but remote edited) are inserted
+ // after their closest surviving remote predecessor, keeping both sides' ordering intact.
+ remote.forEach((remoteEntry, remoteIndex) => {
+ if (mergedIds.has(remoteEntry.id)) {
+ return
+ }
+ const baseEntry = baseById.get(remoteEntry.id)
+ if (baseEntry && !localById.has(remoteEntry.id) && arePropValuesEqual(remoteEntry, baseEntry)) {
+ // Deleted locally and untouched remotely: the deletion wins.
+ return
+ }
+
+ let insertIndex = merged.length
+ for (let previousIndex = remoteIndex - 1; previousIndex >= 0; previousIndex--) {
+ const anchorPosition = merged.findIndex((entry) => entry.id === remote[previousIndex].id)
+ if (anchorPosition !== -1) {
+ insertIndex = anchorPosition + 1
+ break
+ }
+ }
+ merged.splice(insertIndex, 0, remoteEntry)
+ mergedIds.add(remoteEntry.id)
+ })
+
+ return merged
+}
+
+function asIdKeyedArray(value: NotebookPropValue | undefined): IdKeyedEntry[] | null {
+ if (!Array.isArray(value)) {
+ return null
+ }
+
+ const ids = new Set<string>()
+ for (const entry of value) {
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
+ return null
+ }
+ const id = entry.id
+ if (typeof id !== 'string' || !id || ids.has(id)) {
+ return null
+ }
+ ids.add(id)
+ }
+ return value as IdKeyedEntry[]
+}
+
function arePropValuesEqual(
left: NotebookComponentBlockNode['props'][string] | undefined,
right: NotebookComponentBlockNode['props'][string] | undefined
diff --git a/frontend/src/lib/components/MarkdownNotebook/discussionComments.test.ts b/frontend/src/lib/components/MarkdownNotebook/discussionComments.test.ts
new file mode 100644
index 000000000000..bbeb42904c7d
--- /dev/null
+++ b/frontend/src/lib/components/MarkdownNotebook/discussionComments.test.ts
@@ -0,0 +1,176 @@
+import {
+ ensureEditableNotebookDocument,
+ getMarkdownNotebookVisualGroups,
+ removeNotebookNodesWithRefCleanup,
+} from './documentModel'
+import { removeInlineRefMark, setInlineRefMark } from './inlineContent'
+import { parseMarkdownNotebook, serializeMarkdownNotebook } from './markdown'
+import { NotebookDocument } from './types'
+
+describe('discussion comments', () => {
+ const parse = (markdown: string): NotebookDocument => parseMarkdownNotebook(markdown)
+
+ describe('setInlineRefMark', () => {
+ it('wraps the selected range in a ref mark', () => {
+ const children = setInlineRefMark(
+ [{ type: 'text', text: 'Numbers look off here' }],
+ { nodeId: 'n', start: 8, end: 12 },
+ 'banana'
+ )
+
+ expect(children).toEqual([
+ { type: 'text', text: 'Numbers ' },
+ { type: 'text', text: 'look', marks: [{ type: 'ref', id: 'banana' }] },
+ { type: 'text', text: ' off here' },
+ ])
+ })
+
+ it('replaces an existing ref on the selected range', () => {
+ const children = setInlineRefMark(
+ [{ type: 'text', text: 'word', marks: [{ type: 'ref', id: 'old' }] }],
+ { nodeId: 'n', start: 0, end: 4 },
+ 'new'
+ )
+
+ expect(children).toEqual([{ type: 'text', text: 'word', marks: [{ type: 'ref', id: 'new' }] }])
+ })
+ })
+
+ describe('removeInlineRefMark', () => {
+ it('removes only the matching ref and keeps the text', () => {
+ const children = removeInlineRefMark(
+ [
+ { type: 'text', text: 'one', marks: [{ type: 'ref', id: 'a' }] },
+ { type: 'text', text: 'two', marks: [{ type: 'ref', id: 'b' }] },
+ ],
+ 'a'
+ )
+
+ expect(children).toEqual([
+ { type: 'text', text: 'one' },
+ { type: 'text', text: 'two', marks: [{ type: 'ref', id: 'b' }] },
+ ])
+ })
+
+ it('keeps other marks on the unwrapped text', () => {
+ const children = removeInlineRefMark(
+ [{ type: 'text', text: 'bold', marks: [{ type: 'bold' }, { type: 'ref', id: 'a' }] }],
+ 'a'
+ )
+
+ expect(children).toEqual([{ type: 'text', text: 'bold', marks: [{ type: 'bold' }] }])
+ })
+ })
+
+ describe('getMarkdownNotebookVisualGroups', () => {
+ it('keeps a comment thread inside the surrounding text group instead of splitting it', () => {
+ const document = parse(
+ [
+ 'Paragraph one',
+ '',
+ '<Comment ref="x" replies={[]} />',
+ '',
+ 'Paragraph <ref id="x">two</ref>',
+ '',
+ 'Paragraph three',
+ ].join('\n')
+ )
+
+ const groups = getMarkdownNotebookVisualGroups(document.nodes)
+
+ expect(groups).toHaveLength(1)
+ expect(groups[0].type).toEqual('text')
+ expect(groups[0].type === 'text' ? groups[0].items.map((item) => item.surface) : []).toEqual([
+ 'text',
+ 'comment',
+ 'text',
+ 'text',
+ ])
+ })
+
+ it('keeps a comment anchored to a standalone component as its own row', () => {
+ const document = parse(
+ ['<Comment ref="q" replies={[]} />', '', '<Query query={{"kind":"DataTableNode"}} />'].join('\n')
+ )
+
+ const groups = getMarkdownNotebookVisualGroups(document.nodes)
+
+ expect(groups.map((group) => group.type)).toEqual(['block', 'block'])
+ })
+ })
+
+ describe('ensureEditableNotebookDocument', () => {
+ it('slides a leading comment thread below the title instead of adding an empty title', () => {
+ const document = parse(
+ ['<Comment ref="x" replies={[]} />', '', '# <ref id="x">Title</ref>', '', 'Body'].join('\n')
+ )
+
+ const result = ensureEditableNotebookDocument(document)
+
+ expect(result.nodes.map((node) => node.type)).toEqual(['heading', 'component', 'paragraph'])
+ expect(serializeMarkdownNotebook(result)).toEqual(
+ '# <ref id="x">Title</ref>\n\n<Comment ref="x" replies={[]} />\n\nBody'
+ )
+ })
+ })
+
+ describe('removeNotebookNodesWithRefCleanup', () => {
+ const markdown = [
+ '# Title',
+ '',
+ 'Numbers <ref id="banana">look off</ref> here',
+ '',
+ '<Comment ref="banana" replies={[{"id":"r1","author":"Ann","text":"Why?"}]} />',
+ ].join('\n')
+
+ it('deleting the comment thread also unwraps its ref highlight', () => {
+ const document = parse(markdown)
+ const commentNode = document.nodes.find((node) => node.type === 'component')
+
+ const result = removeNotebookNodesWithRefCleanup(document, new Set([commentNode!.id]))
+
+ expect(serializeMarkdownNotebook(result)).toEqual('# Title\n\nNumbers look off here')
+ })
+
+ it('deleting the paragraph holding the ref keeps the comment thread', () => {
+ const document = parse(markdown)
+ const paragraphNode = document.nodes.find((node) => node.type === 'paragraph')
+
+ const result = removeNotebookNodesWithRefCleanup(document, new Set([paragraphNode!.id]))
+ const serialized = serializeMarkdownNotebook(result)
+
+ expect(serialized).toContain('<Comment ref="banana"')
+ expect(serialized).not.toContain('look off')
+ })
+
+ it('unwraps refs inside list items and table cells', () => {
+ const document = parse(
+ [
+ '- item <ref id="x">marked</ref>',
+ '',
+ '| a <ref id="x">b</ref> |',
+ '| --- |',
+ '| c |',
+ '',
+ '<Comment ref="x" replies={[]} />',
+ ].join('\n')
+ )
+ const commentNode = document.nodes.find((node) => node.type === 'component')
+
+ const result = removeNotebookNodesWithRefCleanup(document, new Set([commentNode!.id]))
+ const serialized = serializeMarkdownNotebook(result)
+
+ expect(serialized).not.toContain('<ref')
+ expect(serialized).toContain('item marked')
+ })
+
+ it('deleting a non-comment node leaves unrelated refs alone', () => {
+ const document = parse(markdown)
+ const titleNode = document.nodes[0]
+
+ const result = removeNotebookNodesWithRefCleanup(document, new Set([titleNode.id]))
+
+ expect(serializeMarkdownNotebook(result)).toContain('<ref id="banana">look off</ref>')
+ })
+ })
+})
diff --git a/frontend/src/lib/components/MarkdownNotebook/documentModel.ts b/frontend/src/lib/components/MarkdownNotebook/documentModel.ts
index 4dd3e16bac20..0c05fbeba8a1 100644
--- a/frontend/src/lib/components/MarkdownNotebook/documentModel.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/documentModel.ts
@@ -1,7 +1,9 @@
import { RestoreInlineSelectionRequest, RestoreSelectionRequest } from './editorTypes'
+import { removeInlineRefMark } from './inlineContent'
import {
COMMENT_COMPONENT_TAG,
DIVIDER_COMPONENT_TAG,
+ isDiscussionCommentProps,
makeEmptyParagraph,
makeListItemId,
parseMarkdownNotebook,
@@ -33,7 +35,7 @@ export function getNotebookStringProp(value: NotebookPropValue | undefined): str
return typeof value === 'string' ? value : undefined
}
-export type MarkdownNotebookTextSurface = 'text' | 'quote' | 'code'
+export type MarkdownNotebookTextSurface = 'text' | 'quote' | 'code' | 'comment'
export type MarkdownNotebookVisualGroup =
| {
@@ -54,9 +56,28 @@ export function getMarkdownNotebookVisualGroups(
): MarkdownNotebookVisualGroup[] {
const groups: MarkdownNotebookVisualGroup[] = []
let currentTextGroup: Extract<MarkdownNotebookVisualGroup, { type: 'text' }> | null = null
+ const isTextLikeNode = (node: NotebookBlockNode | undefined): boolean =>
+ !!node && (isTextBlockNode(node) || node.type === 'list' || node.type === 'code')
+
+ // A discussion comment sits right above the text it highlights; joining the surrounding
+ // text group keeps that text from being split into separate cards. A comment anchored to
+ // a standalone block (a component) stays its own row.
+ const commentJoinsTextGroup = (index: number): boolean => {
+ if (!isDiscussionCommentNode(nodes[index])) {
+ return false
+ }
+ if (currentTextGroup) {
+ return true
+ }
+ let nextIndex = index + 1
+ while (nextIndex < nodes.length && isDiscussionCommentNode(nodes[nextIndex])) {
+ nextIndex += 1
+ }
+ return isTextLikeNode(nodes[nextIndex])
+ }
nodes.forEach((node, index) => {
- if ((isTextBlockNode(node) || node.type === 'list' || node.type === 'code') && node.id !== insertMenuNodeId) {
+ if ((isTextLikeNode(node) || commentJoinsTextGroup(index)) && node.id !== insertMenuNodeId) {
if (!currentTextGroup) {
currentTextGroup = {
type: 'text',
@@ -69,7 +90,13 @@ export function getMarkdownNotebookVisualGroups(
currentTextGroup.items.push({
node,
index,
- surface: node.type === 'code' ? 'code' : isGroupedBlockquoteNode(node) ? 'quote' : 'text',
+ surface: isDiscussionCommentNode(node)
+ ? 'comment'
+ : node.type === 'code'
+ ? 'code'
+ : isGroupedBlockquoteNode(node)
+ ? 'quote'
+ : 'text',
})
return
}
@@ -104,6 +131,90 @@ export function isDividerComponentNode(node: NotebookBlockNode): node is Noteboo
return node.type === 'component' && node.tagName === DIVIDER_COMPONENT_TAG
}
+/**
+ * A discussion comment is a `<Comment>` carrying human replies (and usually a `ref`
+ * anchor), as opposed to an authorial note which carries only `text` and serializes as a
+ * markdown `<!-- … -->` comment.
+ */
+export function isDiscussionCommentNode(node: NotebookBlockNode): node is NotebookComponentBlockNode {
+ return isCommentComponentNode(node) && isDiscussionCommentProps(node.props)
+}
+
+export function getDiscussionCommentRefId(node: NotebookBlockNode): string | null {
+ if (!isCommentComponentNode(node)) {
+ return null
+ }
+ const refId = node.props.ref
+ return typeof refId === 'string' && refId.trim() ? refId : null
+}
+
+function mapNodeInlineChildren(
+ node: NotebookBlockNode,
+ mapChildren: (children: NotebookInlineNode[]) => NotebookInlineNode[]
+): NotebookBlockNode {
+ if (isTextBlockNode(node)) {
+ const children = mapChildren(node.children)
+ return children === node.children ? node : { ...node, children }
+ }
+ if (node.type === 'list') {
+ let didChange = false
+ const items = node.items.map((item) => {
+ const children = mapChildren(item.children)
+ if (children === item.children) {
+ return item
+ }
+ didChange = true
+ return { ...item, children }
+ })
+ return didChange ? { ...node, items } : node
+ }
+ if (node.type === 'table') {
+ let didChange = false
+ const mapCell = (cell: { children: NotebookInlineNode[] }): { children: NotebookInlineNode[] } => {
+ const children = mapChildren(cell.children)
+ if (children === cell.children) {
+ return cell
+ }
+ didChange = true
+ return { ...cell, children }
+ }
+ const headers = node.headers.map(mapCell)
+ const rows = node.rows.map((row) => row.map(mapCell))
+ return didChange ? { ...node, headers, rows } : node
+ }
+ return node
+}
+
+/**
+ * Deletes blocks and, for any deleted discussion comment with a `ref` anchor, unwraps the
+ * matching `<ref>` tags so no orphaned highlight is left behind. The reverse direction is
+ * intentionally asymmetric: removing a ref never deletes the comment — it holds people's
+ * replies and stays anchored to the right until deleted on its own.
+ */
+export function removeNotebookNodesWithRefCleanup(document: NotebookDocument, nodeIds: Set<string>): NotebookDocument {
+ const removedRefIds = new Set(
+ document.nodes
+ .filter((node) => nodeIds.has(node.id))
+ .map(getDiscussionCommentRefId)
+ .filter((refId): refId is string => !!refId)
+ )
+ const remainingNodes = document.nodes.filter((node) => !nodeIds.has(node.id))
+ return { ...document, nodes: stripNotebookRefMarksFromNodes(remainingNodes, removedRefIds) }
+}
+
+/** Unwraps `<ref>` tags with the given ids across every text-bearing block, keeping the text. */
+export function stripNotebookRefMarksFromNodes(nodes: NotebookBlockNode[], refIds: Set<string>): NotebookBlockNode[] {
+ if (!refIds.size) {
+ return nodes
+ }
+
+ return nodes.map((node) =>
+ mapNodeInlineChildren(node, (children) =>
+ [...refIds].reduce((current, refId) => removeInlineRefMark(current, refId), children)
+ )
+ )
+}
+
export function isCommentComponentNode(node: NotebookBlockNode): node is NotebookComponentBlockNode {
return node.type === 'component' && node.tagName === COMMENT_COMPONENT_TAG
}
@@ -331,8 +442,25 @@ export function getDividerShortcut(text: string): boolean {
}
export function ensureEditableNotebookDocument(document: NotebookDocument): NotebookDocument {
- const nodes = document.nodes.length ? [...document.nodes] : [makeEmptyNotebookTitle('notebook-title')]
+ let nodes = document.nodes.length ? [...document.nodes] : [makeEmptyNotebookTitle('notebook-title')]
let didChange = nodes.length !== document.nodes.length
+
+ // The `# ` title row always stays first: discussion comments that end up above it (a
+ // comment on the title itself, a merge, a manual markdown edit) slide below it instead
+ // of pushing a fresh empty title on top of the document.
+ let leadingCommentCount = 0
+ while (leadingCommentCount < nodes.length && isDiscussionCommentNode(nodes[leadingCommentCount])) {
+ leadingCommentCount += 1
+ }
+ if (leadingCommentCount > 0 && leadingCommentCount < nodes.length && isTextBlockNode(nodes[leadingCommentCount])) {
+ nodes = [
+ nodes[leadingCommentCount],
+ ...nodes.slice(0, leadingCommentCount),
+ ...nodes.slice(leadingCommentCount + 1),
+ ]
+ didChange = true
+ }
+
const firstNode = nodes[0]
if (isTextBlockNode(firstNode)) {
diff --git a/frontend/src/lib/components/MarkdownNotebook/index.ts b/frontend/src/lib/components/MarkdownNotebook/index.ts
index bd1e79b6677e..3003a3e73686 100644
--- a/frontend/src/lib/components/MarkdownNotebook/index.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/index.ts
@@ -8,6 +8,8 @@ export {
mergeMarkdownNotebookRegistries,
} from './registry'
export { parseMarkdownNotebook, serializeMarkdownNotebook, htmlElementToInlineNodes } from './markdown'
+export { MarkdownTextDiff } from './MarkdownTextDiff'
+export type { MarkdownTextDiffProps } from './MarkdownTextDiff'
export { reconcileNotebookDocuments } from './reconcile'
export { markdownCrc, mergeNotebookMarkdownChanges, tryApplyTextChanges } from './collaboration'
export type { TextChange } from './collaboration'
diff --git a/frontend/src/lib/components/MarkdownNotebook/inlineContent.ts b/frontend/src/lib/components/MarkdownNotebook/inlineContent.ts
index 484d46c9cd9f..d8614bd28846 100644
--- a/frontend/src/lib/components/MarkdownNotebook/inlineContent.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/inlineContent.ts
@@ -224,7 +224,8 @@ export function setMark(
markType: NotebookInlineMark['type'],
shouldApplyMark: boolean
): NotebookInlineMark[] | undefined {
- if (markType === 'link') {
+ // Marks that carry an identity (link href, ref/mention ids) cannot be toggled generically.
+ if (markType === 'link' || markType === 'ref' || markType === 'mention') {
return marks.length ? marks : undefined
}
@@ -245,6 +246,68 @@ export function setLinkMark(marks: NotebookInlineMark[], href: string | null): N
return nextMarks.length ? nextMarks : undefined
}
+/** Wraps the selected range in a ref mark (`<ref id="…">`), anchoring an inline chat to it. */
+export function setInlineRefMark(
+ nodes: NotebookInlineNode[],
+ range: NotebookTextSelectionRange,
+ refId: string
+): NotebookInlineNode[] {
+ const normalizedStart = Math.min(range.start, range.end)
+ const normalizedEnd = Math.max(range.start, range.end)
+ let offset = 0
+ const output: NotebookInlineNode[] = []
+
+ nodes.forEach((node) => {
+ const length = node.type === 'hardBreak' ? 1 : node.text.length
+ const nodeStart = offset
+ const nodeEnd = offset + length
+ offset = nodeEnd
+
+ if (node.type === 'hardBreak' || nodeEnd <= normalizedStart || nodeStart >= normalizedEnd) {
+ output.push(node)
+ return
+ }
+
+ const selectionStart = Math.max(normalizedStart - nodeStart, 0)
+ const selectionEnd = Math.min(normalizedEnd - nodeStart, node.text.length)
+
+ if (selectionStart > 0) {
+ output.push({ ...node, text: node.text.slice(0, selectionStart) })
+ }
+
+ output.push({
+ ...node,
+ text: node.text.slice(selectionStart, selectionEnd),
+ marks: [...(node.marks ?? []).filter((mark) => mark.type !== 'ref'), { type: 'ref', id: refId }],
+ })
+
+ if (selectionEnd < node.text.length) {
+ output.push({ ...node, text: node.text.slice(selectionEnd) })
+ }
+ })
+
+ return normalizeInlineNodes(output)
+}
+
+/** Removes ref marks with the given id, keeping the text — used when the paired chat is deleted. */
+export function removeInlineRefMark(nodes: NotebookInlineNode[], refId: string): NotebookInlineNode[] {
+ let didChange = false
+ const output = nodes.map((node) => {
+ if (node.type === 'hardBreak') {
+ return node
+ }
+ const marks = node.marks ?? []
+ const nextMarks = marks.filter((mark) => !(mark.type === 'ref' && mark.id === refId))
+ if (nextMarks.length === marks.length) {
+ return node
+ }
+ didChange = true
+ return { ...node, marks: nextMarks.length ? nextMarks : undefined }
+ })
+
+ return didChange ? normalizeInlineNodes(output) : nodes
+}
+
export function splitInlineNodesAt(
nodes: NotebookInlineNode[],
offset: number
diff --git a/frontend/src/lib/components/MarkdownNotebook/markdown.ts b/frontend/src/lib/components/MarkdownNotebook/markdown.ts
index 8dd630a2f2c4..4529d6b8f515 100644
--- a/frontend/src/lib/components/MarkdownNotebook/markdown.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/markdown.ts
@@ -43,6 +43,15 @@ const IMAGE_BLOCK_REGEX = /^!\[((?:\\.|[^\]\\])*)\]\(((?:\\.|[^)\\])*)\)$/
const DIVIDER_BLOCK_REGEX = /^(?:-{3,}|\*{3,}|_{3,})$/
export const DIVIDER_COMPONENT_TAG = 'Divider'
export const COMMENT_COMPONENT_TAG = 'Comment'
+
+/**
+ * The `Comment` tag has two flavors: an authorial note (`text` prop, stored as a markdown
+ * `<!-- … -->` comment) and a Google Docs-style discussion thread anchored to a `<ref>`
+ * highlight (`ref` + `replies` props, stored as a real `<Comment … />` tag).
+ */
+export function isDiscussionCommentProps(props: NotebookComponentProps): boolean {
+ return typeof props.ref === 'string' || Array.isArray(props.replies)
+}
const TABLE_SEPARATOR_CELL_REGEX = /^:?-{3,}:?$/
const EMPTY_PARAGRAPH_MARKDOWN = ' '
// Every character the serializer may backslash-escape; the inline parser turns `\X` back into
@@ -80,6 +89,11 @@ const INLINE_EMPHASIS_TOKENS: InlineEmphasisToken[] = [
{ token: '*', markType: 'italic', requiresWordBoundary: false },
{ token: '_', markType: 'italic', requiresWordBoundary: true },
]
+// Inline tags are lowercase (HTML-style) so they can never collide with block components,
+// whose tag names are required to start with an uppercase letter.
+const INLINE_TAG_NAMES = ['ref', 'mention'] as const
+type InlineTagName = (typeof INLINE_TAG_NAMES)[number]
+const INLINE_TAG_OPEN_REGEX = /^<(ref|mention)\s+id=(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)')\s*>/
let generatedNodeIdCounter = 0
export function parseMarkdownNotebook(markdown: string | null | undefined): NotebookDocument {
@@ -199,7 +213,7 @@ export function serializeNode(node: NotebookBlockNode): string {
// silently drop the malformed source on the next save
return node.raw
}
- if (node.type === 'component' && node.tagName === COMMENT_COMPONENT_TAG) {
+ if (node.type === 'component' && node.tagName === COMMENT_COMPONENT_TAG && !isDiscussionCommentProps(node.props)) {
return serializeCommentNode(node)
}
if (node.type === 'component' && node.tagName === DIVIDER_COMPONENT_TAG) {
@@ -282,6 +296,17 @@ export function parseInlineMarkdown(markdown: string, marks: NotebookInlineMark[
}
}
+ if (character === '<') {
+ const inlineTag = parseInlineTag(markdown, index)
+ if (inlineTag) {
+ nodes.push(
+ ...parseInlineMarkdown(inlineTag.content, [...marks, { type: inlineTag.tagName, id: inlineTag.id }])
+ )
+ index = inlineTag.nextIndex
+ continue
+ }
+ }
+
if (character === '`') {
const end = findUnescapedToken(markdown, '`', index + 1)
if (end !== -1) {
@@ -443,6 +468,37 @@ function parseInlineLink(
return null
}
+/**
+ * Parses an inline tag (`<ref id="x">…</ref>`, `<mention id="5">…</mention>`) at `index`.
+ * A tag without a well-formed opener or matching closer is not a tag — the text stays
+ * literal, so nothing a user types can ever be swallowed.
+ */
+function parseInlineTag(
+ markdown: string,
+ index: number
+): { tagName: InlineTagName; id: string; content: string; nextIndex: number } | null {
+ const openMatch = markdown.slice(index).match(INLINE_TAG_OPEN_REGEX)
+ if (!openMatch) {
+ return null
+ }
+
+ const tagName = openMatch[1] as InlineTagName
+ const id = (openMatch[2] ?? openMatch[3] ?? '').replace(/\\(.)/g, '$1')
+ const contentStart = index + openMatch[0].length
+ const closeToken = `</${tagName}>`
+ const end = findTokenOutsideCodeSpans(markdown, closeToken, contentStart)
+ if (end === -1 || !id) {
+ return null
+ }
+
+ return {
+ tagName,
+ id,
+ content: markdown.slice(contentStart, end),
+ nextIndex: end + closeToken.length,
+ }
+}
+
function isAsciiAlphaNumeric(character: string | undefined): boolean {
return !!character && /[A-Za-z0-9]/.test(character)
}
@@ -1251,6 +1307,9 @@ function wrapInlineText(text: string, mark: NotebookInlineMark, marks: NotebookI
if (mark.type === 'code') {
return `\`${text}\``
}
+ if (mark.type === 'ref' || mark.type === 'mention') {
+ return mark.id ? `<${mark.type} id=${JSON.stringify(mark.id)}>${text}</${mark.type}>` : text
+ }
const href = sanitizeNotebookLinkHref(mark.href)
return href ? `[${text}](${escapeMarkdownLinkHref(href)})` : text
}
@@ -1274,7 +1333,7 @@ function pushTextWithMarks(nodes: NotebookInlineNode[], text: string, marks: Not
}
function findNextInlineToken(markdown: string, startIndex: number): number {
- const indexes = ['\\', '**', '*', '__', '_', '<u>', '~~', '`', '[', '\n']
+ const indexes = ['\\', '**', '*', '__', '_', '<u>', '<ref', '<mention', '~~', '`', '[', '\n']
.map((token) => markdown.indexOf(token, startIndex))
.filter((index) => index !== -1)
return indexes.length ? Math.min(...indexes) : markdown.length
@@ -1332,6 +1391,16 @@ function htmlNodeToInlineNodes(node: ChildNode, marks: NotebookInlineMark[]): No
nextMarks.push({ type: 'link', href })
}
}
+ if (tagName === 'span') {
+ const refId = node.getAttribute('data-notebook-ref')
+ if (refId) {
+ nextMarks.push({ type: 'ref', id: refId })
+ }
+ const mentionId = node.getAttribute('data-notebook-mention')
+ if (mentionId) {
+ nextMarks.push({ type: 'mention', id: mentionId })
+ }
+ }
const children = htmlChildNodesToInlineNodes(node, nextMarks)
@@ -1378,6 +1447,12 @@ function wrapHtmlText(html: string, mark: NotebookInlineMark): string {
if (mark.type === 'code') {
return `<code>${html}</code>`
}
+ if (mark.type === 'ref') {
+ return `<span class="MarkdownNotebook__ref" data-notebook-ref="${escapeAttribute(mark.id)}">${html}</span>`
+ }
+ if (mark.type === 'mention') {
+ return `<span class="MarkdownNotebook__mention" data-notebook-mention="${escapeAttribute(mark.id)}">${html}</span>`
+ }
const href = sanitizeNotebookLinkHref(mark.href)
return href ? `<a href="${escapeAttribute(href)}">${html}</a>` : html
}
@@ -1393,7 +1468,7 @@ export function escapeInlineMarkdownText(text: string): string {
// Intraword underscores (snake_case) are never emphasis, keep them readable
isAsciiAlphaNumeric(source[offset - 1]) && isAsciiAlphaNumeric(source[offset + 1]) ? '_' : '\\_'
)
- .replace(/<(?=\/?u>)/g, '\\<')
+ .replace(/<(?=\/?(?:u>|ref[\s>]|mention[\s>]))/g, '\\<')
}
export function escapeCodeSpanText(text: string): string {
diff --git a/frontend/src/lib/components/MarkdownNotebook/markdownRoundTrip.test.ts b/frontend/src/lib/components/MarkdownNotebook/markdownRoundTrip.test.ts
index d3900ad936c5..2efb5d103ed8 100644
--- a/frontend/src/lib/components/MarkdownNotebook/markdownRoundTrip.test.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/markdownRoundTrip.test.ts
@@ -479,6 +479,129 @@ describe('markdown round trip', () => {
})
})
+ describe('inline ref and mention tags', () => {
+ it('parses a ref tag into a ref mark', () => {
+ const nodes = parseMarkdownNotebook('Before <ref id="banana">highlighted text</ref> after').nodes
+ const node = nodes[0] as NotebookTextBlockNode
+
+ expect(node.children).toEqual([
+ { type: 'text', text: 'Before ' },
+ { type: 'text', text: 'highlighted text', marks: [{ type: 'ref', id: 'banana' }] },
+ { type: 'text', text: ' after' },
+ ])
+ })
+
+ it('parses a mention tag into a mention mark', () => {
+ const nodes = parseMarkdownNotebook('Ping <mention id="5">@Marius</mention> please').nodes
+ const node = nodes[0] as NotebookTextBlockNode
+
+ expect(node.children[1]).toEqual({
+ type: 'text',
+ text: '@Marius',
+ marks: [{ type: 'mention', id: '5' }],
+ })
+ })
+
+ it('round-trips ref and mention marks', () => {
+ const document = makeDocument([
+ paragraph([
+ text('Hello '),
+ text('@Marius', [{ type: 'mention', id: '5' }]),
+ text(' look at '),
+ text('this number', [{ type: 'ref', id: 'banana' }]),
+ ]),
+ ])
+
+ expect(serializeMarkdownNotebook(document)).toEqual(
+ 'Hello <mention id="5">@Marius</mention> look at <ref id="banana">this number</ref>'
+ )
+ expect(stripIds(roundTrip(document))).toEqual(stripIds(document))
+ })
+
+ it('keeps formatting marks inside the ref tag', () => {
+ const document = makeDocument([
+ paragraph([text('important', [{ type: 'bold' }, { type: 'ref', id: 'r1' }])]),
+ ])
+
+ expect(serializeMarkdownNotebook(document)).toEqual('<ref id="r1">**important**</ref>')
+ expect(stripIds(roundTrip(document))).toEqual(stripIds(document))
+ })
+
+ it('parses formatting nested inside a ref tag', () => {
+ const nodes = parseMarkdownNotebook('<ref id="r1">plain **bold** tail</ref>').nodes
+ const node = nodes[0] as NotebookTextBlockNode
+
+ expect(node.children).toEqual([
+ { type: 'text', text: 'plain ', marks: [{ type: 'ref', id: 'r1' }] },
+ { type: 'text', text: 'bold', marks: [{ type: 'bold' }, { type: 'ref', id: 'r1' }] },
+ { type: 'text', text: ' tail', marks: [{ type: 'ref', id: 'r1' }] },
+ ])
+ })
+
+ it.each(['<ref id="x">unclosed', '<ref>no id</ref>', '<ref id="">empty</ref>', '<refid="x">a</ref>'])(
+ 'treats malformed inline tag %s as literal text',
+ (markdown) => {
+ const nodes = parseMarkdownNotebook(markdown).nodes
+ const node = nodes[0] as NotebookTextBlockNode
+
+ expect(node.children.every((child) => child.type !== 'text' || !child.marks?.length)).toBe(true)
+ expect(getNodeText(node)).toEqual(markdown)
+ }
+ )
+
+ it('round-trips literal ref-looking text without creating a mark', () => {
+ const document = makeDocument([paragraph([text('see <ref id="x">this</ref> tag')])])
+ const result = roundTrip(document)
+
+ expect(stripIds(result)).toEqual(stripIds(document))
+ })
+
+ it('round-trips ref marks inside list items', () => {
+ const document = makeDocument([
+ {
+ id: '',
+ type: 'list',
+ ordered: false,
+ items: [
+ {
+ children: [text('todo item', [{ type: 'ref', id: 'r2' }])],
+ depth: 0,
+ ordered: false,
+ start: undefined,
+ },
+ ],
+ },
+ ])
+
+ expect(stripIds(roundTrip(document))).toEqual(stripIds(document))
+ })
+ })
+
+ 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"}]} />'
+ const nodes = parseMarkdownNotebook(markdown).nodes
+
+ expect(nodes[0]).toMatchObject({
+ type: 'component',
+ tagName: 'Comment',
+ props: {
+ ref: 'banana',
+ replies: [{ id: 'r1', author: 'Ann', text: 'Looks off' }],
+ },
+ })
+ expect(serializeMarkdownNotebook(parseMarkdownNotebook(markdown))).toEqual(markdown)
+ })
+
+ it('keeps the authorial note flavor serializing as an html comment', () => {
+ const document = makeDocument([
+ { id: '', type: 'component', tagName: 'Comment', props: { text: 'just a note' } },
+ ])
+
+ expect(serializeMarkdownNotebook(document)).toEqual('<!-- just a note -->')
+ })
+ })
+
describe('list indentation', () => {
it('clamps externally indented nesting to one level per step', () => {
const nodes = parseMarkdownNotebook('- parent\n - child\n - grandchild').nodes
diff --git a/frontend/src/lib/components/MarkdownNotebook/renderNode.tsx b/frontend/src/lib/components/MarkdownNotebook/renderNode.tsx
index 9bd9e9aebc41..d65956c7ce4e 100644
--- a/frontend/src/lib/components/MarkdownNotebook/renderNode.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/renderNode.tsx
@@ -3,7 +3,12 @@ import { MutableRefObject } from 'react'
import { CommentBlock } from './CommentBlock'
import { ComponentPanel, ComponentPanelVisibility } from './componentPanels'
import { DividerBlock } from './DividerBlock'
-import { isCommentComponentNode, isDividerComponentNode, isPromptComponentNode } from './documentModel'
+import {
+ isCommentComponentNode,
+ isDiscussionCommentNode,
+ isDividerComponentNode,
+ isPromptComponentNode,
+} from './documentModel'
import { EditableCodeBlock } from './EditableCodeBlock'
import { EditableListBlock } from './EditableListBlock'
import { EditablePromptComponent } from './EditablePromptComponent'
@@ -122,7 +127,9 @@ export function renderNode({
)
}
- if (isCommentComponentNode(node)) {
+ // Discussion comments (ref/replies) render through the registry shell; only the
+ // authorial note flavor uses the inline chip.
+ if (isCommentComponentNode(node) && !isDiscussionCommentNode(node)) {
return (
<CommentBlock
node={node}
diff --git a/frontend/src/lib/components/MarkdownNotebook/types.ts b/frontend/src/lib/components/MarkdownNotebook/types.ts
index e78c4421963c..4f9e9d6d796c 100644
--- a/frontend/src/lib/components/MarkdownNotebook/types.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/types.ts
@@ -9,6 +9,10 @@ export type NotebookInlineMark =
| { type: 'strike' }
| { type: 'code' }
| { type: 'link'; href: string }
+ /** Anchors an inline chat to this text: `<ref id="x">text</ref>` pairs with `<Chat ref="x" />`. */
+ | { type: 'ref'; id: string }
+ /** A person mention: `<mention id="5">@Name</mention>` — the text is the display label. */
+ | { type: 'mention'; id: string }
export type NotebookTextInlineNode = {
type: 'text'
diff --git a/frontend/src/lib/components/MarkdownNotebook/utils.ts b/frontend/src/lib/components/MarkdownNotebook/utils.ts
index 6c3ced858fab..4885d2454519 100644
--- a/frontend/src/lib/components/MarkdownNotebook/utils.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/utils.ts
@@ -226,6 +226,13 @@ function getInlineMarkOrder(mark: NotebookInlineMark): number {
if (mark.type === 'strike') {
return 4
}
+ if (mark.type === 'mention') {
+ return 6
+ }
+ if (mark.type === 'ref') {
+ // Outermost, so the ref tag wraps the fully formatted text.
+ return 7
+ }
return 5
}
diff --git a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookDiscussionComment.tsx b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookDiscussionComment.tsx
new file mode 100644
index 000000000000..eff9d57b35bc
--- /dev/null
+++ b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookDiscussionComment.tsx
@@ -0,0 +1,186 @@
+import { useValues } from 'kea'
+import { useEffect, useRef, useState } from 'react'
+
+import { IconSend, IconTrash } from '@posthog/icons'
+import { LemonButton, LemonTextArea, ProfilePicture } from '@posthog/lemon-ui'
+
+import { wasNotebookNodeJustInserted } from 'lib/components/MarkdownNotebook/freshlyInserted'
+import {
+ NotebookComponentBlockNode,
+ NotebookComponentRenderProps,
+ NotebookPropValue,
+} from 'lib/components/MarkdownNotebook/types'
+import { TZLabel } from 'lib/components/TZLabel'
+import { dayjs } from 'lib/dayjs'
+import { uuid } from 'lib/utils'
+import { userLogic } from 'scenes/userLogic'
+
+/**
+ * One human reply inside a `<Comment ref="…" replies={[…]} />` tag. Replies live in the
+ * markdown itself, keyed by `id` so concurrent replies from different people merge
+ * instead of clobbering each other (see mergeIdKeyedArrayPropValues in collaboration.ts).
+ */
+export type NotebookCommentReply = {
+ id: string
+ text: string
+ author?: string
+ authorId?: number
+ at?: string
+}
+
+export function getNotebookCommentReplies(value: NotebookPropValue | undefined): NotebookCommentReply[] {
+ if (!Array.isArray(value)) {
+ return []
+ }
+
+ return value.flatMap((entry): NotebookCommentReply[] => {
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
+ return []
+ }
+ const { id, text, author, authorId, at } = entry as Record<string, NotebookPropValue>
+ if (typeof id !== 'string' || typeof text !== 'string') {
+ return []
+ }
+ return [
+ {
+ id,
+ text,
+ author: typeof author === 'string' ? author : undefined,
+ authorId: typeof authorId === 'number' ? authorId : undefined,
+ at: typeof at === 'string' ? at : undefined,
+ },
+ ]
+ })
+}
+
+export function getNotebookDiscussionCommentTitle(node: NotebookComponentBlockNode): string | null {
+ const firstReply = getNotebookCommentReplies(node.props.replies)[0]
+ return firstReply ? firstReply.text : 'Comment thread'
+}
+
+/**
+ * A Google Docs-style inline comment thread anchored to highlighted text: the thread hangs
+ * in the right margin and the `<ref>` tag it points at gets a persistent highlight.
+ * Deleting the thread also unwraps the highlight (handled by the editor); removing the
+ * highlight leaves the thread in place — it holds people's replies and is deleted
+ * separately.
+ */
+export function NotebookDiscussionComment({
+ node,
+ mode,
+ updateProps,
+ deleteNode,
+}: NotebookComponentRenderProps): JSX.Element {
+ const { user } = useValues(userLogic)
+ const replies = getNotebookCommentReplies(node.props.replies)
+ const refId = typeof node.props.ref === 'string' ? node.props.ref : null
+ const [draft, setDraft] = useState('')
+ const [isHovered, setIsHovered] = useState(false)
+ const repliesRef = useRef<HTMLDivElement | null>(null)
+ const isEditable = mode === 'edit'
+ const draftText = draft.trim()
+
+ // Light up the anchored highlight while the cursor is over the thread.
+ useEffect(() => {
+ if (!refId || !isHovered || typeof document === 'undefined') {
+ return
+ }
+
+ const highlightedElements = Array.from(document.querySelectorAll(`[data-notebook-ref="${CSS.escape(refId)}"]`))
+ highlightedElements.forEach((element) => element.classList.add('MarkdownNotebook__ref--active'))
+ return () => {
+ highlightedElements.forEach((element) => element.classList.remove('MarkdownNotebook__ref--active'))
+ }
+ }, [refId, isHovered])
+
+ // The replies list is height-capped; new replies should land in view, not below the fold.
+ useEffect(() => {
+ const element = repliesRef.current
+ if (element) {
+ element.scrollTop = element.scrollHeight
+ }
+ }, [replies.length])
+
+ const submitReply = (): void => {
+ if (!draftText || !isEditable) {
+ return
+ }
+
+ const reply: NotebookCommentReply = {
+ id: uuid(),
+ text: draftText,
+ author: user?.first_name || user?.email || undefined,
+ authorId: user?.id,
+ at: dayjs.utc().toISOString(),
+ }
+ updateProps({ replies: [...replies, reply] })
+ setDraft('')
+ }
+
+ return (
+ <div
+ className="MarkdownNotebook__discussion-comment"
+ onMouseEnter={() => setIsHovered(true)}
+ onMouseLeave={() => setIsHovered(false)}
+ data-attr="notebook-discussion-comment"
+ >
+ <div className="MarkdownNotebook__discussion-comment-replies" ref={repliesRef}>
+ {replies.map((reply) => (
+ <div key={reply.id} className="MarkdownNotebook__discussion-comment-reply">
+ <ProfilePicture user={{ first_name: reply.author }} size="sm" />
+ <div className="MarkdownNotebook__discussion-comment-reply-body">
+ <div className="MarkdownNotebook__discussion-comment-reply-meta">
+ <span className="MarkdownNotebook__discussion-comment-reply-author">
+ {reply.author ?? 'Someone'}
+ </span>
+ {reply.at ? (
+ <span className="MarkdownNotebook__discussion-comment-reply-time">
+ <TZLabel time={reply.at} />
+ </span>
+ ) : null}
+ </div>
+ <div className="MarkdownNotebook__discussion-comment-reply-text">{reply.text}</div>
+ </div>
+ </div>
+ ))}
+ {!replies.length && !isEditable ? (
+ <div className="MarkdownNotebook__discussion-comment-empty">No replies yet</div>
+ ) : null}
+ </div>
+ {isEditable ? (
+ <div className="MarkdownNotebook__discussion-comment-composer">
+ <LemonTextArea
+ value={draft}
+ onChange={setDraft}
+ onPressEnter={submitReply}
+ placeholder={replies.length ? 'Reply...' : 'Comment...'}
+ minRows={1}
+ maxRows={6}
+ autoFocus={wasNotebookNodeJustInserted(node.id)}
+ stopPropagation
+ data-attr="notebook-discussion-comment-input"
+ />
+ <div className="MarkdownNotebook__discussion-comment-actions">
+ {isEditable ? (
+ <LemonButton
+ size="xsmall"
+ icon={<IconTrash />}
+ tooltip="Delete thread"
+ aria-label="Delete thread"
+ onClick={deleteNode}
+ />
+ ) : null}
+ <LemonButton
+ size="xsmall"
+ type="primary"
+ icon={<IconSend />}
+ onClick={submitReply}
+ disabledReason={draftText ? undefined : 'Write a reply first'}
+ aria-label="Send reply"
+ />
+ </div>
+ </div>
+ ) : null}
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/notebooks/Notebook/Notebook.tsx b/frontend/src/scenes/notebooks/Notebook/Notebook.tsx
index 52f021d53ab7..0f26138772bd 100644
--- a/frontend/src/scenes/notebooks/Notebook/Notebook.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/Notebook.tsx
@@ -29,6 +29,7 @@ import { NotebookColumnRight } from './NotebookColumnRight'
import { NotebookConflictWarning } from './NotebookConflictWarning'
import { NotebookHistoryWarning } from './NotebookHistory'
import { NotebookLoadingState } from './NotebookLoadingState'
+import { NotebookMergeConflictDetails } from './NotebookMergeConflictDetails'
import { notebookSettingsLogic } from './notebookSettingsLogic'
import { openUpgradeToMarkdownNotebookDialog } from './notebookUpgradeDialog'
@@ -67,6 +68,7 @@ export function Notebook({
isTemplate,
notebookMissing,
content,
+ comments,
} = useValues(logic)
const { duplicateNotebook, loadNotebook, setEditable, setLocalContent, setContainerSize } = useActions(logic)
const { isExpanded } = useValues(notebookSettingsLogic)
@@ -112,7 +114,7 @@ export function Notebook({
const isMarkdownNotebook = isMarkdownNotebookContent(content)
const canUpgradeToMarkdownNotebooks = !!featureFlags[FEATURE_FLAGS.MARKDOWN_NOTEBOOKS]
const upgradeToMarkdownNotebook = (): void => {
- openUpgradeToMarkdownNotebookDialog({ content, setLocalContent })
+ openUpgradeToMarkdownNotebookDialog({ content, comments, setLocalContent })
}
return (
@@ -150,6 +152,7 @@ export function Notebook({
)}
<NotebookHistoryWarning />
<NotebookCollabConflictModal />
+ <NotebookMergeConflictDetails />
{shortId === SCRATCHPAD_NOTEBOOK.short_id ? (
<LemonBanner
type="info"
diff --git a/frontend/src/scenes/notebooks/Notebook/NotebookMergeConflictDetails.tsx b/frontend/src/scenes/notebooks/Notebook/NotebookMergeConflictDetails.tsx
new file mode 100644
index 000000000000..dbb92419c859
--- /dev/null
+++ b/frontend/src/scenes/notebooks/Notebook/NotebookMergeConflictDetails.tsx
@@ -0,0 +1,76 @@
+import { useActions, useValues } from 'kea'
+
+import { IconCopy } from '@posthog/icons'
+import { LemonButton, LemonModal } from '@posthog/lemon-ui'
+
+import { MarkdownTextDiff } from 'lib/components/MarkdownNotebook'
+import type { NotebookCollaborationConflict } from 'lib/components/MarkdownNotebook'
+import { copyToClipboard } from 'lib/utils/copyToClipboard'
+
+import { notebookLogic } from './notebookLogic'
+
+function ConflictItem({ conflict }: { conflict: NotebookCollaborationConflict }): JSX.Element {
+ const remoteDeleted = !conflict.remoteMarkdown
+ const localDeleted = !conflict.localMarkdown
+
+ return (
+ <div className="border rounded overflow-hidden">
+ <div className="flex items-center justify-between gap-2 p-2 border-b bg-surface-secondary">
+ <span className="text-xs font-medium text-secondary">
+ {remoteDeleted
+ ? 'A collaborator deleted this block — your edit was kept'
+ : localDeleted
+ ? 'You deleted this block — a collaborator edited it, and your deletion was kept'
+ : 'You both edited this block — your version was kept'}
+ </span>
+ {!remoteDeleted && (
+ <LemonButton
+ size="xsmall"
+ type="secondary"
+ icon={<IconCopy />}
+ onClick={() => void copyToClipboard(conflict.remoteMarkdown, "the collaborator's version")}
+ >
+ Copy their version
+ </LemonButton>
+ )}
+ </div>
+ <div className="p-3 max-h-60 overflow-y-auto overflow-x-hidden break-words font-mono text-sm">
+ <MarkdownTextDiff before={conflict.remoteMarkdown} after={conflict.localMarkdown} />
+ </div>
+ </div>
+ )
+}
+
+export function NotebookMergeConflictDetails(): JSX.Element {
+ const { markdownMergeConflictDetails } = useValues(notebookLogic)
+ const { dismissMarkdownMergeConflictDetails } = useActions(notebookLogic)
+
+ return (
+ <LemonModal
+ isOpen={!!markdownMergeConflictDetails}
+ onClose={dismissMarkdownMergeConflictDetails}
+ title="Review merge conflicts"
+ description="These edits couldn't be merged automatically, so your version is showing. The collaborator's conflicting text is below in case you want to recover it."
+ footer={
+ <LemonButton type="primary" onClick={dismissMarkdownMergeConflictDetails}>
+ Close
+ </LemonButton>
+ }
+ width={720}
+ >
+ <div className="flex flex-col gap-3">
+ <div className="flex gap-4 text-xs text-secondary">
+ <span>
+ <del className="text-danger bg-danger-highlight line-through">A collaborator wrote</del>
+ </span>
+ <span>
+ <ins className="text-success bg-success-highlight no-underline">Your version (kept)</ins>
+ </span>
+ </div>
+ {(markdownMergeConflictDetails ?? []).map((conflict, index) => (
+ <ConflictItem key={`${conflict.nodeId}-${index}`} conflict={conflict} />
+ ))}
+ </div>
+ </LemonModal>
+ )
+}
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.test.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.test.ts
new file mode 100644
index 000000000000..49db30be0af7
--- /dev/null
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.test.ts
@@ -0,0 +1,321 @@
+import { parseMarkdownNotebook, serializeMarkdownNotebook } from 'lib/components/MarkdownNotebook/markdown'
+import { JSONContent } from 'lib/components/RichContentEditor/types'
+
+import { NotebookNodeType } from '../types'
+import { convertMarkdownToNotebookContent } from './markdownNotebookDowngrade'
+import { convertNotebookContentToMarkdown } from './markdownNotebookV2'
+
+describe('markdownNotebookDowngrade', () => {
+ it('returns an empty doc for empty markdown', () => {
+ expect(convertMarkdownToNotebookContent('')).toEqual({ type: 'doc', content: [] })
+ })
+
+ it('converts paragraphs with hard breaks', () => {
+ expect(convertMarkdownToNotebookContent('First line\nSecond line')).toEqual({
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ { type: 'text', text: 'First line' },
+ { type: 'hardBreak' },
+ { type: 'text', text: 'Second line' },
+ ],
+ },
+ ],
+ })
+ })
+
+ it.each([[1], [2], [3], [4], [5], [6]])('converts level %i headings', (level) => {
+ expect(convertMarkdownToNotebookContent(`${'#'.repeat(level)} Title`)).toEqual({
+ type: 'doc',
+ content: [{ type: 'heading', attrs: { level }, content: [{ type: 'text', text: 'Title' }] }],
+ })
+ })
+
+ it('converts blockquotes to a blockquote with a paragraph child', () => {
+ expect(convertMarkdownToNotebookContent('> Quoted text')).toEqual({
+ type: 'doc',
+ content: [
+ {
+ type: 'blockquote',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Quoted text' }] }],
+ },
+ ],
+ })
+ })
+
+ it.each<[string, string, JSONContentMarks]>([
+ ['**bold**', 'bold', [{ type: 'bold' }]],
+ ['*italic*', 'italic', [{ type: 'italic' }]],
+ ['<u>underline</u>', 'underline', [{ type: 'underline' }]],
+ ['~~strike~~', 'strike', [{ type: 'strike' }]],
+ ['`code`', 'code', [{ type: 'code' }]],
+ ['[label](https://posthog.com)', 'label', [{ type: 'link', attrs: { href: 'https://posthog.com' } }]],
+ ['<ref id="thread-1">anchored</ref>', 'anchored', [{ type: 'comment', attrs: { id: 'thread-1' } }]],
+ ])('converts inline %s to a marked text node', (markdown, text, marks) => {
+ expect(convertMarkdownToNotebookContent(markdown)).toEqual({
+ type: 'doc',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text, marks }] }],
+ })
+ })
+
+ it('converts mention marks to atomic v1 mention nodes, replacing the label', () => {
+ expect(convertMarkdownToNotebookContent('Ping <mention id="5">@Marius</mention> please')).toEqual({
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ { type: 'text', text: 'Ping ' },
+ { type: NotebookNodeType.Mention, attrs: { id: 5 } },
+ { type: 'text', text: ' please' },
+ ],
+ },
+ ],
+ })
+ })
+
+ it('keeps the label as plain text when a mention id is not numeric', () => {
+ expect(convertMarkdownToNotebookContent('<mention id="abc">@Someone</mention>')).toEqual({
+ type: 'doc',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: '@Someone' }] }],
+ })
+ })
+
+ it('collapses a partially formatted mention label into a single mention node', () => {
+ expect(convertMarkdownToNotebookContent('<mention id="7">@**M**ember</mention>')).toEqual({
+ type: 'doc',
+ content: [{ type: 'paragraph', content: [{ type: NotebookNodeType.Mention, attrs: { id: 7 } }] }],
+ })
+ })
+
+ it('reconstructs nested bullet lists from item depth', () => {
+ expect(convertMarkdownToNotebookContent('- One\n- Two\n - Nested\n- Three')).toEqual({
+ type: 'doc',
+ content: [
+ {
+ type: 'bulletList',
+ content: [
+ listItem('One'),
+ {
+ type: 'listItem',
+ content: [
+ { type: 'paragraph', content: [{ type: 'text', text: 'Two' }] },
+ { type: 'bulletList', content: [listItem('Nested')] },
+ ],
+ },
+ listItem('Three'),
+ ],
+ },
+ ],
+ })
+ })
+
+ it('converts ordered lists and keeps a non-default start', () => {
+ expect(convertMarkdownToNotebookContent('3. Third\n4. Fourth')).toEqual({
+ type: 'doc',
+ content: [{ type: 'orderedList', attrs: { start: 3 }, content: [listItem('Third'), listItem('Fourth')] }],
+ })
+ })
+
+ it('nests an ordered sub-list inside a bullet list item', () => {
+ expect(convertMarkdownToNotebookContent('- Parent\n 1. Child')).toEqual({
+ type: 'doc',
+ content: [
+ {
+ type: 'bulletList',
+ content: [
+ {
+ type: 'listItem',
+ content: [
+ { type: 'paragraph', content: [{ type: 'text', text: 'Parent' }] },
+ { type: 'orderedList', content: [listItem('Child')] },
+ ],
+ },
+ ],
+ },
+ ],
+ })
+ })
+
+ it('wraps blockquoted lists in a blockquote', () => {
+ expect(convertMarkdownToNotebookContent('> - One\n> - Two')).toEqual({
+ type: 'doc',
+ content: [
+ { type: 'blockquote', content: [{ type: 'bulletList', content: [listItem('One'), listItem('Two')] }] },
+ ],
+ })
+ })
+
+ it('converts code blocks to codeBlock with a single text child', () => {
+ expect(convertMarkdownToNotebookContent('```python\nprint("hi")\nprint("bye")\n```')).toEqual({
+ type: 'doc',
+ content: [
+ {
+ type: 'codeBlock',
+ attrs: { language: 'python' },
+ content: [{ type: 'text', text: 'print("hi")\nprint("bye")' }],
+ },
+ ],
+ })
+ })
+
+ it('converts empty code blocks without a language', () => {
+ expect(convertMarkdownToNotebookContent('```\n```')).toEqual({
+ type: 'doc',
+ content: [{ type: 'codeBlock', attrs: { language: null } }],
+ })
+ })
+
+ it('converts tables to TipTap table structure with paragraph-wrapped cells', () => {
+ expect(convertMarkdownToNotebookContent('| Name | Value |\n| --- | --- |\n| Users | **42** |')).toEqual({
+ type: 'doc',
+ content: [
+ {
+ type: 'table',
+ content: [
+ {
+ type: 'tableRow',
+ content: [tableCell('tableHeader', 'Name'), tableCell('tableHeader', 'Value')],
+ },
+ {
+ type: 'tableRow',
+ content: [
+ tableCell('tableCell', 'Users'),
+ {
+ type: 'tableCell',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: '42', marks: [{ type: 'bold' }] }],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ })
+ })
+
+ it('converts dividers to horizontalRule', () => {
+ expect(convertMarkdownToNotebookContent('---')).toEqual({
+ type: 'doc',
+ content: [{ type: 'horizontalRule' }],
+ })
+ })
+
+ it('converts images to the v1 image node', () => {
+ expect(convertMarkdownToNotebookContent('![PostHog](https://example.com/hog.png)')).toEqual({
+ type: 'doc',
+ content: [{ type: NotebookNodeType.Image, attrs: { src: 'https://example.com/hog.png', alt: 'PostHog' } }],
+ })
+ })
+
+ it('converts component tags to their v1 node type with props as attrs', () => {
+ expect(convertMarkdownToNotebookContent('<Query query={{"kind":"DataTableNode"}} />')).toEqual({
+ type: 'doc',
+ content: [{ type: NotebookNodeType.Query, attrs: { query: { kind: 'DataTableNode' } } }],
+ })
+ })
+
+ it.each<[string, NotebookNodeType]>([
+ ['<Recording id="abc" />', NotebookNodeType.Recording],
+ ['<FeatureFlag id={42} />', NotebookNodeType.FeatureFlag],
+ ['<Survey id="s1" />', NotebookNodeType.Survey],
+ ['<Embed src="https://example.com" />', NotebookNodeType.Embed],
+ ])('converts %s to its v1 node type', (markdown, nodeType) => {
+ expect(convertMarkdownToNotebookContent(markdown).content?.[0]?.type).toEqual(nodeType)
+ })
+
+ it('converts authorial comments to plain paragraphs', () => {
+ expect(convertMarkdownToNotebookContent('<!-- A note to self -->')).toEqual({
+ type: 'doc',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'A note to self' }] }],
+ })
+ })
+
+ it('drops discussion comment threads but keeps the ref anchor as a comment mark', () => {
+ expect(
+ convertMarkdownToNotebookContent(
+ '<ref id="t1">anchored</ref>\n\n<Comment ref="t1" replies={[{"text":"hi"}]} />'
+ )
+ ).toEqual({
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'anchored', marks: [{ type: 'comment', attrs: { id: 't1' } }] }],
+ },
+ ],
+ })
+ })
+
+ it.each([['<Chat id="c1" />'], ['<Prompt text="hello" />']])('drops %s blocks', (markdown) => {
+ expect(convertMarkdownToNotebookContent(markdown)).toEqual({ type: 'doc', content: [] })
+ })
+
+ it('re-emits UnknownNode wrappers as their original node type', () => {
+ expect(convertMarkdownToNotebookContent('<UnknownNode nodeType="ph-custom" foo="bar" />')).toEqual({
+ type: 'doc',
+ content: [{ type: 'ph-custom', attrs: { foo: 'bar' } }],
+ })
+ })
+
+ it('falls back to a paragraph with the serialized source for unmapped tags', () => {
+ expect(convertMarkdownToNotebookContent('<Mystery foo="bar" />')).toEqual({
+ type: 'doc',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: '<Mystery foo="bar" />' }] }],
+ })
+ })
+
+ it('round-trips a representative lossless document through v1 and back', () => {
+ const markdown = [
+ '# Roadmap',
+ 'A **bold**, *italic*, <u>underlined</u>, ~~struck~~, `coded`, [linked](https://posthog.com) line.',
+ 'Multi\nline paragraph',
+ '<Comment ref="thread-1" replies={[]} />',
+ '<ref id="thread-1">Highlighted decision</ref> needs review.',
+ 'Ping <mention id="5">@member</mention> about this.',
+ '> A wise quote',
+ '- First bullet\n- Second bullet\n - Nested bullet',
+ '1. Step one\n2. Step two',
+ '> - Quoted item one\n> - Quoted item two',
+ '| Metric | Value |\n| --- | --- |\n| Users | **42** |',
+ '```python\nprint("hello")\n```',
+ '---',
+ '<Query query={{"kind":"DataTableNode"}} />',
+ '<UnknownNode nodeType="ph-custom" foo="bar" />',
+ '![Dashboard](https://example.com/dashboard.png)',
+ ].join('\n\n')
+
+ const roundTrippedMarkdown = convertNotebookContentToMarkdown(convertMarkdownToNotebookContent(markdown))
+
+ expect(serializeMarkdownNotebook(parseMarkdownNotebook(roundTrippedMarkdown))).toEqual(
+ serializeMarkdownNotebook(parseMarkdownNotebook(markdown))
+ )
+ })
+
+ it('keeps discussion anchors but loses thread replies on round-trip', () => {
+ const markdown = [
+ '<ref id="t1">anchored</ref>',
+ '<Comment ref="t1" replies={[{"author":"Ann","text":"hi"}]} />',
+ ].join('\n\n')
+
+ expect(convertNotebookContentToMarkdown(convertMarkdownToNotebookContent(markdown))).toEqual(
+ '<Comment ref="t1" replies={[]} />\n\n<ref id="t1">anchored</ref>'
+ )
+ })
+})
+
+type JSONContentMarks = NonNullable<JSONContent['marks']>
+
+function listItem(text: string): JSONContent {
+ return { type: 'listItem', content: [{ type: 'paragraph', content: [{ type: 'text', text }] }] }
+}
+
+function tableCell(type: 'tableHeader' | 'tableCell', text: string): JSONContent {
+ return { type, content: [{ type: 'paragraph', content: [{ type: 'text', text }] }] }
+}
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.ts
new file mode 100644
index 000000000000..c4484d22390e
--- /dev/null
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookDowngrade.ts
@@ -0,0 +1,282 @@
+/**
+ * Downgrades a markdown (v2) notebook to TipTap JSONContent (v1) — the inverse of
+ * `convertNotebookContentToMarkdown`.
+ *
+ * Known one-way losses (v1 has nowhere to store these):
+ * - Discussion `<Comment ref="…" replies={…} />` threads: the inline `<ref>` highlight survives as
+ * a v1 `comment` mark (so the anchor is preserved), but the thread node and its replies are
+ * dropped — v1 keeps discussion threads outside the document content.
+ * - `<Chat />` (AI chat) and `<Prompt />` blocks are dropped — v1 has no equivalent node.
+ * - Authorial `<!-- … -->` comments become plain paragraphs: the note text stays visible, but its
+ * comment framing is lost.
+ * - Table column alignments are dropped — v1 tables do not store alignment.
+ */
+import {
+ COMMENT_COMPONENT_TAG,
+ DIVIDER_COMPONENT_TAG,
+ isDiscussionCommentProps,
+ parseMarkdownNotebook,
+ serializeNode,
+} from 'lib/components/MarkdownNotebook/markdown'
+import {
+ NotebookBlockNode,
+ NotebookCodeBlockNode,
+ NotebookComponentBlockNode,
+ NotebookInlineMark,
+ NotebookInlineNode,
+ NotebookListBlockNode,
+ NotebookTableBlockNode,
+ NotebookTableCell,
+} from 'lib/components/MarkdownNotebook/types'
+import { JSONContent } from 'lib/components/RichContentEditor/types'
+
+import { NotebookNodeType } from '../types'
+import { NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG } from './markdownNotebookV2'
+
+type JSONContentMark = NonNullable<JSONContent['marks']>[number]
+
+const MARKDOWN_TAG_TO_NOTEBOOK_NODE_TYPE: Partial<Record<string, NotebookNodeType>> = Object.entries(
+ NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG
+).reduce<Partial<Record<string, NotebookNodeType>>>((mapping, [nodeType, tagName]) => {
+ if (tagName) {
+ mapping[tagName] = nodeType as NotebookNodeType
+ }
+ return mapping
+}, {})
+
+// No v1 equivalent — dropped on downgrade (see module docstring).
+const DROPPED_COMPONENT_TAGS = new Set(['Chat', 'Prompt'])
+
+export function convertMarkdownToNotebookContent(markdown: string): JSONContent {
+ const document = parseMarkdownNotebook(markdown)
+ const content = document.nodes.flatMap((node) => {
+ const converted = convertBlockNode(node)
+ return converted ? [converted] : []
+ })
+
+ return { type: 'doc', content }
+}
+
+function convertBlockNode(node: NotebookBlockNode): JSONContent | null {
+ if (node.type === 'paragraph') {
+ return makeParagraph(convertInlineNodes(node.children))
+ }
+ if (node.type === 'heading') {
+ const content = convertInlineNodes(node.children)
+ return { type: 'heading', attrs: { level: node.level ?? 1 }, ...(content.length ? { content } : {}) }
+ }
+ if (node.type === 'blockquote') {
+ return { type: 'blockquote', content: [makeParagraph(convertInlineNodes(node.children))] }
+ }
+ if (node.type === 'list') {
+ const list = convertListNode(node)
+ return node.blockquote ? { type: 'blockquote', content: [list] } : list
+ }
+ if (node.type === 'table') {
+ return convertTableNode(node)
+ }
+ if (node.type === 'code') {
+ return convertCodeNode(node)
+ }
+ if (node.type === 'component') {
+ return convertComponentNode(node)
+ }
+ return makeParagraph(convertInlineNodes(node.children))
+}
+
+function convertComponentNode(node: NotebookComponentBlockNode): JSONContent | null {
+ if (node.tagName === DIVIDER_COMPONENT_TAG) {
+ return { type: 'horizontalRule' }
+ }
+ if (node.tagName === COMMENT_COMPONENT_TAG) {
+ if (isDiscussionCommentProps(node.props)) {
+ // Discussion thread: the inline `<ref>` highlight already became a `comment` mark on
+ // the text it anchors to; the thread itself cannot be represented in v1 content, so it
+ // is dropped (see module docstring).
+ return null
+ }
+ // Authorial note: surfaced as a plain paragraph so the text stays visible in v1, even
+ // though its comment framing is lost.
+ const text = typeof node.props.text === 'string' ? node.props.text : ''
+ return text ? makeParagraph(makeTextWithHardBreaks(text)) : null
+ }
+ if (DROPPED_COMPONENT_TAGS.has(node.tagName)) {
+ return null
+ }
+ if (node.tagName === 'Image') {
+ return {
+ type: NotebookNodeType.Image,
+ attrs: {
+ src: typeof node.props.src === 'string' ? node.props.src : '',
+ alt: typeof node.props.alt === 'string' ? node.props.alt : '',
+ },
+ }
+ }
+ if (node.tagName === 'UnknownNode') {
+ // The upgrade path wraps unmapped v1 nodes as `<UnknownNode nodeType="…" … />` — re-emit
+ // the original node so the downgrade restores it exactly.
+ const { nodeType, ...attrs } = node.props
+ if (typeof nodeType === 'string') {
+ return { type: nodeType, attrs }
+ }
+ }
+
+ const notebookNodeType = MARKDOWN_TAG_TO_NOTEBOOK_NODE_TYPE[node.tagName]
+ if (notebookNodeType) {
+ return { type: notebookNodeType, attrs: { ...node.props } }
+ }
+
+ // No v1 node type for this tag — keep the serialized tag source as paragraph text so the
+ // content is never silently lost.
+ return makeParagraph(makeTextWithHardBreaks(serializeNode(node)))
+}
+
+function convertListNode(node: NotebookListBlockNode): JSONContent {
+ // Inverse of `serializeList` in markdownNotebookV2.ts: items with greater depth nest into the
+ // previous shallower item's listItem as a child list.
+ const rootList = makeList(node.ordered, node.start)
+ const listStack: JSONContent[] = [rootList]
+
+ for (const item of node.items) {
+ const depth = Math.max(0, item.depth)
+ while (listStack.length - 1 > depth) {
+ listStack.pop()
+ }
+ while (listStack.length - 1 < depth) {
+ const parentItems = listStack[listStack.length - 1].content ?? []
+ const parentItem = parentItems[parentItems.length - 1]
+ if (!parentItem) {
+ // Nothing to nest under — keep the item at the current depth.
+ break
+ }
+ const nestedList = makeList(item.ordered ?? node.ordered, item.start)
+ parentItem.content = [...(parentItem.content ?? []), nestedList]
+ listStack.push(nestedList)
+ }
+ const currentList = listStack[listStack.length - 1]
+ currentList.content = [
+ ...(currentList.content ?? []),
+ { type: 'listItem', content: [makeParagraph(convertInlineNodes(item.children))] },
+ ]
+ }
+
+ return rootList
+}
+
+function makeList(ordered: boolean, start: number | undefined): JSONContent {
+ return {
+ type: ordered ? 'orderedList' : 'bulletList',
+ ...(ordered && start !== undefined && start !== 1 ? { attrs: { start } } : {}),
+ content: [],
+ }
+}
+
+function convertTableNode(node: NotebookTableBlockNode): JSONContent {
+ // `node.alignments` is dropped — v1 tables do not store column alignment.
+ const headerRow: JSONContent = {
+ type: 'tableRow',
+ content: node.headers.map((cell) => makeTableCellNode('tableHeader', cell)),
+ }
+ const bodyRows = node.rows.map(
+ (row): JSONContent => ({
+ type: 'tableRow',
+ content: row.map((cell) => makeTableCellNode('tableCell', cell)),
+ })
+ )
+
+ return { type: 'table', content: [headerRow, ...bodyRows] }
+}
+
+function makeTableCellNode(type: 'tableHeader' | 'tableCell', cell: NotebookTableCell): JSONContent {
+ return { type, content: [makeParagraph(convertInlineNodes(cell.children))] }
+}
+
+function convertCodeNode(node: NotebookCodeBlockNode): JSONContent {
+ return {
+ type: 'codeBlock',
+ attrs: { language: node.language ?? null },
+ // v1 code blocks hold plain text; one text node with embedded newlines round-trips through
+ // the upgrade path, which joins child text and hardBreaks back into the code string.
+ ...(node.text ? { content: [{ type: 'text', text: node.text }] } : {}),
+ }
+}
+
+function convertInlineNodes(nodes: NotebookInlineNode[]): JSONContent[] {
+ const content: JSONContent[] = []
+ for (const node of nodes) {
+ const converted = convertInlineNode(node)
+ const previous = content[content.length - 1]
+ if (
+ converted.type === NotebookNodeType.Mention &&
+ previous?.type === NotebookNodeType.Mention &&
+ previous.attrs?.id === converted.attrs?.id
+ ) {
+ // One labeled mention can parse into several adjacent runs (e.g. a partially bold
+ // label); they all collapse into the same atomic v1 mention.
+ continue
+ }
+ content.push(converted)
+ }
+ return content
+}
+
+function convertInlineNode(node: NotebookInlineNode): JSONContent {
+ if (node.type === 'hardBreak') {
+ return { type: 'hardBreak' }
+ }
+
+ const mentionMark = (node.marks ?? []).find(
+ (mark): mark is Extract<NotebookInlineMark, { type: 'mention' }> => mark.type === 'mention'
+ )
+ if (mentionMark) {
+ const memberId = Number(mentionMark.id)
+ if (Number.isFinite(memberId)) {
+ // v1 mentions are atomic nodes whose label is derived from the member id at render
+ // time, so the mention replaces the labeled text.
+ return { type: NotebookNodeType.Mention, attrs: { id: memberId } }
+ }
+ }
+
+ const marks = convertInlineMarks(node.marks ?? [])
+ return { type: 'text', text: node.text, ...(marks.length ? { marks } : {}) }
+}
+
+function convertInlineMarks(marks: NotebookInlineMark[]): JSONContentMark[] {
+ return marks.flatMap((mark): JSONContentMark[] => {
+ if (
+ mark.type === 'bold' ||
+ mark.type === 'italic' ||
+ mark.type === 'underline' ||
+ mark.type === 'strike' ||
+ mark.type === 'code'
+ ) {
+ return [{ type: mark.type }]
+ }
+ if (mark.type === 'link') {
+ return [{ type: 'link', attrs: { href: mark.href } }]
+ }
+ if (mark.type === 'ref') {
+ return [{ type: 'comment', attrs: { id: mark.id } }]
+ }
+ // 'mention' is handled as an atomic node in convertInlineNode; a mention with a
+ // non-numeric id degrades to its plain-text label.
+ return []
+ })
+}
+
+function makeParagraph(content: JSONContent[]): JSONContent {
+ return { type: 'paragraph', ...(content.length ? { content } : {}) }
+}
+
+function makeTextWithHardBreaks(text: string): JSONContent[] {
+ const content: JSONContent[] = []
+ text.split('\n').forEach((line, index) => {
+ if (index > 0) {
+ content.push({ type: 'hardBreak' })
+ }
+ if (line) {
+ content.push({ type: 'text', text: line })
+ }
+ })
+ return content
+}
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx
index ff3e8432fb4f..cc1f53c50afd 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx
@@ -34,11 +34,12 @@ import clsx from 'clsx'
import { BindLogic, useActions, useMountedLogic } from 'kea'
import { type CSSProperties, useCallback, useEffect, useMemo, useRef } from 'react'
-import { IconSparkles } from '@posthog/icons'
+import { IconComment, IconSparkles } from '@posthog/icons'
import { LemonInput, LemonTextArea } from '@posthog/lemon-ui'
import { createMarkdownNotebookRegistry } from 'lib/components/MarkdownNotebook'
import { wasNotebookNodeJustInserted } from 'lib/components/MarkdownNotebook/freshlyInserted'
+import { isDiscussionCommentProps } from 'lib/components/MarkdownNotebook/markdown'
import {
NotebookComponentBlockNode,
NotebookComponentDefinition,
@@ -55,6 +56,7 @@ import { notebookNodeLogic } from '../Nodes/notebookNodeLogic'
import { CreatePostHogWidgetNodeOptions, NotebookNodeAttributes, NotebookNodeType } from '../types'
import { KNOWN_NODES } from '../utils'
import { NotebookAIChat, getNotebookAIChatTitle } from './MarkdownNotebookAIChat'
+import { NotebookDiscussionComment, getNotebookDiscussionCommentTitle } from './MarkdownNotebookDiscussionComment'
import { notebookLogic } from './notebookLogic'
export const MARKDOWN_TAG_TO_NOTEBOOK_NODE_TYPE: Partial<Record<string, NotebookNodeType>> = {
@@ -169,6 +171,28 @@ export const NOTEBOOK_MARKDOWN_REGISTRY: NotebookComponentRegistry = createMarkd
hideModeActions: true,
getTitle: getNotebookAIChatTitle,
},
+ {
+ // Overrides the default registry's authorial-note definition: the note flavor
+ // (`text`, stored as `<!-- … -->`) renders through CommentBlock before the registry
+ // is consulted, so this ViewComponent only ever sees the discussion flavor
+ // (`ref` + `replies`, Google Docs-style threads anchored to a highlight).
+ tagName: 'Comment',
+ label: 'Comment',
+ category: 'Text',
+ description: 'Inline note, stored as a markdown comment',
+ aliases: ['note', 'annotation', 'todo'],
+ icon: <IconComment />,
+ defaultProps: { text: '' },
+ ViewComponent: NotebookDiscussionComment,
+ EditComponent: NotebookDiscussionComment,
+ exclusiveEditPanel: true,
+ hideModeActions: true,
+ insertCommand: {},
+ getTitle: (node: NotebookComponentBlockNode) =>
+ isDiscussionCommentProps(node.props)
+ ? getNotebookDiscussionCommentTitle(node)
+ : (getUnknownStringProp(node.props.text) ?? 'Comment'),
+ },
])
export function getMarkdownNotebookNodeTitle(
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts
index f123faabf9c0..8afde58d27d2 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts
@@ -378,6 +378,96 @@ Users activated faster.
expect(notebookContentHasCommentMarks(null)).toBe(false)
})
+ it('converts v1 comment marks to ref highlights with comment threads', () => {
+ const content: JSONContent = {
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ { type: 'text', text: 'Numbers ' },
+ { type: 'text', text: 'look off', marks: [{ type: 'comment', attrs: { id: 'mark-1' } }] },
+ { type: 'text', text: ' here' },
+ ],
+ },
+ { type: 'paragraph', content: [{ type: 'text', text: 'Unrelated' }] },
+ ],
+ }
+
+ const markdown = convertNotebookContentToMarkdown(content, {
+ commentRepliesByMarkId: {
+ 'mark-1': [{ id: 'c1', author: 'Ann', text: 'Why is this lower?', at: '2026-01-01T00:00:00Z' }],
+ },
+ })
+
+ expect(markdown).toEqual(
+ [
+ '<Comment ref="mark-1" replies={[{"id":"c1","author":"Ann","text":"Why is this lower?","at":"2026-01-01T00:00:00Z"}]} />',
+ '',
+ 'Numbers <ref id="mark-1">look off</ref> here',
+ '',
+ 'Unrelated',
+ ].join('\n')
+ )
+ expect(parseMarkdownNotebook(markdown).errors).toEqual([])
+ })
+
+ it('emits an empty comment thread when no replies are provided for a mark', () => {
+ const content: JSONContent = {
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: 'annotated', marks: [{ type: 'comment', attrs: { id: 'm1' } }] }],
+ },
+ ],
+ }
+
+ expect(convertNotebookContentToMarkdown(content)).toEqual(
+ '<Comment ref="m1" replies={[]} />\n\n<ref id="m1">annotated</ref>'
+ )
+ })
+
+ it('wraps the ref outside other formatting marks', () => {
+ const content: JSONContent = {
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ {
+ type: 'text',
+ text: 'bolded',
+ marks: [{ type: 'bold' }, { type: 'comment', attrs: { id: 'm1' } }],
+ },
+ ],
+ },
+ ],
+ }
+
+ expect(convertNotebookContentToMarkdown(content)).toContain('<ref id="m1">**bolded**</ref>')
+ })
+
+ it('converts mentions to mention tags preserving the member id', () => {
+ const content: JSONContent = {
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ { type: 'text', text: 'Ping ' },
+ { type: NotebookNodeType.Mention, attrs: { id: 5 } },
+ ],
+ },
+ ],
+ }
+
+ expect(convertNotebookContentToMarkdown(content, { getMentionLabel: () => '@Marius' })).toEqual(
+ 'Ping <mention id="5">@Marius</mention>'
+ )
+ expect(convertNotebookContentToMarkdown(content)).toEqual('Ping <mention id="5">@member</mention>')
+ })
+
it('does not duplicate an artifact markdown title', () => {
const content: NotebookArtifactContent = {
content_type: ArtifactContentType.Notebook,
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts
index 4c4e3b26e358..ab6aac70cbe4 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts
@@ -33,7 +33,7 @@ export type MarkdownNotebookV2Node = {
const MARKDOWN_NOTEBOOK_NODE_ID = 'markdown-notebook-v2'
-const NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG: Partial<Record<NotebookNodeType, string>> = {
+export const NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG: Partial<Record<NotebookNodeType, string>> = {
[NotebookNodeType.Query]: 'Query',
[NotebookNodeType.Python]: 'Python',
[NotebookNodeType.DuckSQL]: 'DuckSQL',
@@ -143,8 +143,9 @@ export function visualizationArtifactContentToNotebookArtifactContent(
}
/**
- * Whether any node in a rich (v1) notebook carries an inline comment mark. Markdown has no
- * slot for range-anchored comment marks, so the conversion drops them — callers must warn.
+ * Whether any node in a rich (v1) notebook carries an inline comment mark. The conversion
+ * preserves them as `<ref>` highlights paired with `<Comment ref>` threads — callers can
+ * use this to know whether to fetch the comment threads up front.
*/
export function notebookContentHasCommentMarks(content: JSONContent | null | undefined): boolean {
if (!content) {
@@ -156,15 +157,68 @@ export function notebookContentHasCommentMarks(content: JSONContent | null | und
return (content.content ?? []).some((child) => notebookContentHasCommentMarks(child))
}
-export function convertNotebookContentToMarkdown(content: JSONContent | null | undefined): string {
+export type NotebookMarkdownConversionOptions = {
+ /**
+ * Replies per v1 comment mark id, embedded into the matching `<Comment ref>` tag so
+ * the discussion travels with the markdown. Threads without an entry still get an
+ * empty comment thread — the anchor must never be silently dropped.
+ */
+ commentRepliesByMarkId?: Record<string, NotebookPropValue[]>
+ /** Display label for a mention (e.g. `@Marius`); falls back to `@member`. */
+ getMentionLabel?: (memberId: number) => string | null
+}
+
+export function convertNotebookContentToMarkdown(
+ content: JSONContent | null | undefined,
+ options: NotebookMarkdownConversionOptions = {}
+): string {
if (isMarkdownNotebookContent(content)) {
return getMarkdownNotebookMarkdown(content)
}
- return (content?.content ?? [])
- .map((node) => serializeRichContentNode(node))
- .filter((markdown) => markdown.trim().length > 0)
- .join('\n\n')
+ const blocks: string[] = []
+ const emittedCommentMarkIds = new Set<string>()
+ for (const node of content?.content ?? []) {
+ // Each comment-marked range gets its thread right above the block holding the
+ // highlight, so the margin-anchored thread aligns with the text it is about.
+ for (const markId of collectCommentMarkIds(node)) {
+ if (emittedCommentMarkIds.has(markId)) {
+ continue
+ }
+ emittedCommentMarkIds.add(markId)
+ blocks.push(
+ serializeNode({
+ id: '',
+ type: 'component',
+ tagName: 'Comment',
+ props: { ref: markId, replies: options.commentRepliesByMarkId?.[markId] ?? [] },
+ })
+ )
+ }
+
+ const markdown = serializeRichContentNode(node, 0, options)
+ if (markdown.trim().length > 0) {
+ blocks.push(markdown)
+ }
+ }
+
+ return blocks.join('\n\n')
+}
+
+function collectCommentMarkIds(node: JSONContent): string[] {
+ const markIds: string[] = []
+ const visit = (current: JSONContent): void => {
+ for (const mark of current.marks ?? []) {
+ if (mark.type === 'comment' && typeof mark.attrs?.id === 'string' && mark.attrs.id) {
+ markIds.push(mark.attrs.id)
+ }
+ }
+ for (const child of current.content ?? []) {
+ visit(child)
+ }
+ }
+ visit(node)
+ return markIds
}
export function getMarkdownNotebookTextContent(content: JSONContent | null | undefined): string | null {
@@ -287,19 +341,23 @@ function toNotebookPropValue(value: unknown): NotebookPropValue | null {
return isNotebookPropValue(parsedValue) ? parsedValue : null
}
-function serializeRichContentNode(node: JSONContent, listDepth = 0): string {
+function serializeRichContentNode(
+ node: JSONContent,
+ listDepth = 0,
+ options: NotebookMarkdownConversionOptions = {}
+): string {
if (node.type === 'heading') {
const level = typeof node.attrs?.level === 'number' ? Math.min(Math.max(node.attrs.level, 1), 6) : 1
- return `${'#'.repeat(level)} ${serializeInlineContent(node.content)}`
+ return `${'#'.repeat(level)} ${serializeInlineContent(node.content, options)}`
}
if (node.type === 'paragraph') {
- return escapeMarkdownBlockLines(serializeInlineContent(node.content))
+ return escapeMarkdownBlockLines(serializeInlineContent(node.content, options))
}
if (node.type === 'blockquote') {
return (node.content ?? [])
- .map((child) => serializeRichContentNode(child, listDepth))
+ .map((child) => serializeRichContentNode(child, listDepth, options))
.join('\n')
.split('\n')
.map((line) => `> ${line}`)
@@ -307,7 +365,7 @@ function serializeRichContentNode(node: JSONContent, listDepth = 0): string {
}
if (node.type === 'bulletList' || node.type === 'orderedList' || node.type === 'taskList') {
- return serializeList(node, node.type === 'orderedList', listDepth)
+ return serializeList(node, node.type === 'orderedList', listDepth, options)
}
if (node.type === 'horizontalRule') {
@@ -325,7 +383,7 @@ function serializeRichContentNode(node: JSONContent, listDepth = 0): string {
}
if (node.type === 'table') {
- return serializeTable(node)
+ return serializeTable(node, options)
}
const markdownTagName = NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG[node.type as NotebookNodeType]
@@ -339,7 +397,7 @@ function serializeRichContentNode(node: JSONContent, listDepth = 0): string {
}
const childMarkdown = (node.content ?? [])
- .map((child) => serializeRichContentNode(child, listDepth))
+ .map((child) => serializeRichContentNode(child, listDepth, options))
.filter(Boolean)
.join('\n\n')
if (childMarkdown || !node.type) {
@@ -356,11 +414,14 @@ function serializeRichContentNode(node: JSONContent, listDepth = 0): string {
})
}
-function serializeInlineContent(content: JSONContent[] | undefined): string {
- return (content ?? []).map(serializeInlineNode).join('')
+function serializeInlineContent(
+ content: JSONContent[] | undefined,
+ options: NotebookMarkdownConversionOptions = {}
+): string {
+ return (content ?? []).map((node) => serializeInlineNode(node, options)).join('')
}
-function serializeInlineNode(node: JSONContent): string {
+function serializeInlineNode(node: JSONContent, options: NotebookMarkdownConversionOptions = {}): string {
if (node.type === 'text') {
const isCodeText = (node.marks ?? []).some((mark) => mark.type === 'code')
// Literal `*`/`` ` ``/`[` in legacy text must not become formatting after the upgrade
@@ -371,12 +432,38 @@ function serializeInlineNode(node: JSONContent): string {
return '\n'
}
if (node.type === NotebookNodeType.Mention) {
- return typeof node.attrs?.label === 'string' ? escapeInlineMarkdownText(node.attrs.label) : ''
+ return serializeMentionNode(node, options)
+ }
+ return serializeInlineContent(node.content, options)
+}
+
+/** Mentions keep their member id: `<mention id="5">@Marius</mention>`. */
+function serializeMentionNode(node: JSONContent, options: NotebookMarkdownConversionOptions): string {
+ const memberId = typeof node.attrs?.id === 'number' ? node.attrs.id : null
+ const attrLabel = typeof node.attrs?.label === 'string' && node.attrs.label.trim() ? node.attrs.label.trim() : null
+ const lookedUpLabel = memberId !== null ? options.getMentionLabel?.(memberId) : null
+ const label = attrLabel ?? lookedUpLabel ?? '@member'
+ const displayLabel = label.startsWith('@') ? label : `@${label}`
+ if (memberId === null) {
+ return escapeInlineMarkdownText(displayLabel)
}
- return serializeInlineContent(node.content)
+ return `<mention id=${JSON.stringify(String(memberId))}>${escapeInlineMarkdownText(displayLabel)}</mention>`
}
function applyMarks(text: string, marks: JSONContent['marks']): string {
+ // Comment marks become `<ref>` anchors and wrap outermost, so the tag encloses the
+ // fully formatted text.
+ const commentMarkIds = (marks ?? [])
+ .filter((mark) => mark.type === 'comment' && typeof mark.attrs?.id === 'string' && mark.attrs.id)
+ .map((mark) => mark.attrs?.id as string)
+ const formattedText = applyFormattingMarks(text, marks)
+ return commentMarkIds.reduce(
+ (markedText, markId) => `<ref id=${JSON.stringify(markId)}>${markedText}</ref>`,
+ formattedText
+ )
+}
+
+function applyFormattingMarks(text: string, marks: JSONContent['marks']): string {
return (marks ?? []).reduce((markedText, mark) => {
if (mark.type === 'bold') {
return `**${markedText}**`
@@ -404,7 +491,12 @@ function applyMarks(text: string, marks: JSONContent['marks']): string {
const LIST_NODE_TYPES = new Set(['bulletList', 'orderedList', 'taskList'])
const LIST_ITEM_NODE_TYPES = new Set(['listItem', 'taskItem'])
-function serializeList(node: JSONContent, ordered: boolean, depth: number): string {
+function serializeList(
+ node: JSONContent,
+ ordered: boolean,
+ depth: number,
+ options: NotebookMarkdownConversionOptions = {}
+): string {
// The markdown notebook list model only holds one inline line per item, so block content inside a
// list item (extra paragraphs, code blocks, quotes) is emitted as standalone blocks after the item,
// splitting the list rather than dropping the content.
@@ -419,7 +511,7 @@ function serializeList(node: JSONContent, ordered: boolean, depth: number): stri
const items = (node.content ?? []).filter((child) => LIST_ITEM_NODE_TYPES.has(child.type ?? ''))
items.forEach((item, index) => {
- const { listLines, trailingBlocks } = serializeListItem(item, ordered, depth, index)
+ const { listLines, trailingBlocks } = serializeListItem(item, ordered, depth, index, options)
pendingListLines.push(...listLines)
if (trailingBlocks.length) {
flushListLines()
@@ -435,7 +527,8 @@ function serializeListItem(
item: JSONContent,
ordered: boolean,
depth: number,
- index: number
+ index: number,
+ options: NotebookMarkdownConversionOptions = {}
): { listLines: string[]; trailingBlocks: string[] } {
const marker = ordered ? `${index + 1}.` : '-'
const children = item.content ?? []
@@ -444,24 +537,27 @@ function serializeListItem(
const extraBlocks = children.filter((child) => child !== firstParagraph && !LIST_NODE_TYPES.has(child.type ?? ''))
const checkbox = item.type === 'taskItem' ? (item.attrs?.checked ? '[x] ' : '[ ] ') : ''
// List lines cannot contain raw newlines in the markdown notebook model
- const itemText = (firstParagraph ? serializeInlineContent(firstParagraph.content) : '').replace(/\s*\n\s*/g, ' ')
+ const itemText = (firstParagraph ? serializeInlineContent(firstParagraph.content, options) : '').replace(
+ /\s*\n\s*/g,
+ ' '
+ )
const listLines = [`${' '.repeat(depth)}${marker} ${checkbox}${itemText}`.trimEnd()]
for (const nestedList of nestedLists) {
- const nestedMarkdown = serializeRichContentNode(nestedList, depth + 1)
+ const nestedMarkdown = serializeRichContentNode(nestedList, depth + 1, options)
if (nestedMarkdown) {
listLines.push(nestedMarkdown)
}
}
const trailingBlocks = extraBlocks
- .map((child) => serializeRichContentNode(child))
+ .map((child) => serializeRichContentNode(child, 0, options))
.filter((block) => block.trim().length > 0)
return { listLines, trailingBlocks }
}
-function serializeTable(node: JSONContent): string {
+function serializeTable(node: JSONContent, options: NotebookMarkdownConversionOptions = {}): string {
const rows = (node.content ?? []).filter((child) => child.type === 'tableRow')
if (!rows.length) {
return ''
@@ -472,7 +568,7 @@ function serializeTable(node: JSONContent): string {
.filter((cell) => cell.type === 'tableCell' || cell.type === 'tableHeader')
.map((cell) =>
(cell.content ?? [])
- .map((child) => serializeRichContentNode(child))
+ .map((child) => serializeRichContentNode(child, 0, options))
.join(' ')
.replace(/\s*\n\s*/g, ' ')
// Plain-text pipes are already escaped inline; only escape the rest (code spans),
diff --git a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts
index b41eefb0f7eb..8328da9ada95 100644
--- a/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts
+++ b/frontend/src/scenes/notebooks/Notebook/notebookLogic.ts
@@ -314,6 +314,8 @@ export const notebookLogic = kea<notebookLogicType>([
/** Broadcast the local caret; null means the selection left the notebook. */
publishMarkdownCaret: (position: MarkdownNotebookCaretPosition | null) => ({ position }),
reportMarkdownMergeConflicts: (conflicts: NotebookCollaborationConflict[]) => ({ conflicts }),
+ showMarkdownMergeConflictDetails: (conflicts: NotebookCollaborationConflict[]) => ({ conflicts }),
+ dismissMarkdownMergeConflictDetails: true,
saveNotebook: (notebook: Pick<NotebookType, 'content' | 'title'>) => ({ notebook }),
renameNotebook: (title: string) => ({ title }),
setEditingNodeEditing: (nodeId: string, editing: boolean) => ({ nodeId, editing }),
@@ -440,6 +442,13 @@ export const notebookLogic = kea<notebookLogicType>([
dismissCollabConflict: () => null,
},
],
+ markdownMergeConflictDetails: [
+ null as NotebookCollaborationConflict[] | null,
+ {
+ showMarkdownMergeConflictDetails: (_, { conflicts }) => conflicts,
+ dismissMarkdownMergeConflictDetails: () => null,
+ },
+ ],
markdownRemotePresence: [
{} as Record<string, NotebookRemotePresenceState>,
{
@@ -1395,9 +1404,15 @@ export const notebookLogic = kea<notebookLogicType>([
})
lemonToast.warning(
conflicts.length === 1
- ? 'Someone else edited the same block as you — your version was kept.'
- : `Someone else edited ${conflicts.length} of the same blocks as you — your versions were kept.`,
- { toastId: `notebook-merge-conflict-${values.shortId}` }
+ ? "Your edit and a collaborator's edit to the same block couldn't be merged — your version is showing."
+ : `Your edits and a collaborator's edits to ${conflicts.length} blocks couldn't be merged — your versions are showing.`,
+ {
+ toastId: `notebook-merge-conflict-${values.shortId}`,
+ button: {
+ label: 'Review',
+ action: () => actions.showMarkdownMergeConflictDetails(conflicts),
+ },
+ }
)
},
insertAfterLastNode: async ({ content }) => {
diff --git a/frontend/src/scenes/notebooks/Notebook/notebookUpgradeDialog.test.tsx b/frontend/src/scenes/notebooks/Notebook/notebookUpgradeDialog.test.tsx
index 4fd478e9a963..a1a4942976f4 100644
--- a/frontend/src/scenes/notebooks/Notebook/notebookUpgradeDialog.test.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/notebookUpgradeDialog.test.tsx
@@ -4,9 +4,11 @@ import { createElement, Fragment } from 'react'
import { JSONContent } from 'lib/components/RichContentEditor/types'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+import { CommentType } from '~/types'
+
import { NotebookNodeType } from '../types'
import { getMarkdownNotebookMarkdown, isMarkdownNotebookContent } from './markdownNotebookV2'
-import { openUpgradeToMarkdownNotebookDialog } from './notebookUpgradeDialog'
+import { buildCommentRepliesByMarkId, openUpgradeToMarkdownNotebookDialog } from './notebookUpgradeDialog'
jest.mock('lib/lemon-ui/LemonDialog', () => ({
LemonDialog: {
@@ -66,4 +68,74 @@ describe('notebookUpgradeDialog', () => {
<Query query={{"kind":"InsightVizNode","source":{"kind":"TrendsQuery","series":[]}}} />`)
})
+
+ it('embeds comment threads from range-anchored comments during conversion', () => {
+ const content: JSONContent = {
+ type: 'doc',
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ { type: 'text', text: 'annotated', marks: [{ type: 'comment', attrs: { id: 'mark-1' } }] },
+ ],
+ },
+ ],
+ }
+ const comments = [
+ makeComment({ id: 'c1', content: 'Root note', item_context: { type: 'mark', id: 'mark-1' } }),
+ makeComment({ id: 'c2', content: 'A reply', source_comment: 'c1', created_at: '2026-01-02T00:00:00Z' }),
+ makeComment({ id: 'c3', content: '👍', source_comment: 'c1', item_context: { is_emoji: true } }),
+ makeComment({ id: 'c4', content: 'Unanchored', item_context: null }),
+ ]
+ const setLocalContent = jest.fn()
+
+ openUpgradeToMarkdownNotebookDialog({ content, comments, setLocalContent })
+ openDialogMock.mock.calls[0][0].primaryButton.onClick()
+
+ const markdown = getMarkdownNotebookMarkdown(setLocalContent.mock.calls[0][0])
+ expect(markdown).toContain('<ref id="mark-1">annotated</ref>')
+ expect(markdown).toContain('<Comment ref="mark-1"')
+ expect(markdown).toContain('Root note')
+ expect(markdown).toContain('A reply')
+ expect(markdown).not.toContain('👍')
+ expect(markdown).not.toContain('Unanchored')
+ })
+
+ it('groups comment threads by mark id, oldest first, skipping deleted comments', () => {
+ const replies = buildCommentRepliesByMarkId([
+ makeComment({ id: 'c1', content: 'Root', item_context: { type: 'mark', id: 'm1' } }),
+ makeComment({ id: 'c2', content: 'Newer reply', source_comment: 'c1', created_at: '2026-01-03T00:00:00Z' }),
+ makeComment({ id: 'c3', content: 'Older reply', source_comment: 'c1', created_at: '2026-01-02T00:00:00Z' }),
+ makeComment({ id: 'c4', content: 'Gone', source_comment: 'c1', deleted: true }),
+ ])
+
+ expect(replies['m1'].map((reply) => (reply as { text: string }).text)).toEqual([
+ 'Root',
+ 'Older reply',
+ 'Newer reply',
+ ])
+ })
})
+
+function makeComment(overrides: Partial<CommentType>): CommentType {
+ return {
+ id: 'comment-id',
+ content: null,
+ rich_content: null,
+ version: 0,
+ created_at: '2026-01-01T00:00:00Z',
+ created_by: {
+ id: 1,
+ uuid: 'user-uuid',
+ distinct_id: 'user-distinct-id',
+ first_name: 'Ann',
+ email: '[email protected]',
+ },
+ scope: 'Notebook',
+ item_context: null,
+ is_task: false,
+ completed_at: null,
+ completed_by: null,
+ ...overrides,
+ }
+}
diff --git a/frontend/src/scenes/notebooks/Notebook/notebookUpgradeDialog.tsx b/frontend/src/scenes/notebooks/Notebook/notebookUpgradeDialog.tsx
index 65ab66a27981..1712c26ecfc2 100644
--- a/frontend/src/scenes/notebooks/Notebook/notebookUpgradeDialog.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/notebookUpgradeDialog.tsx
@@ -1,5 +1,9 @@
+import { NotebookPropValue } from 'lib/components/MarkdownNotebook/types'
import { JSONContent } from 'lib/components/RichContentEditor/types'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+import { membersLogic } from 'scenes/organization/membersLogic'
+
+import { CommentType } from '~/types'
import {
buildMarkdownNotebookContent,
@@ -9,11 +13,68 @@ import {
type OpenUpgradeToMarkdownNotebookDialogProps = {
content: JSONContent | null | undefined
+ /** The notebook's discussion comments — inline threads are embedded into the markdown. */
+ comments?: CommentType[] | null
setLocalContent: (jsonContent: JSONContent) => void
}
+/**
+ * Groups a notebook's range-anchored comments (item_context.type === 'mark') into reply
+ * threads keyed by their v1 comment mark id, so the converter can emit a matching
+ * `<Comment ref="markId" replies={…} />` thread next to each `<ref>` highlight.
+ */
+export function buildCommentRepliesByMarkId(
+ comments: CommentType[] | null | undefined
+): Record<string, NotebookPropValue[]> {
+ const repliesByMarkId: Record<string, NotebookPropValue[]> = {}
+ const toReply = (comment: CommentType): NotebookPropValue => {
+ const author = comment.created_by?.first_name || comment.created_by?.email
+ return {
+ id: comment.id,
+ text: comment.content ?? '',
+ ...(author ? { author } : {}),
+ ...(comment.created_by ? { authorId: comment.created_by.id } : {}),
+ at: comment.created_at,
+ }
+ }
+
+ for (const comment of comments ?? []) {
+ if (
+ comment.deleted ||
+ comment.source_comment ||
+ comment.item_context?.type !== 'mark' ||
+ typeof comment.item_context?.id !== 'string'
+ ) {
+ continue
+ }
+
+ const thread = [
+ comment,
+ ...(comments ?? []).filter(
+ (candidate) =>
+ candidate.source_comment === comment.id && !candidate.deleted && !candidate.item_context?.is_emoji
+ ),
+ ].sort((left, right) => left.created_at.localeCompare(right.created_at))
+
+ repliesByMarkId[comment.item_context.id] = thread.map(toReply)
+ }
+
+ return repliesByMarkId
+}
+
+function getMentionLabel(memberId: number): string | null {
+ const member = membersLogic
+ .findMounted()
+ ?.values.meFirstMembers?.find((candidate) => candidate.user.id === memberId)
+ if (!member) {
+ return null
+ }
+ return `@${member.user.first_name || member.user.email}`
+}
+
export function openUpgradeToMarkdownNotebookDialog({
content,
+ comments,
setLocalContent,
}: OpenUpgradeToMarkdownNotebookDialogProps): void {
LemonDialog.open({
@@ -25,9 +86,8 @@ export function openUpgradeToMarkdownNotebookDialog({
editor.
</p>
{notebookContentHasCommentMarks(content) && (
- <p className="mt-2 font-semibold text-warning">
- This notebook has inline comments. Their anchors are not carried over — the comments will no
- longer point at the text they were left on.
+ <p className="mt-2">
+ Inline comments come along: each becomes a comment thread anchored to the same highlighted text.
</p>
)}
<p className="mt-2">Make sure you want to continue before converting it.</p>
@@ -36,7 +96,15 @@ export function openUpgradeToMarkdownNotebookDialog({
primaryButton: {
children: 'Convert to Markdown notebooks',
type: 'primary',
- onClick: () => setLocalContent(buildMarkdownNotebookContent(convertNotebookContentToMarkdown(content))),
+ onClick: () =>
+ setLocalContent(
+ buildMarkdownNotebookContent(
+ convertNotebookContentToMarkdown(content, {
+ commentRepliesByMarkId: buildCommentRepliesByMarkId(comments),
+ getMentionLabel,
+ })
+ )
+ ),
size: 'small',
},
secondaryButton: {