:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(notebooks): some more markdown polish (#65196)
Marius Andra5c419a82aaff
diff --git a/frontend/src/lib/components/MarkdownNotebook/EditablePromptComponent.tsx b/frontend/src/lib/components/MarkdownNotebook/EditablePromptComponent.tsxindex ff237fdc2426..3abeea60a7c8 100644--- a/frontend/src/lib/components/MarkdownNotebook/EditablePromptComponent.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/EditablePromptComponent.tsx@@ -16,6 +16,7 @@ export function EditablePromptComponent({deleteNodeAndFocusAdjacent,updateAIPromptQuery,submitAIPrompt,+ isAIPromptSubmitDisabled,isActive,focusRequest,restoreSelectionRef,@@ -27,6 +28,7 @@ export function EditablePromptComponent({deleteNodeAndFocusAdjacent: () => voidupdateAIPromptQuery: (query: string) => voidsubmitAIPrompt: (queryOverride?: string) => boolean+ isAIPromptSubmitDisabled: booleanisActive: booleanfocusRequest?: numberrestoreSelectionRef: MutableRefObject<RestoreSelectionRequest | null>@@ -36,6 +38,11 @@ export function EditablePromptComponent({const [isCollapsed, setIsCollapsed] = useState(false)const question = getNotebookStringProp(node.props.question) ?? ''const isEmpty = question.length === 0+ const submitDisabledReason = question.trim()+ ? isAIPromptSubmitDisabled+ ? 'AI is already running'+ : undefined+ : 'Write a prompt first'const setElementRef = useCallback((element: HTMLTextAreaElement | null): void => {@@ -100,6 +107,9 @@ export function EditablePromptComponent({}const submitPrompt = (query: string = question): void => {+ if (isAIPromptSubmitDisabled) {+ return+ }submitAIPrompt(query)}@@ -194,7 +204,8 @@ export function EditablePromptComponent({tooltip="Send prompt"aria-label="Send prompt"onClick={() => submitPrompt()}- disabledReason={question.trim() ? undefined : 'Write a prompt first'}+ disabled={!!submitDisabledReason || mode !== 'edit'}+ disabledReason={submitDisabledReason}/></div>)}diff --git a/frontend/src/lib/components/MarkdownNotebook/EditableTextBlock.tsx b/frontend/src/lib/components/MarkdownNotebook/EditableTextBlock.tsxindex 70a5d9102749..f03abfca08cc 100644--- a/frontend/src/lib/components/MarkdownNotebook/EditableTextBlock.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/EditableTextBlock.tsx@@ -5,11 +5,9 @@ import {KeyboardEvent,MutableRefObject,useCallback,- useEffect,useLayoutEffect,useMemo,useRef,- useState,} from 'react'import { IconX } from '@posthog/icons'@@ -43,8 +41,7 @@ import { htmlElementToInlineNodes, inlineNodesToHtml, makeEmptyParagraph, parseMimport { NotebookBlockNode, NotebookInlineNode, NotebookMode, NotebookTextBlockNode } from './types'import { getInlineText, normalizeInlineNodes } from './utils'-const AI_THINKING_FRAMES = ['Thinking.', 'Thinking..', 'Thinking...'] as const-const AI_THINKING_FRAME_MS = 450+const AI_THINKING_LABEL = 'Thinking...'export function EditableTextBlock({node,@@ -69,6 +66,7 @@ export function EditableTextBlock({isInsertMenuOpen,insertMenuMode,hasInvalidInsertMenuQuery,+ isAIWriting,isAIWritingPlaceholder,submitInsertMenuSelection,handleSelectionChange,@@ -98,6 +96,7 @@ export function EditableTextBlock({isInsertMenuOpen: booleaninsertMenuMode: InsertMenuState['mode'] | nullhasInvalidInsertMenuQuery: boolean+ isAIWriting: booleanisAIWritingPlaceholder: booleansubmitInsertMenuSelection: (queryOverride?: string) => booleanhandleSelectionChange: () => void@@ -110,8 +109,7 @@ export function EditableTextBlock({const renderedHtml = useMemo(() => inlineNodesToHtml(node.children), [node.children])const text = getInlineText(node.children)const isEmpty = text.length === 0- const [aiThinkingFrameIndex, setAIThinkingFrameIndex] = useState(0)- const aiThinkingLabel = isAIWritingPlaceholder ? AI_THINKING_FRAMES[aiThinkingFrameIndex] : undefined+ const aiThinkingLabel = isAIWritingPlaceholder ? AI_THINKING_LABEL : undefinedconst isToolInsertMenuOpen = isInsertMenuOpen && (!insertMenuMode || insertMenuMode === 'tools')const TextTag =node.type === 'heading' ? (`h${node.level ?? 1}` as const) : node.type === 'blockquote' ? 'blockquote' : 'p'@@ -124,19 +122,6 @@ export function EditableTextBlock({[setBlockRef])- useEffect(() => {- if (!isAIWritingPlaceholder) {- return- }-- setAIThinkingFrameIndex(0)- const interval = window.setInterval(() => {- setAIThinkingFrameIndex((currentFrame) => (currentFrame + 1) % AI_THINKING_FRAMES.length)- }, AI_THINKING_FRAME_MS)-- return () => window.clearInterval(interval)- }, [isAIWritingPlaceholder])-useLayoutEffect(() => {const element = elementRef.currentif (!element) {@@ -330,6 +315,11 @@ export function EditableTextBlock({}const handleInput = (event: FormEvent<HTMLElement>): void => {+ if (isAIWriting) {+ event.currentTarget.innerHTML = renderedHtml+ return+ }+const element = event.currentTargetconst elementChildren = htmlElementToInlineNodes(element)const elementText = getInlineText(elementChildren)@@ -362,6 +352,11 @@ export function EditableTextBlock({}const handlePaste = (event: ReactClipboardEvent<HTMLElement>): void => {+ if (isAIWriting) {+ event.preventDefault()+ return+ }+const plainText = event.clipboardData.getData('text/plain')const html = event.clipboardData.getData('text/html')const linkPasteResult = getInlineLinkPasteResult(event.currentTarget, node.id, node.children, plainText)@@ -403,6 +398,19 @@ export function EditableTextBlock({}const handleKeyDown = (event: KeyboardEvent<HTMLElement>): void => {+ if (isAIWriting) {+ if (+ event.key.length === 1 ||+ event.key === 'Backspace' ||+ event.key === 'Delete' ||+ event.key === 'Enter'+ ) {+ event.preventDefault()+ event.stopPropagation()+ }+ return+ }+if (isToolInsertMenuOpen && (event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'a') {event.preventDefault()event.stopPropagation()@@ -548,6 +556,13 @@ export function EditableTextBlock({}const selection = getCollapsedSelectionRange(event.currentTarget, node.id)+ if (isTitleBlock && event.key === 'Backspace' && selection?.start === 0 && selection.end === 0) {+ event.preventDefault()+ event.stopPropagation()+ restoreSelectionRef.current = { nodeId: node.id, start: 0, end: 0 }+ return+ }+if (isEmpty && !isTitleBlock && node.type === 'paragraph' && event.key === 'Backspace') {event.preventDefault()if (!deleteNodeAndFocusPrevious(node.id)) {@@ -658,13 +673,15 @@ export function EditableTextBlock({`MarkdownNotebook__text-block--${node.type}`,isTitleBlock && 'MarkdownNotebook__text-block--title',isToolInsertMenuOpen && 'MarkdownNotebook__text-block--insert-placeholder',+ isAIWriting && 'MarkdownNotebook__text-block--ai-writing',isAIWritingPlaceholder && 'MarkdownNotebook__text-block--ai-thinking',hasInvalidInsertMenuQuery && 'MarkdownNotebook__text-block--invalid-insert-filter')}data-markdown-notebook-node-id={node.id}data-ai-thinking-label={aiThinkingLabel}- contentEditable={mode === 'edit'}+ contentEditable={mode === 'edit' && !isAIWriting}suppressContentEditableWarning+ aria-busy={isAIWriting || undefined}data-placeholder={isEmpty ? placeholder : undefined}onInput={handleInput}onPaste={handlePaste}diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scssindex 59a0124eb34e..69583aaf106d 100644--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss@@ -88,6 +88,8 @@position: absolute;bottom: 100%;left: -2px; // aligned with the bar's left edge+ display: inline-flex;+ align-items: baseline;max-width: 12rem;padding: 1px 6px;overflow: hidden;@@ -101,6 +103,31 @@background: var(--remote-presence-color, currentColor);border-radius: 3px 3px 3px 0;}++ &-name {+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ }++ &-ai-dots {+ display: inline-flex;+ flex: 0 0 0.75em;+ margin-left: 1px;++ span {+ opacity: 0;+ animation: MarkdownNotebook__AICaretDots 1.2s steps(1, end) infinite;++ &:nth-child(2) {+ animation-delay: 0.2s;+ }++ &:nth-child(3) {+ animation-delay: 0.4s;+ }+ }+ }}.MarkdownNotebook__remote-block {@@ -127,6 +154,8 @@position: absolute;bottom: 100%;left: -2px;+ display: inline-flex;+ align-items: baseline;max-width: 12rem;padding: 1px 6px;overflow: hidden;@@ -147,6 +176,25 @@opacity: 0;}+@keyframes MarkdownNotebook__AICaretDots {+ 0%,+ 24% {+ opacity: 0;+ }++ 25%,+ 100% {+ opacity: 1;+ }+}++@media (prefers-reduced-motion: reduce) {+ .MarkdownNotebook__remote-caret-ai-dots span {+ opacity: 1;+ animation: none;+ }+}+.MarkdownNotebook__debug-toolbar {position: absolute;@@ -763,6 +811,20 @@background: var(--bg-light);}+.MarkdownNotebook__text-block--ai-writing,+.MarkdownNotebook__row--ai-writing .MarkdownNotebook__code-block,+.MarkdownNotebook__row--ai-writing .MarkdownNotebook__list-block,+.MarkdownNotebook__row--ai-writing .MarkdownNotebook__table-block {+ background: color-mix(in sRGB, var(--color-bg-fill-button-tertiary-hover) 72%, transparent);+ border-radius: 0.25rem;+ box-shadow: 0 0 0 0.25rem color-mix(in sRGB, var(--color-bg-fill-button-tertiary-hover) 36%, transparent);+ animation: MarkdownNotebook__AIWritingPulse 1.8s ease-in-out infinite;+}++.MarkdownNotebook__text-block--ai-writing {+ cursor: default;+}+.MarkdownNotebook__text-block--ai-thinking {position: relative;color: transparent;@@ -782,6 +844,26 @@color: var(--color-text-primary);}+@keyframes MarkdownNotebook__AIWritingPulse {+ 0%,+ 100% {+ background-color: color-mix(in sRGB, var(--color-bg-fill-button-tertiary-hover) 54%, transparent);+ }++ 50% {+ background-color: color-mix(in sRGB, var(--color-bg-fill-button-tertiary-hover) 88%, transparent);+ }+}++@media (prefers-reduced-motion: reduce) {+ .MarkdownNotebook__text-block--ai-writing,+ .MarkdownNotebook__row--ai-writing .MarkdownNotebook__code-block,+ .MarkdownNotebook__row--ai-writing .MarkdownNotebook__list-block,+ .MarkdownNotebook__row--ai-writing .MarkdownNotebook__table-block {+ animation: none;+ }+}+.MarkdownNotebook__text-block[contenteditable='true'] a,.MarkdownNotebook__list-block[contenteditable='true'] .MarkdownNotebook__list-item-content a,.MarkdownNotebook__table-cell-content[contenteditable='true'] a {diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.tsindex b5db2d7f0c3a..11fe5d932243 100644--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts@@ -1171,6 +1171,41 @@ Last paragraph`)expect(onChange).toHaveBeenLastCalledWith(`# New title\n\nNotebookTitle`)})+ it('keeps a standalone heading marker as body text with an empty title', () => {+ const { container } = render(createElement(MarkdownNotebook, { value: '#' }))++ const textBlocks = getEditableTextBlocks(container)+ expect(textBlocks.map((block) => block.tagName)).toEqual(['H1', 'P'])+ expect(textBlocks.map((block) => block.textContent)).toEqual(['', '#'])+ })++ it('prevents Backspace at the start of the notebook title from editing the canvas background', () => {+ const onChange = jest.fn()+ const { container } = render(createElement(MarkdownNotebook, { value: '# Title', onChange }))+ const title = container.querySelector('h1.MarkdownNotebook__text-block') as HTMLElement++ placeCaretInElement(title)++ expect(fireEvent.keyDown(title, { key: 'Backspace' })).toEqual(false)+ expect(getEditableTextBlocks(container).map((block) => block.textContent)).toEqual(['Title'])+ expect(document.activeElement).toEqual(title)+ expect(onChange).not.toHaveBeenCalled()+ })++ it('prevents native deleteContentBackward at the start of the notebook title', () => {+ const onChange = jest.fn()+ const { container } = render(createElement(MarkdownNotebook, { value: '# Title', onChange }))+ const canvas = container.querySelector('.MarkdownNotebook__canvas') as HTMLElement+ const title = container.querySelector('h1.MarkdownNotebook__text-block') as HTMLElement++ placeCaretInElement(title)+ const event = beforeInputInContentEditable(canvas, 'deleteContentBackward')++ expect(event.defaultPrevented).toBe(true)+ expect(getEditableTextBlocks(container).map((block) => block.textContent)).toEqual(['Title'])+ expect(onChange).not.toHaveBeenCalled()+ })+it('merges the notebook title split back together when backspacing after Enter', () => {const onChange = jest.fn()const { container } = render(@@ -1445,7 +1480,7 @@ Repeated block`),fireEvent.keyDown(editableTextBlock, { key: 'z', metaKey: true })- expect(onChange).toHaveBeenLastCalledWith('#')+ expect(onChange).toHaveBeenLastCalledWith('')expect(editableTextBlock.textContent).toEqual('')fireEvent.keyDown(editableTextBlock, { key: 'z', metaKey: true, shiftKey: true })@@ -1691,7 +1726,7 @@ Tail paragraph`)expect(getEditableTextBlocks(container).map((block) => block.textContent)).toEqual([''])expect(container.querySelector('.MarkdownNotebook__code-block')).toBeNull()expect(container.querySelector('.MarkdownNotebook__component-shell')).toBeNull()- expect(onChange).toHaveBeenLastCalledWith('#')+ expect(onChange).toHaveBeenLastCalledWith('')fireUndoShortcut(getEditableTextBlocks(container)[0])@@ -1709,7 +1744,7 @@ Tail paragraph`)expect(getEditableTextBlocks(container).map((block) => block.textContent)).toEqual([''])expect(container.querySelector('.MarkdownNotebook__code-block')).toBeNull()expect(container.querySelector('.MarkdownNotebook__component-shell')).toBeNull()- expect(onChange).toHaveBeenLastCalledWith('#')+ expect(onChange).toHaveBeenLastCalledWith('')})it('undoes and redoes deleting a partial selection around a component node', () => {@@ -3317,7 +3352,7 @@ ${queryMarkdown}`)expect(aiRequest.query).toContain('Full-notebook artifact content must not include the prompt')})- it('disables Ask AI in the insert menu while an AI request is active', () => {+ it('opens Ask AI prompts while an AI request is active but blocks submission', () => {const onAskAI = jest.fn()const onChange = jest.fn()const { container } = render(@@ -3335,19 +3370,26 @@ ${queryMarkdown}`)const askAIButton = container.querySelector('.MarkdownNotebook__insert-item') as HTMLButtonElementexpect(askAIButton.textContent).toEqual('Ask AI')- expect(askAIButton.disabled).toBe(true)+ expect(askAIButton.disabled).toBe(false)expect(askAIButton.getAttribute('aria-selected')).toEqual('true')fireEvent.click(askAIButton)- fireEvent.keyDown(getBodyTextBlock(container), { key: 'Enter' })+ expect(container.querySelector('.MarkdownNotebook__ai-prompt-tag')?.textContent).toEqual('Ask AI:')+ expect(onChange).toHaveBeenLastCalledWith(`${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\n<Prompt question="" />`)++ const promptInput = getAIPromptInput(container)+ updateAIPromptInput(promptInput, 'Summarize this')+ const changeCount = onChange.mock.calls.length++ fireEvent.keyDown(promptInput, { key: 'Enter' })+ fireEvent.click(container.querySelector('button[aria-label="Send prompt"]') as HTMLButtonElement)expect(onAskAI).not.toHaveBeenCalled()- expect(onChange).toHaveBeenLastCalledWith(`${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\n `)- expect(container.querySelector('.MarkdownNotebook__ai-prompt-tag')).toBeNull()- expect(container.querySelector('.MarkdownNotebook__insert-menu')).toBeInstanceOf(HTMLElement)+ expect(onChange).toHaveBeenCalledTimes(changeCount)+ expect(container.querySelector('.MarkdownNotebook__ai-prompt-tag')).toBeInstanceOf(HTMLElement)})- it('disables Ask AI in the insert menu while an Ask AI prompt is already open', () => {+ it('opens another Ask AI prompt while one is already open', () => {const onAskAI = jest.fn()const onChange = jest.fn()const { container } = render(@@ -3364,48 +3406,96 @@ ${queryMarkdown}`)const askAIButton = container.querySelector('.MarkdownNotebook__insert-item') as HTMLButtonElementexpect(askAIButton.textContent).toEqual('Ask AI')- expect(askAIButton.disabled).toBe(true)- const changeCount = onChange.mock.calls.length+ expect(askAIButton.disabled).toBe(false)fireEvent.click(askAIButton)- fireEvent.keyDown(getBodyTextBlock(container), { key: 'Enter' })expect(onAskAI).not.toHaveBeenCalled()- expect(onChange).toHaveBeenCalledTimes(changeCount)- expect(container.querySelectorAll('.MarkdownNotebook__ai-prompt-tag')).toHaveLength(1)- expect(container.querySelector('.MarkdownNotebook__insert-menu')).toBeInstanceOf(HTMLElement)+ expect(onChange).toHaveBeenLastCalledWith(+ `${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\n<Prompt question="" />\n\n<Prompt question="" />`+ )+ expect(container.querySelectorAll('.MarkdownNotebook__ai-prompt-tag')).toHaveLength(2)})- it('animates the live AI thinking placeholder without editing markdown', () => {- jest.useFakeTimers()+ it('marks only the active AI writing block as pending and read-only', () => {const onChange = jest.fn()+ const { container } = render(+ createElement(MarkdownNotebook, {+ value: withNotebookTitle(`Editable AI paragraph- try {- const { container, unmount } = render(- createElement(MarkdownNotebook, {- value: withNotebookTitle('Thinking...'),- onChange,- })- )- const thinkingBlock = getBodyTextBlock(container)+Current AI paragraph`),+ onChange,+ aiWritingNodeIndexes: [2],+ })+ )+ const aiBlocks = Array.from(container.querySelectorAll('p.MarkdownNotebook__text-block')) as HTMLElement[]+ const previousAIBlock = aiBlocks[0]+ const activeAIBlock = aiBlocks[1]- expect(thinkingBlock.textContent).toEqual('Thinking...')- expect(thinkingBlock.classList.contains('MarkdownNotebook__text-block--ai-thinking')).toBe(true)- expect(thinkingBlock.getAttribute('data-ai-thinking-label')).toEqual('Thinking.')+ expect(aiBlocks).toHaveLength(2)- act(() => jest.advanceTimersByTime(450))- expect(thinkingBlock.getAttribute('data-ai-thinking-label')).toEqual('Thinking..')+ expect(previousAIBlock.getAttribute('contenteditable')).toEqual('true')+ expect(previousAIBlock.classList.contains('MarkdownNotebook__text-block--ai-writing')).toBe(false)+ expect(activeAIBlock.getAttribute('contenteditable')).toEqual('false')+ expect(activeAIBlock.classList.contains('MarkdownNotebook__text-block--ai-writing')).toBe(true)+ expect(activeAIBlock.getAttribute('aria-busy')).toEqual('true')- act(() => jest.advanceTimersByTime(450))- expect(thinkingBlock.getAttribute('data-ai-thinking-label')).toEqual('Thinking...')+ updateContentEditableText(previousAIBlock, 'Human edited AI paragraph')+ expect(onChange).toHaveBeenLastCalledWith(+ `${TEST_NOTEBOOK_TITLE_MARKDOWN}\n\nHuman edited AI paragraph\n\nCurrent AI paragraph`+ )- act(() => jest.advanceTimersByTime(450))- expect(thinkingBlock.getAttribute('data-ai-thinking-label')).toEqual('Thinking.')- expect(onChange).not.toHaveBeenCalled()- unmount()- } finally {- jest.useRealTimers()- }+ onChange.mockClear()+ updateContentEditableText(activeAIBlock, 'Human should not edit current AI paragraph')+ expect(activeAIBlock.textContent).toEqual('Current AI paragraph')+ expect(onChange).not.toHaveBeenCalled()+ })++ it('does not delete the active AI writing block from a multi-block selection', () => {+ const onChange = jest.fn()+ const { container } = render(+ createElement(MarkdownNotebook, {+ value: withNotebookTitle(`Editable AI paragraph++Current AI paragraph`),+ onChange,+ aiWritingNodeIndexes: [2],+ })+ )+ const aiBlocks = Array.from(container.querySelectorAll('p.MarkdownNotebook__text-block')) as HTMLElement[]+ const previousAIBlock = aiBlocks[0]+ const activeAIBlock = aiBlocks[1]++ expect(aiBlocks).toHaveLength(2)++ selectTextAcrossNodes(+ getFirstTextNode(previousAIBlock),+ 0,+ getFirstTextNode(activeAIBlock),+ 'Current AI paragraph'.length+ )+ fireEvent.keyDown(previousAIBlock, { key: 'Backspace' })++ expect(+ Array.from(container.querySelectorAll('p.MarkdownNotebook__text-block')).map((block) => block.textContent)+ ).toEqual(['Editable AI paragraph', 'Current AI paragraph'])+ expect(onChange).not.toHaveBeenCalled()+ })++ it('renders the live AI thinking placeholder without editing markdown', () => {+ const onChange = jest.fn()+ const { container } = render(+ createElement(MarkdownNotebook, {+ value: withNotebookTitle('Thinking...'),+ onChange,+ })+ )+ const thinkingBlock = getBodyTextBlock(container)++ expect(thinkingBlock.textContent).toEqual('Thinking...')+ expect(thinkingBlock.classList.contains('MarkdownNotebook__text-block--ai-thinking')).toBe(true)+ expect(thinkingBlock.getAttribute('data-ai-thinking-label')).toEqual('Thinking...')+ expect(onChange).not.toHaveBeenCalled()})it('selects the Ask AI prompt text with Cmd+A on the first press', () => {@@ -5090,7 +5180,7 @@ First paragraphexpect(aiRequest.markdownWithResponse).toContain('</ref> paragraph\n\nThinking...')})- it('disables selection Ask AI when an Ask AI prompt is already open', () => {+ it('opens a selection Ask AI prompt when another Ask AI prompt is already open', () => {const onAskAI = jest.fn()const onChange = jest.fn()const { container } = render(@@ -5105,13 +5195,12 @@ First paragraphselectTextNode(getFirstTextNode(textBlock), 0, 'First'.length, true)const askAIButton = container.querySelector('button[aria-label="Ask AI"]') as HTMLButtonElement- const changeCount = onChange.mock.calls.lengthfireEvent.click(askAIButton)expect(onAskAI).not.toHaveBeenCalled()- expect(onChange).toHaveBeenCalledTimes(changeCount)- expect(container.querySelectorAll('.MarkdownNotebook__ai-prompt-tag')).toHaveLength(1)+ expect(onChange).toHaveBeenLastCalledWith(expect.stringContaining(`<Prompt question="" source="selection"`))+ expect(container.querySelectorAll('.MarkdownNotebook__ai-prompt-tag')).toHaveLength(2)})it('adds a link from the formatting toolbar', () => {@@ -5399,7 +5488,7 @@ After paragraph`),expect(nextTextBlocks.map((block) => block.textContent)).toEqual([''])expect(document.activeElement).toEqual(nextTextBlocks[0])expect(window.getSelection()?.focusOffset).toEqual(0)- expect(onChange).toHaveBeenLastCalledWith('#')+ expect(onChange).toHaveBeenLastCalledWith('')})it('merges a text row into the previous text row with Backspace and supports undo', () => {diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsxindex cf8a7555dc07..0432892ebfb8 100644--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx@@ -41,7 +41,6 @@ import {import {MarkdownNotebookTextSurface,areNotebookDocumentsEqual,- collapseAdjacentEmptyPromptNodes,ensureEditableNotebookDocument,getAskAIInlineNotebookQuery,getAskAISelectionQuery,@@ -238,6 +237,7 @@ export type MarkdownNotebookProps = {onCaretChange?: (position: MarkdownNotebookCaretPosition | null) => voidinitialInsertMenu?: { nodeIndex?: number; query?: string }focusAIPromptRequest?: number+ aiWritingNodeIndexes?: number[]placeholder?: stringclassName?: stringautoFocus?: boolean@@ -394,7 +394,7 @@ export function MarkdownNotebook({value,onChange,onAskAI,- isAskAIDisabled = false,+ isAskAIDisabled: isAIPromptSubmitDisabled = false,createAIConversationId = createDefaultAIConversationId,mode = 'edit',registry,@@ -408,6 +408,7 @@ export function MarkdownNotebook({onCaretChange,initialInsertMenu,focusAIPromptRequest,+ aiWritingNodeIndexes,placeholder = 'Start writing...',className,autoFocus = false,@@ -499,6 +500,7 @@ export function MarkdownNotebook({}, [])const hasDiscussionComments = useMemo(() => document.nodes.some(isDiscussionCommentNode), [document])+ const aiWritingNodeIndexSet = useMemo(() => new Set(aiWritingNodeIndexes ?? []), [aiWritingNodeIndexes])useLayoutEffect(() => {const element = mainRef.current@@ -1183,6 +1185,10 @@ export function MarkdownNotebook({return false}+ if (selectedEntries.some((entry) => aiWritingNodeIndexSet.has(entry.index))) {+ return true+ }+const requestFocusForDeletedSelection = (nextNodes: NotebookBlockNode[],selectionStartIndex: number@@ -1340,7 +1346,7 @@ export function MarkdownNotebook({})return true},- [commitDocument]+ [aiWritingNodeIndexSet, commitDocument])const splitTextBlockAtCurrentSelection = useCallback((): boolean => {@@ -1982,6 +1988,11 @@ export function MarkdownNotebook({return true}+ if (direction === 'backward' && selectionStart === 0 && nodeIndex === 0) {+ restoreSelectionRef.current = { nodeId: node.id, start: 0, end: 0 }+ return true+ }+if (direction === 'forward' || selectionStart !== 0 || nodeIndex <= 0) {return false}@@ -2374,10 +2385,6 @@ export function MarkdownNotebook({nodeId: string,options?: { source?: 'slash' | 'selection'; selectedMarkdown?: string; selectedRefId?: string }): void => {- if (isAskAIDisabled || documentRef.current.nodes.some(isPromptComponentNode)) {- return- }-onInteractionStateChange?.(true)const currentDocument = documentRef.currentconst nodes = currentDocument.nodes.length ? currentDocument.nodes : [emptyNodeRef.current]@@ -2410,7 +2417,7 @@ export function MarkdownNotebook({if (didUpdate) {commitDocument({...currentDocument,- nodes: collapseAdjacentEmptyPromptNodes(nextNodes, nodeId),+ nodes: nextNodes,})} else {commitDocument({@@ -2428,7 +2435,7 @@ export function MarkdownNotebook({selectedRefId: options?.selectedRefId,})},- [commitDocument, isAskAIDisabled, onInteractionStateChange]+ [commitDocument, onInteractionStateChange])const updateAIPromptQuery = (nodeId: string, query: string): void => {@@ -2442,7 +2449,6 @@ export function MarkdownNotebook({const renderedNodes = getRenderedNodes()const aiWritingPlaceholderNodeIds = useMemo(() => getAIWritingPlaceholderNodeIds(document.nodes), [document.nodes])- const isAskAIInsertionDisabled = isAskAIDisabled || document.nodes.some(isPromptComponentNode)const focusAIPromptNodeId = useMemo(() => (focusAIPromptRequest === undefined ? null : getLatestEmptyAIPromptNodeId(document.nodes)),[document.nodes, focusAIPromptRequest]@@ -2470,7 +2476,7 @@ export function MarkdownNotebook({restoreSelectionRef.current = { nodeId, start: 0, end: 0 }},onAskAI ? openAIPrompt : undefined,- isAskAIInsertionDisabled,+ false,extraInsertCommands ? extraInsertCommands(insertMenuApi) : []),[@@ -2479,7 +2485,6 @@ export function MarkdownNotebook({replaceNode,onAskAI,openAIPrompt,- isAskAIInsertionDisabled,extraInsertCommands,insertMenuApi,]@@ -3274,7 +3279,7 @@ export function MarkdownNotebook({}const askAIAboutSelection = (): void => {- if (!floatingToolbar || !onAskAI || isAskAIInsertionDisabled) {+ if (!floatingToolbar || !onAskAI) {return}@@ -3355,7 +3360,7 @@ export function MarkdownNotebook({}commitDocument({...currentDocument,- nodes: collapseAdjacentEmptyPromptNodes(nextNodes, promptNode.id),+ nodes: nextNodes,})floatingToolbarPositionLockRef.current = null@@ -4705,6 +4710,10 @@ export function MarkdownNotebook({}const submitAIPromptForNode = (nodeId: string, queryOverride?: string): boolean => {+ if (isAIPromptSubmitDisabled) {+ return false+ }+const activeAIPromptMenu = insertMenu?.nodeId === nodeId && insertMenu.mode === 'ai' ? insertMenu : nullconst currentDocument = documentRef.currentconst nodes = currentDocument.nodes.length ? currentDocument.nodes : [emptyNodeRef.current]@@ -5041,6 +5050,8 @@ export function MarkdownNotebook({const renderNotebookRow = (node: NotebookBlockNode, index: number): JSX.Element => {const isTitleRow = index === 0+ const isAIWritingNode = aiWritingNodeIndexSet.has(index)+ const nodeMode = isAIWritingNode ? 'view' : modeconst isInsertMenuOpen = insertMenu?.nodeId === node.idconst insertMenuMode = isInsertMenuOpen ? (insertMenu.mode ?? 'tools') : nullconst isToolInsertMenuOpen = isInsertMenuOpen && insertMenuMode === 'tools'@@ -5063,7 +5074,7 @@ export function MarkdownNotebook({insertMenu.query.length > 0 &&getFilteredInsertCommands(insertCommands, insertMenu.query).length === 0- const isDraggableRow = mode === 'edit' && !isTitleRow && !isDiscussionCommentNode(node)+ const isDraggableRow = mode === 'edit' && !isTitleRow && !isDiscussionCommentNode(node) && !isAIWritingNodereturn (<div@@ -5071,6 +5082,7 @@ export function MarkdownNotebook({'MarkdownNotebook__row',isInsertMenuOpen && 'MarkdownNotebook__row--insert-menu-open',isAIPromptOpen && 'MarkdownNotebook__row--ai-prompt',+ isAIWritingNode && 'MarkdownNotebook__row--ai-writing',isDiscussionCommentNode(node) && 'MarkdownNotebook__row--margin-comment',draggingNodeId === node.id && 'MarkdownNotebook__row--dragging')}@@ -5128,7 +5140,7 @@ export function MarkdownNotebook({{renderNode({node,nodeIndex: index,- mode,+ mode: nodeMode,placeholder: isTitleRow? NOTEBOOK_TITLE_PLACEHOLDER: isToolInsertMenuOpen@@ -5220,16 +5232,18 @@ export function MarkdownNotebook({setActiveRowIndex(index)setActiveBoundaryIndex(null)},- showInlineInsertMenuButton: mode === 'edit' && shouldShowInlineInsertMenuButton,+ showInlineInsertMenuButton: mode === 'edit' && !isAIWritingNode && shouldShowInlineInsertMenuButton,isInlineInsertMenuButtonVisible: activeRowIndex === index || isToolInsertMenuOpen || isAIPromptOpen,isInsertMenuOpen,insertMenuMode,hasInvalidInsertMenuQuery,+ isAIWriting: isAIWritingNode,isAIWritingPlaceholder: aiWritingPlaceholderNodeIds.has(node.id),aiPromptFocusRequest:focusAIPromptNodeId === node.id && focusAIPromptRequest !== undefined? focusAIPromptRequest: undefined,+ isAIPromptSubmitDisabled,submitInsertMenuSelection: (queryOverride) =>submitInsertMenuSelectionForNode(node.id, queryOverride),submitAIPrompt: (queryOverride) => submitAIPromptForNode(node.id, queryOverride),@@ -5397,7 +5411,7 @@ export function MarkdownNotebook({setBlockStyle={setSelectedBlockStyle}copySelection={copyFloatingToolbarSelection}askAIAboutSelection={onAskAI ? askAIAboutSelection : undefined}- isAskAIDisabled={isAskAIInsertionDisabled}+ isAskAIDisabled={false}startInlineCommentAtSelection={canStartInlineCommentAtSelection() ? startInlineCommentAtSelection : undefined}diff --git a/frontend/src/lib/components/MarkdownNotebook/documentModel.ts b/frontend/src/lib/components/MarkdownNotebook/documentModel.tsindex 994359a381df..c9be42b2b927 100644--- a/frontend/src/lib/components/MarkdownNotebook/documentModel.ts+++ b/frontend/src/lib/components/MarkdownNotebook/documentModel.ts@@ -554,7 +554,13 @@ export function ensureEditableNotebookDocument(document: NotebookDocument): NotedidChange = true}- const firstNode = nodes[0]+ let firstNode = nodes[0]++ if (firstNode && isStandaloneHeadingMarkerParagraph(firstNode)) {+ nodes.unshift(makeEmptyNotebookTitle('notebook-title'))+ firstNode = nodes[0]+ didChange = true+ }if (isTextBlockNode(firstNode)) {if (firstNode.type !== 'heading' || firstNode.level !== 1) {@@ -578,6 +584,10 @@ export function ensureEditableNotebookDocument(document: NotebookDocument): Notereturn didChange ? { ...document, nodes: uniqueNodes } : document}+function isStandaloneHeadingMarkerParagraph(node: NotebookBlockNode): boolean {+ return node.type === 'paragraph' && /^#{1,6}$/.test(getInlineText(node.children).trim())+}+export function makeEmptyNotebookTitle(idSeed: string): NotebookTextBlockNode {return {...makeEmptyParagraph(idSeed),diff --git a/frontend/src/lib/components/MarkdownNotebook/markdown.ts b/frontend/src/lib/components/MarkdownNotebook/markdown.tsindex 6c2e795a79b4..4d3ba0779c9c 100644--- a/frontend/src/lib/components/MarkdownNotebook/markdown.ts+++ b/frontend/src/lib/components/MarkdownNotebook/markdown.ts@@ -143,6 +143,10 @@ export function parseMarkdownNotebook(markdown: string | null | undefined): Note}export function serializeMarkdownNotebook(document: NotebookDocument): string {+ if (document.nodes.length === 1 && isEmptyNotebookTitleNode(document.nodes[0])) {+ return ''+ }+const shouldPreserveEmptyParagraphs = document.nodes.length > 1const serialized = document.nodes.map((node) => serializeDocumentNode(node, shouldPreserveEmptyParagraphs))@@ -155,6 +159,10 @@ export function serializeMarkdownNotebook(document: NotebookDocument): string {return shouldPreserveTrailingEmptyParagraph ? serialized : serialized.trimEnd()}+function isEmptyNotebookTitleNode(node: NotebookBlockNode | undefined): boolean {+ return !!node && node.type === 'heading' && node.level === 1 && serializeInlineNodes(node.children) === ''+}+export function serializeNode(node: NotebookBlockNode): string {if (node.type === 'heading') {const [firstLine, ...followingLines] = serializeInlineNodes(node.children).split('\n')diff --git a/frontend/src/lib/components/MarkdownNotebook/notebookAI.test.ts b/frontend/src/lib/components/MarkdownNotebook/notebookAI.test.tsindex 113610343cbe..4aa42b6bfe5c 100644--- a/frontend/src/lib/components/MarkdownNotebook/notebookAI.test.ts+++ b/frontend/src/lib/components/MarkdownNotebook/notebookAI.test.ts@@ -1,4 +1,9 @@-import { insertNotebookAIFollowUpPromptAfterResponse, replaceNotebookAIResponseMarkdown } from './notebookAI'+import {+ insertNotebookAIFollowUpPromptAfterResponse,+ rebaseNotebookAIResponseRange,+ replaceNotebookAIResponseMarkdown,+ streamNotebookAIResponseMarkdown,+} from './notebookAI'function replaceMarkdown(markdown: string,@@ -101,6 +106,78 @@ describe('notebookAI', () => {})})+ it('preserves edited previous AI blocks while streaming the active tail block', () => {+ const result = streamNotebookAIResponseMarkdown(+ '# Notebook\n\nHuman edited first paragraph\n\nSecond paragraph still writing',+ 2,+ 'First paragraph\n\nSecond paragraph finished\n\nThird paragraph still writing',+ 2+ )++ expect(result).toEqual({+ markdown:+ '# Notebook\n\nHuman edited first paragraph\n\nSecond paragraph finished\n\nThird paragraph still writing',+ responseNodeIndex: 3,+ responseNodeCount: 3,+ })+ })++ it('continues streaming when an earlier generated AI block was deleted', () => {+ const result = streamNotebookAIResponseMarkdown(+ '# Notebook\n\nSecond paragraph\n\nThird paragraph still writing',+ 3,+ 'First paragraph\n\nSecond paragraph\n\nThird paragraph finished\n\nFourth paragraph still writing',+ 3+ )++ expect(result).toEqual({+ markdown: '# Notebook\n\nSecond paragraph\n\nThird paragraph finished\n\nFourth paragraph still writing',+ responseNodeIndex: 3,+ responseNodeCount: 3,+ })+ })++ it('continues streaming when a middle generated AI block was deleted', () => {+ const result = streamNotebookAIResponseMarkdown(+ '# Notebook\n\nFirst paragraph\n\nThird paragraph still writing',+ 3,+ 'First paragraph\n\nSecond paragraph\n\nThird paragraph finished\n\nFourth paragraph still writing',+ 3+ )++ expect(result).toEqual({+ markdown: '# Notebook\n\nFirst paragraph\n\nThird paragraph finished\n\nFourth paragraph still writing',+ responseNodeIndex: 3,+ responseNodeCount: 3,+ })+ })++ it('rebases the streamed AI response range after deleting an earlier generated block', () => {+ expect(+ rebaseNotebookAIResponseRange(+ '# Notebook\n\nFirst paragraph\n\nSecond paragraph\n\nThird paragraph still writing',+ '# Notebook\n\nSecond paragraph\n\nThird paragraph still writing',+ 3,+ 3+ )+ ).toEqual({ responseNodeIndex: 2, responseNodeCount: 2 })+ })++ it('replaces the active streamed block when the AI has only written one block so far', () => {+ const result = streamNotebookAIResponseMarkdown(+ '# Notebook\n\nFirst paragraph still writing',+ 1,+ 'First paragraph finished\n\nSecond paragraph still writing',+ 1+ )++ expect(result).toEqual({+ markdown: '# Notebook\n\nFirst paragraph finished\n\nSecond paragraph still writing',+ responseNodeIndex: 2,+ responseNodeCount: 2,+ })+ })+it('normalizes saved insight tags from AI output before insertion', () => {const markdown = '# Notebook\n\nThinking...'@@ -131,10 +208,12 @@ describe('notebookAI', () => {)})- it('does not insert duplicate empty follow-up prompts', () => {+ it('inserts another empty follow-up prompt when one is already open', () => {const markdown = '# Notebook\n\n<Prompt question="" />\n\nAnswer text'- expect(insertNotebookAIFollowUpPromptAfterResponse(markdown, 2, '<Prompt question="" />')).toEqual(markdown)+ expect(insertNotebookAIFollowUpPromptAfterResponse(markdown, 2, '<Prompt question="" />')).toEqual(+ '# Notebook\n\n<Prompt question="" />\n\nAnswer text\n\n<Prompt question="" />'+ )})it('keeps the AI response anchored on the final list item before a follow-up prompt', () => {diff --git a/frontend/src/lib/components/MarkdownNotebook/notebookAI.ts b/frontend/src/lib/components/MarkdownNotebook/notebookAI.tsindex 3db9938e6f6e..9a90cce9a205 100644--- a/frontend/src/lib/components/MarkdownNotebook/notebookAI.ts+++ b/frontend/src/lib/components/MarkdownNotebook/notebookAI.ts@@ -1,15 +1,23 @@import { parseMarkdownNotebook, serializeMarkdownNotebook } from './markdown'-import type { NotebookBlockNode, NotebookComponentBlockNode, NotebookPropValue } from './types'+import type { NotebookBlockNode } from './types'import { getNodeFingerprint, getNodeSignature, getNodeText } from './utils'export const NOTEBOOK_AI_WRITING_PLACEHOLDER = 'Thinking...'-const NOTEBOOK_PROMPT_COMPONENT_TAG = 'Prompt'export type NotebookAIResponseMarkdownResult = {markdown: stringresponseNodeIndex: number}+export type NotebookAIStreamResponseMarkdownResult = NotebookAIResponseMarkdownResult & {+ responseNodeCount: number+}++export type NotebookAIResponseRange = {+ responseNodeIndex: number+ responseNodeCount: number+}+export function replaceNotebookAIResponseMarkdown(markdown: string,responseNodeIndex: number,@@ -19,6 +27,56 @@ export function replaceNotebookAIResponseMarkdown(return applyNotebookAIResponseMarkdown(markdown, responseNodeIndex, replacementMarkdown, replacedNodeCount)}+export function streamNotebookAIResponseMarkdown(+ markdown: string,+ responseNodeIndex: number,+ replacementMarkdown: string,+ replacedNodeCount: number = 1+): NotebookAIStreamResponseMarkdownResult {+ return applyNotebookAIStreamResponseMarkdown(markdown, responseNodeIndex, replacementMarkdown, replacedNodeCount)+}++export function rebaseNotebookAIResponseRange(+ previousMarkdown: string,+ nextMarkdown: string,+ responseNodeIndex: number,+ responseNodeCount: number+): NotebookAIResponseRange {+ const previousDocument = parseMarkdownNotebook(previousMarkdown)+ const nextDocument = parseMarkdownNotebook(nextMarkdown)+ if (!nextDocument.nodes.length) {+ return { responseNodeIndex: 0, responseNodeCount: 1 }+ }++ const previousRange = getNotebookAIResponseReplaceRange(responseNodeIndex, responseNodeCount)+ const previousStartIndex = Math.min(previousRange.insertionIndex, previousDocument.nodes.length)+ const previousEndIndex = Math.min(+ previousDocument.nodes.length,+ previousRange.insertionIndex + previousRange.deleteCount+ )+ const nextStartIndex = getRebasedNotebookAIResponseStartIndex(+ previousDocument.nodes,+ nextDocument.nodes,+ previousStartIndex+ )+ const nextEndIndex = getRebasedNotebookAIResponseEndIndex(+ previousDocument.nodes,+ nextDocument.nodes,+ previousEndIndex,+ nextStartIndex+ )++ if (nextEndIndex <= nextStartIndex) {+ const fallbackIndex = Math.max(0, Math.min(nextStartIndex, nextDocument.nodes.length - 1))+ return { responseNodeIndex: fallbackIndex, responseNodeCount: 1 }+ }++ return {+ responseNodeIndex: nextEndIndex - 1,+ responseNodeCount: nextEndIndex - nextStartIndex,+ }+}+export function insertNotebookAIFollowUpPromptAfterResponse(markdown: string,responseNodeIndex: number,@@ -38,9 +96,6 @@ export function insertNotebookAIFollowUpPromptAfterResponse(if (!promptNodes.length) {return markdown}- if (promptNodes.some(isEmptyNotebookPromptNode) && document.nodes.some(isEmptyNotebookPromptNode)) {- return markdown- }const insertionIndex = responseNodeIndex + 1const nextNodes = [@@ -55,24 +110,6 @@ export function insertNotebookAIFollowUpPromptAfterResponse(})}-function isEmptyNotebookPromptNode(node: NotebookBlockNode): node is NotebookComponentBlockNode {- return (- node.type === 'component' &&- node.tagName === NOTEBOOK_PROMPT_COMPONENT_TAG &&- isEmptyNotebookStringProp(node.props.question) &&- isEmptyNotebookStringProp(node.props.selectedMarkdown) &&- isEmptyNotebookStringProp(node.props.ref)- )-}--function isEmptyNotebookStringProp(value: NotebookPropValue | undefined): boolean {- if (typeof value === 'string') {- return !value.trim()- }-- return value === undefined-}-function applyNotebookAIResponseMarkdown(markdown: string,responseNodeIndex: number,@@ -120,6 +157,191 @@ function applyNotebookAIResponseMarkdown(}}+function applyNotebookAIStreamResponseMarkdown(+ markdown: string,+ responseNodeIndex: number,+ insertedMarkdown: string,+ replacedNodeCount: number = 1+): NotebookAIStreamResponseMarkdownResult {+ const trimmedInsertedMarkdown = normalizeNotebookAIInsertedMarkdown(insertedMarkdown).trim()+ if (!trimmedInsertedMarkdown) {+ return { markdown, responseNodeIndex, responseNodeCount: Math.max(1, replacedNodeCount) }+ }++ const document = parseMarkdownNotebook(markdown)+ if (responseNodeIndex < 0 || !document.nodes.length) {+ return { markdown, responseNodeIndex, responseNodeCount: Math.max(1, replacedNodeCount) }+ }++ const parsedReplacementNodes = parseMarkdownNotebook(trimmedInsertedMarkdown).nodes+ if (!parsedReplacementNodes.length) {+ return { markdown, responseNodeIndex, responseNodeCount: Math.max(1, replacedNodeCount) }+ }++ const currentResponseNodeIndex = Math.min(responseNodeIndex, document.nodes.length - 1)+ const replacementNodes = stripEchoedNotebookContextBeforeAIResponse(+ document.nodes,+ currentResponseNodeIndex,+ parsedReplacementNodes+ )+ if (!replacementNodes.length) {+ return { markdown, responseNodeIndex, responseNodeCount: Math.max(1, replacedNodeCount) }+ }++ const targetRange = getNotebookAIResponseCurrentReplaceRange(+ document.nodes.length,+ responseNodeIndex,+ replacedNodeCount+ )+ const { insertionIndex, deleteCount } = targetRange+ const currentResponseNodes = document.nodes.slice(insertionIndex, insertionIndex + deleteCount)+ if (!currentResponseNodes.length) {+ return { markdown, responseNodeIndex, responseNodeCount: Math.max(1, replacedNodeCount) }+ }++ const preservedNodes = currentResponseNodes.slice(0, -1)+ const activeNode = currentResponseNodes[currentResponseNodes.length - 1]+ const nextReplacementSearchIndex = getNextReplacementSearchIndexForPreservedNodes(preservedNodes, replacementNodes)+ const activeReplacementIndex = getMatchingReplacementNodeIndex(+ activeNode,+ replacementNodes,+ nextReplacementSearchIndex+ )+ const replacementTailStartIndex = activeReplacementIndex ?? nextReplacementSearchIndex+ const replacementTailNodes = replacementNodes.slice(replacementTailStartIndex)+ if (!replacementTailNodes.length) {+ return { markdown, responseNodeIndex, responseNodeCount: Math.max(1, deleteCount) }+ }++ const nextNodes = [+ ...document.nodes.slice(0, insertionIndex),+ ...preservedNodes,+ ...replacementTailNodes,+ ...document.nodes.slice(insertionIndex + deleteCount),+ ]+ const responseNodeCount = preservedNodes.length + replacementTailNodes.length+ const nextResponseNodeIndex = insertionIndex + responseNodeCount - 1++ return {+ markdown: serializeMarkdownNotebook({+ ...document,+ nodes: nextNodes,+ }),+ responseNodeIndex: nextResponseNodeIndex,+ responseNodeCount,+ }+}++function getRebasedNotebookAIResponseStartIndex(+ previousNodes: NotebookBlockNode[],+ nextNodes: NotebookBlockNode[],+ previousStartIndex: number+): number {+ for (let previousIndex = previousStartIndex - 1; previousIndex >= 0; previousIndex--) {+ const nextIndex = getMatchingNodeFingerprintIndex(previousNodes[previousIndex], nextNodes, 0)+ if (nextIndex !== null) {+ return nextIndex + 1+ }+ }++ return Math.min(previousStartIndex, nextNodes.length)+}++function getRebasedNotebookAIResponseEndIndex(+ previousNodes: NotebookBlockNode[],+ nextNodes: NotebookBlockNode[],+ previousEndIndex: number,+ nextStartIndex: number+): number {+ for (let previousIndex = previousEndIndex; previousIndex < previousNodes.length; previousIndex++) {+ const nextIndex = getMatchingNodeFingerprintIndex(previousNodes[previousIndex], nextNodes, nextStartIndex)+ if (nextIndex !== null) {+ return nextIndex+ }+ }++ return nextNodes.length+}++function getMatchingNodeFingerprintIndex(+ node: NotebookBlockNode,+ candidateNodes: NotebookBlockNode[],+ startIndex: number+): number | null {+ const nodeFingerprint = getNodeFingerprint(node)+ for (let index = Math.max(0, startIndex); index < candidateNodes.length; index++) {+ if (getNodeFingerprint(candidateNodes[index]) === nodeFingerprint) {+ return index+ }+ }++ return null+}++function getNextReplacementSearchIndexForPreservedNodes(+ currentNodes: NotebookBlockNode[],+ replacementNodes: NotebookBlockNode[]+): number {+ let replacementSearchIndex = 0+ for (const currentNode of currentNodes) {+ const matchingIndex = getMatchingReplacementNodeIndex(currentNode, replacementNodes, replacementSearchIndex)+ replacementSearchIndex =+ matchingIndex !== null+ ? matchingIndex + 1+ : Math.min(replacementSearchIndex + 1, Math.max(0, replacementNodes.length - 1))+ }++ return replacementSearchIndex+}++function getMatchingReplacementNodeIndex(+ currentNode: NotebookBlockNode,+ replacementNodes: NotebookBlockNode[],+ startIndex: number+): number | null {+ for (let index = Math.max(0, startIndex); index < replacementNodes.length; index++) {+ if (nodesLikelyRepresentSameAIResponseBlock(currentNode, replacementNodes[index])) {+ return index+ }+ }++ return null+}++function nodesLikelyRepresentSameAIResponseBlock(+ currentNode: NotebookBlockNode,+ replacementNode: NotebookBlockNode+): boolean {+ if (getNodeFingerprint(currentNode) === getNodeFingerprint(replacementNode)) {+ return true+ }+ if (getNodeSignature(currentNode) !== getNodeSignature(replacementNode) || currentNode.type === 'component') {+ return false+ }++ const currentText = normalizeNotebookContextText(getNodeText(currentNode)).trim()+ const replacementText = normalizeNotebookContextText(getNodeText(replacementNode)).trim()+ const commonPrefixLength = getCommonPrefixLength(currentText, replacementText)+ return (+ currentText.length >= 4 &&+ replacementText.length >= 4 &&+ (currentText.startsWith(replacementText) ||+ replacementText.startsWith(currentText) ||+ (commonPrefixLength >= 8 && commonPrefixLength >= Math.min(currentText.length, replacementText.length) / 2))+ )+}++function getCommonPrefixLength(leftText: string, rightText: string): number {+ const maxLength = Math.min(leftText.length, rightText.length)+ for (let index = 0; index < maxLength; index++) {+ if (leftText[index] !== rightText[index]) {+ return index+ }+ }++ return maxLength+}+function normalizeNotebookAIInsertedMarkdown(markdown: string): string {return markdown.replace(@@ -277,3 +499,15 @@ function getNotebookAIResponseReplaceRange(return { insertionIndex, deleteCount: deleteEndExclusive - insertionIndex }}++function getNotebookAIResponseCurrentReplaceRange(+ nodeCount: number,+ responseNodeIndex: number,+ replacedNodeCount: number+): { insertionIndex: number; deleteCount: number } {+ const requestedRange = getNotebookAIResponseReplaceRange(responseNodeIndex, replacedNodeCount)+ const deleteEndExclusive = Math.min(nodeCount, responseNodeIndex + 1)+ const insertionIndex = Math.min(requestedRange.insertionIndex, deleteEndExclusive)++ return { insertionIndex, deleteCount: deleteEndExclusive - insertionIndex }+}diff --git a/frontend/src/lib/components/MarkdownNotebook/remoteCarets.test.ts b/frontend/src/lib/components/MarkdownNotebook/remoteCarets.test.tsindex 8555dc34c216..74304eecb0ae 100644--- a/frontend/src/lib/components/MarkdownNotebook/remoteCarets.test.ts+++ b/frontend/src/lib/components/MarkdownNotebook/remoteCarets.test.ts@@ -1,14 +1,35 @@+import { render, waitFor } from '@testing-library/react'+import { createElement } from 'react'+import { getListItemRefKey } from './listModel'import { parseMarkdownNotebook } from './markdown'import { reconcileNotebookDocuments } from './reconcile'import {getFocusedBlockCaretPosition,mapRemoteCaretPositionThroughDocumentChange,+ RemoteCaretOverlay,resolveRemoteCaretLayout,} from './remoteCarets'import { NotebookBlockNode, NotebookDocument } from './types'describe('remoteCarets', () => {+ const originalResizeObserver = global.ResizeObserver++ class ResizeObserverMock {+ observe(): void {}+ disconnect(): void {}+ }++ beforeEach(() => {+ ;(global as typeof globalThis & { ResizeObserver: typeof ResizeObserver | undefined }).ResizeObserver =+ ResizeObserverMock as unknown as typeof ResizeObserver+ })++ afterEach(() => {+ ;(global as typeof globalThis & { ResizeObserver: typeof ResizeObserver | undefined }).ResizeObserver =+ originalResizeObserver+ })+const paragraph = (id: string, text: string): NotebookBlockNode => ({id,type: 'paragraph',@@ -106,6 +127,35 @@ describe('remoteCarets', () => {expect(layout).toMatchObject({ top: 300, left: 16, width: 100, height: 20 })})+ it('renders AI thinking dots after the remote caret label', async () => {+ const nodes = [paragraph('p1', 'hello')]+ const element = makeElement('hello', { top: 20, left: 12 })+ const containerElement = makeElement('', { top: 0, left: 0 })+ const { container: renderedContainer } = render(+ createElement(RemoteCaretOverlay, {+ carets: [+ {+ clientId: 'notebook-agent:ai',+ userName: 'AI',+ color: 'green',+ position: { nodeIndex: 0 },+ isAI: true,+ isAIThinking: true,+ },+ ],+ nodes,+ blockRefs: { current: { p1: element } },+ listItemRefs: { current: {} },+ containerRef: { current: containerElement },+ })+ )++ await waitFor(() =>+ expect(renderedContainer.querySelectorAll('.MarkdownNotebook__remote-caret-ai-dots span')).toHaveLength(3)+ )+ expect(renderedContainer.querySelector('.MarkdownNotebook__remote-caret-flag')?.textContent).toEqual('AI...')+ })+describe('mapRemoteCaretPositionThroughDocumentChange', () => {function evolve(markdown: string, nextMarkdown: string): [NotebookDocument, NotebookDocument] {const previousDocument = parseMarkdownNotebook(markdown)diff --git a/frontend/src/lib/components/MarkdownNotebook/remoteCarets.tsx b/frontend/src/lib/components/MarkdownNotebook/remoteCarets.tsxindex 9d0ed4fa4a56..a6652231c347 100644--- a/frontend/src/lib/components/MarkdownNotebook/remoteCarets.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/remoteCarets.tsx@@ -37,6 +37,8 @@ export type RemoteNotebookCaret = {position: MarkdownNotebookCaretPosition/** Notebook version the position was computed against, when known. */version?: number+ isAI?: boolean+ isAIThinking?: booleanisFading?: boolean}@@ -272,6 +274,19 @@ export function RemoteCaretOverlay({if (!layout) {return null}+ const caretFlag = (+ <span className="MarkdownNotebook__remote-caret-flag">+ <span className="MarkdownNotebook__remote-caret-name">{caret.userName}</span>+ {caret.isAI && caret.isAIThinking ? (+ <span className="MarkdownNotebook__remote-caret-ai-dots">+ <span>.</span>+ <span>.</span>+ <span>.</span>+ </span>+ ) : null}+ </span>+ )+if (layout.width !== undefined) {// Block-level presence: the user is on a component/table, not at a text offset.const style = {@@ -286,7 +301,7 @@ export function RemoteCaretOverlay({: 'MarkdownNotebook__remote-block'return (<div key={caret.clientId} className={className} style={style}>- <span className="MarkdownNotebook__remote-caret-flag">{caret.userName}</span>+ {caretFlag}</div>)}@@ -301,7 +316,7 @@ export function RemoteCaretOverlay({: 'MarkdownNotebook__remote-caret'return (<div key={caret.clientId} className={className} style={style}>- <span className="MarkdownNotebook__remote-caret-flag">{caret.userName}</span>+ {caretFlag}</div>)})}diff --git a/frontend/src/lib/components/MarkdownNotebook/renderNode.tsx b/frontend/src/lib/components/MarkdownNotebook/renderNode.tsxindex d6b52f6640de..1efcf2f98cb5 100644--- a/frontend/src/lib/components/MarkdownNotebook/renderNode.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/renderNode.tsx@@ -61,7 +61,9 @@ export function renderNode({isInsertMenuOpen,insertMenuMode,hasInvalidInsertMenuQuery,+ isAIWriting,isAIWritingPlaceholder,+ isAIPromptSubmitDisabled,aiPromptFocusRequest,submitInsertMenuSelection,submitAIPrompt,@@ -106,7 +108,9 @@ export function renderNode({isInsertMenuOpen: booleaninsertMenuMode: InsertMenuState['mode'] | nullhasInvalidInsertMenuQuery: boolean+ isAIWriting: booleanisAIWritingPlaceholder: boolean+ isAIPromptSubmitDisabled: booleanaiPromptFocusRequest?: numbersubmitInsertMenuSelection: (queryOverride?: string) => booleansubmitAIPrompt: (queryOverride?: string) => boolean@@ -159,6 +163,7 @@ export function renderNode({deleteNodeAndFocusAdjacent={deleteNodeAndFocusAdjacent}updateAIPromptQuery={updateAIPromptQuery}submitAIPrompt={submitAIPrompt}+ isAIPromptSubmitDisabled={isAIPromptSubmitDisabled}isActive={isInsertMenuOpen && insertMenuMode === 'ai'}focusRequest={aiPromptFocusRequest}restoreSelectionRef={restoreSelectionRef}@@ -256,6 +261,7 @@ export function renderNode({isInsertMenuOpen={isInsertMenuOpen}insertMenuMode={insertMenuMode}hasInvalidInsertMenuQuery={hasInvalidInsertMenuQuery}+ isAIWriting={isAIWriting}isAIWritingPlaceholder={isAIWritingPlaceholder}submitInsertMenuSelection={submitInsertMenuSelection}handleSelectionChange={handleSelectionChange}diff --git a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsxindex 9ed44ceb807e..a86b49a91a9e 100644--- a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx+++ b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx@@ -11,7 +11,9 @@ import type {} from 'lib/components/MarkdownNotebook'import {insertNotebookAIFollowUpPromptAfterResponse,+ rebaseNotebookAIResponseRange,replaceNotebookAIResponseMarkdown,+ streamNotebookAIResponseMarkdown,} from 'lib/components/MarkdownNotebook/notebookAI'import type { MarkdownNotebookCaretPosition, RemoteNotebookCaret } from 'lib/components/MarkdownNotebook/remoteCarets'import type { NotebookBlockNode } from 'lib/components/MarkdownNotebook/types'@@ -65,6 +67,7 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNotconst [inlineAIRequests, setInlineAIRequests] = useState<InlineNotebookAIRequest[]>([])const [aiCaretPosition, setAICaretPosition] = useState<MarkdownNotebookCaretPosition | null>(null)const [aiCaretFading, setAICaretFading] = useState(false)+ const [aiCaretThinking, setAICaretThinking] = useState(false)const markdownEditorValueRef = useRef(markdownEditorValue)const inlineAIResponseNodeCountsRef = useRef<Record<string, number>>({})const inlineAIResponseNodeIndicesRef = useRef<Record<string, number>>({})@@ -114,6 +117,25 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNot[handleMarkdownEditorChange])+ const handleMarkdownNotebookChange = useCallback(+ (markdown: string): void => {+ const previousMarkdown = markdownEditorValueRef.current+ for (const request of inlineAIRequests) {+ const currentRange = rebaseNotebookAIResponseRange(+ previousMarkdown,+ markdown,+ getInlineAIResponseNodeIndex(request, inlineAIResponseNodeIndicesRef.current),+ inlineAIResponseNodeCountsRef.current[request.conversationId] ?? 1+ )+ inlineAIResponseNodeIndicesRef.current[request.conversationId] = currentRange.responseNodeIndex+ inlineAIResponseNodeCountsRef.current[request.conversationId] = currentRange.responseNodeCount+ }+ markdownEditorValueRef.current = markdown+ handleMarkdownEditorChange(markdown)+ },+ [handleMarkdownEditorChange, inlineAIRequests]+ )+const clearAIPresenceDepartureTimeout = useCallback((): void => {if (aiPresenceDepartureTimeoutRef.current !== null) {window.clearTimeout(aiPresenceDepartureTimeoutRef.current)@@ -146,6 +168,7 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNotsetAICaretPosition(null)setAICaretFading(false)+ setAICaretThinking(false)setMarkdownAIPresenceActive(false)},[setMarkdownAIPresenceActive]@@ -182,6 +205,7 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNotaiPresenceActivityVersionRef.current += 1clearAIPresenceTimeouts()setAICaretFading(false)+ setAICaretThinking(true)setMarkdownAIPresenceActive(true)},[clearAIPresenceTimeouts, setMarkdownAIPresenceActive]@@ -199,6 +223,7 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNotaiPresenceRetainedByPromptRef.current = trueclearAIPresenceTimeouts()setAICaretFading(false)+ setAICaretThinking(false)setAICaretPosition(promptCaretPosition)setMarkdownAIPresenceActive(true)}, [clearAIPresenceTimeouts, setMarkdownAIPresenceActive])@@ -206,6 +231,9 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNotconst markAIPresenceInactive = useCallback((conversationId: string): void => {activeInlineAIRequestIdsRef.current.delete(conversationId)+ if (activeInlineAIRequestIdsRef.current.size === 0) {+ setAICaretThinking(false)+ }scheduleAIPresenceDeparture()},[scheduleAIPresenceDeparture]@@ -230,6 +258,7 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNotaiPresenceRetainedByPromptRef.current = trueclearAIPresenceTimeouts()setAICaretFading(false)+ setAICaretThinking(false)setAICaretPosition(promptCaretPosition)setMarkdownAIPresenceActive(true)return@@ -253,11 +282,13 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNotcolor: NOTEBOOK_AI_PRESENCE_COLOR,position: aiCaretPosition,version: notebook?.version,+ isAI: true,+ isAIThinking: aiCaretThinking,isFading: aiCaretFading,},]: [],- [aiCaretFading, aiCaretPosition, notebook?.version]+ [aiCaretFading, aiCaretPosition, aiCaretThinking, notebook?.version])const remoteCarets = useMemo<RemoteNotebookCaret[]>(() => [...markdownRemoteCarets, ...aiCarets],@@ -422,17 +453,17 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNotconst replacedNodeCount = inlineAIResponseNodeCountsRef.current[request.conversationId] ?? 1updateMarkdownEditorValue((currentMarkdown) => {- const result = replaceNotebookAIResponseMarkdown(+ const result = streamNotebookAIResponseMarkdown(currentMarkdown,getInlineAIResponseNodeIndex(request, inlineAIResponseNodeIndicesRef.current),message.content,replacedNodeCount)inlineAIResponseNodeIndicesRef.current[request.conversationId] = result.responseNodeIndex+ inlineAIResponseNodeCountsRef.current[request.conversationId] = result.responseNodeCountsetAICaretPosition(getNotebookAICaretPosition(result.markdown, result.responseNodeIndex))return result.markdown})- inlineAIResponseNodeCountsRef.current[request.conversationId] = getMarkdownBlockCount(message.content)},[updateMarkdownEditorValue])@@ -503,6 +534,14 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNot[markAIPresenceInactive, updateMarkdownEditorValue])+ const aiWritingNodeIndexes = useMemo(+ () =>+ inlineAIRequests.map((request) =>+ getInlineAIResponseNodeIndex(request, inlineAIResponseNodeIndicesRef.current)+ ),+ [inlineAIRequests, markdownEditorValue]+ )+return (<MarkdownNotebookRuntimeContext.Provider value={runtimeContext}><MarkdownNotebook@@ -512,7 +551,7 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNotmode={isEditable ? 'edit' : 'view'}registry={NOTEBOOK_MARKDOWN_REGISTRY}extraInsertCommands={isEditable ? buildSavedInsightInsertCommands : undefined}- onChange={isEditable ? handleMarkdownEditorChange : undefined}+ onChange={isEditable ? handleMarkdownNotebookChange : undefined}onConflict={reportMarkdownMergeConflicts}remoteCarets={remoteCarets}onCaretChange={isEditable ? publishMarkdownCaret : undefined}@@ -528,6 +567,7 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNotdebugOpen={isDebugOpen}onDebugOpenChange={handleDebugOpenChange}focusAIPromptRequest={focusAIPromptRequest}+ aiWritingNodeIndexes={aiWritingNodeIndexes}/>{inlineAIRequests.map((request) => (<InlineNotebookAIRunner