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.

fix(notebooks): stop merging own autosave echoes back into the markdown editor (#63296)

Marius Andra83d539a24e22
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
index 1512a4424d19..5083ea04f27e 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
@@ -2021,7 +2021,12 @@ Tail paragraph`
const selection = window.getSelection()
expect(activeElement.textContent).toEqual('Typed while save is pending')
expect(selection?.isCollapsed).toBe(true)
- expect(selection?.focusOffset).toEqual('Typed while save is pending'.length)
+ // Measure the caret as a text offset: the echo may leave the original element-level
+ // selection untouched instead of normalizing it to a text-node offset.
+ const caretRange = selection!.getRangeAt(0).cloneRange()
+ caretRange.selectNodeContents(activeElement)
+ caretRange.setEnd(selection!.focusNode!, selection!.focusOffset)
+ expect(caretRange.toString().length).toEqual('Typed while save is pending'.length)
})
it('keeps the caret in place when an autosave echo arrives while editing a list item', () => {
@@ -2092,6 +2097,37 @@ Tail paragraph`
expect(onChange.mock.calls.at(-1)?.[0]).toEqual(initialMarkdown)
})
+ it('does not duplicate text when a stale autosave echo arrives mid-typing', () => {
+ const onChange = jest.fn()
+ // The typed paragraph must not be the last block: the serializer trims trailing
+ // whitespace at the document end, which would hide the NBSP this scenario needs.
+ const initialMarkdown = withNotebookTitle('if i\n\nlast paragraph')
+ const { container, rerender } = render(
+ createElement(MarkdownNotebook, { value: initialMarkdown, remoteValue: initialMarkdown, onChange })
+ )
+ const bodyBlock = getBodyTextBlock(container)
+
+ // Type a trailing space — browsers put a non-breaking space in the DOM so it renders —
+ // and let the autosave of that state go in flight.
+ updateContentEditableText(bodyBlock, 'if i\u00a0')
+ const inFlightSaveMarkdown = onChange.mock.calls.at(-1)?.[0] as string
+ // The next keystroke makes the browser turn the no-longer-trailing NBSP back into a
+ // plain space, so the local text no longer contains the saved snapshot verbatim.
+ updateContentEditableText(bodyBlock, 'if i t')
+ const localMarkdown = onChange.mock.calls.at(-1)?.[0] as string
+
+ expect(inFlightSaveMarkdown).toEqual(withNotebookTitle('if i\u00a0\n\nlast paragraph'))
+ expect(localMarkdown).toEqual(withNotebookTitle('if i t\n\nlast paragraph'))
+
+ // The intermediate save echoes back as the new remote state. Everything in it is already
+ // part of the local text — merging it back in would re-apply the NBSP next to the new
+ // plain space, duplicating it ("if i\u00a0 t", rendered as a double space).
+ rerender(createElement(MarkdownNotebook, { value: localMarkdown, remoteValue: inFlightSaveMarkdown, onChange }))
+
+ expect(getBodyTextBlock(container).textContent).toEqual('if i t')
+ expect(onChange.mock.calls.at(-1)?.[0]).toEqual(localMarkdown)
+ })
+
it('keeps local edits when consecutive remote updates arrive before the save lands', () => {
const onChange = jest.fn()
const initialMarkdown = withNotebookTitle('First paragraph\n\nLast paragraph')
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
index 17eb35021577..220fb5ee421e 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
@@ -279,6 +279,10 @@ type NotebookHistoryState = {
/** Consecutive single-block edits within this window fold into one undo step. */
const UNDO_TYPING_GROUP_MS = 1000
+/** How many recent local serializations to remember for save-echo detection. Must comfortably
+ * cover the keystrokes that can land between a save being sent and its response echoing back. */
+const MAX_TRACKED_LOCAL_SNAPSHOTS = 100
+
function createDefaultAIChatId(): string {
if (typeof window !== 'undefined' && window.crypto?.randomUUID) {
return window.crypto.randomUUID()
@@ -417,6 +421,10 @@ export function MarkdownNotebook({
const notebookClipboardMarkdownRef = useRef<string | null>(null)
const historyRef = useRef<NotebookHistoryState>({ undo: [], redo: [] })
const lastSerializedValueRef = useRef(value)
+ // Recent local serializations, oldest first. A remote update matching one of these is the
+ // echo of our own save — already contained in the local state, so merging it back in would
+ // duplicate the overlapping insertions.
+ const localSnapshotsRef = useRef<string[]>([value])
// The three-way merge base: the last server state local edits were derived from.
const lastBaseValueRef = useRef(remoteValue ?? value)
const lastRemoteValueRef = useRef(remoteValue)
@@ -735,6 +743,7 @@ export function MarkdownNotebook({
// The base is intentionally left untouched: an external `value` change is a local-side
// update (artifact apply, restore), so the last synced server state remains the merge base.
lastSerializedValueRef.current = value
+ trackLocalSnapshot(value)
// oxlint-disable-next-line exhaustive-deps
}, [value])
@@ -848,6 +857,17 @@ export function MarkdownNotebook({
[captureHistorySelection]
)
+ const trackLocalSnapshot = useCallback((serialized: string): void => {
+ const snapshots = localSnapshotsRef.current
+ if (snapshots[snapshots.length - 1] === serialized) {
+ return
+ }
+ snapshots.push(serialized)
+ if (snapshots.length > MAX_TRACKED_LOCAL_SNAPSHOTS) {
+ snapshots.splice(0, snapshots.length - MAX_TRACKED_LOCAL_SNAPSHOTS)
+ }
+ }, [])
+
const commitDocument = useCallback(
(nextDocument: NotebookDocument, options: CommitDocumentOptions = {}): void => {
const editableDocument = ensureEditableNotebookDocument(nextDocument)
@@ -866,21 +886,30 @@ export function MarkdownNotebook({
})
documentRef.current = editableDocument
lastSerializedValueRef.current = serialized
+ trackLocalSnapshot(serialized)
setDebugMarkdown(serialized)
setDocument(editableDocument)
onChange?.(serialized)
},
- [onChange, pushHistoryEntry, mapRemoteCaretAnchors, logDebugEntry]
+ [onChange, pushHistoryEntry, mapRemoteCaretAnchors, logDebugEntry, trackLocalSnapshot]
)
const applyRemoteValue = useCallback(
(nextRemoteValue: string): void => {
- 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', {})
+ const snapshotIndex =
+ nextRemoteValue === lastSerializedValueRef.current
+ ? localSnapshotsRef.current.length - 1
+ : localSnapshotsRef.current.indexOf(nextRemoteValue)
+ if (snapshotIndex !== -1) {
+ // The remote state matches a recent local serialization: it's the echo of our own
+ // save, so everything in it is already contained in the local state. Merging it
+ // would re-apply insertions the local text has since built on, duplicating them —
+ // only the merge base advances. Undo history must survive autosaves too.
+ logDebugEntry('remote-echo', { behind: nextRemoteValue !== lastSerializedValueRef.current })
lastRemoteValueRef.current = nextRemoteValue
lastBaseValueRef.current = nextRemoteValue
+ // Older snapshots can't echo after a newer one: saves are acknowledged in order.
+ localSnapshotsRef.current.splice(0, snapshotIndex)
return
}
@@ -2891,6 +2920,7 @@ export function MarkdownNotebook({
documentRef.current = reconciledDocument
lastSerializedValueRef.current = serialized
+ trackLocalSnapshot(serialized)
lastBaseValueRef.current = serialized
setDebugMarkdown(nextMarkdown)
setDocument(reconciledDocument)
diff --git a/frontend/src/scenes/notebooks/Notebook/Notebook.tsx b/frontend/src/scenes/notebooks/Notebook/Notebook.tsx
index 0f26138772bd..e2a13f59c508 100644
--- a/frontend/src/scenes/notebooks/Notebook/Notebook.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/Notebook.tsx
@@ -129,7 +129,8 @@ export function Notebook({
<div
className={clsx(
'Notebook',
- !isExpanded && 'Notebook--compact',
+ // Markdown notebooks have no width toggle — they always fill the content width.
+ !isExpanded && !isMarkdownNotebook && 'Notebook--compact',
mode && `Notebook--${mode}`,
size === 'small' && `Notebook--single-column`,
isEditable && 'Notebook--editable',
diff --git a/frontend/src/scenes/notebooks/NotebookPanel/NotebookPanel.tsx b/frontend/src/scenes/notebooks/NotebookPanel/NotebookPanel.tsx
index 29ee1156117a..43fb1225a2da 100644
--- a/frontend/src/scenes/notebooks/NotebookPanel/NotebookPanel.tsx
+++ b/frontend/src/scenes/notebooks/NotebookPanel/NotebookPanel.tsx
@@ -13,6 +13,7 @@ import { urls } from 'scenes/urls'
import { SidePanelPaneHeader } from '~/layout/navigation-3000/sidepanel/components/SidePanelPaneHeader'
import { SidePanelContentContainer } from '~/layout/navigation-3000/sidepanel/SidePanelContentContainer'
+import { isMarkdownNotebookContent } from '../Notebook/markdownNotebookV2'
import { Notebook } from '../Notebook/Notebook'
import { NotebookListMini } from '../Notebook/NotebookListMini'
import { notebookLogic } from '../Notebook/notebookLogic'
@@ -25,14 +26,20 @@ import { notebookPanelLogic } from './notebookPanelLogic'
export function NotebookPanel(): JSX.Element | null {
const { selectedNotebook, initialAutofocus, droppedResource, dropProperties } = useValues(notebookPanelLogic)
const { selectNotebook, closeSidePanel } = useActions(notebookPanelLogic)
- const { notebook } = useValues(notebookLogic({ shortId: selectedNotebook, target: NotebookTarget.Popover }))
+ const { notebook, content } = useValues(
+ notebookLogic({ shortId: selectedNotebook, target: NotebookTarget.Popover })
+ )
const editable = !notebook?.is_template
const { ref, size } = useResizeBreakpoints({
0: 'small',
832: 'medium',
})
- const contentWidthHasEffect = useMemo(() => size === 'medium', [size])
+ // Markdown notebooks have no width toggle — they always fill the content width.
+ const contentWidthHasEffect = useMemo(
+ () => size === 'medium' && !isMarkdownNotebookContent(content),
+ [size, content]
+ )
return (
<div ref={ref} className={cn('NotebookPanel', 'bg-transparent')} {...dropProperties}>
diff --git a/frontend/src/scenes/notebooks/NotebookScene.tsx b/frontend/src/scenes/notebooks/NotebookScene.tsx
index c11bd7147c90..ccc18bcf4057 100644
--- a/frontend/src/scenes/notebooks/NotebookScene.tsx
+++ b/frontend/src/scenes/notebooks/NotebookScene.tsx
@@ -14,6 +14,7 @@ import { SceneExport } from 'scenes/sceneTypes'
import { SceneBreadcrumbBackButton } from '~/layout/scenes/components/SceneBreadcrumbs'
+import { isMarkdownNotebookContent } from './Notebook/markdownNotebookV2'
import { Notebook } from './Notebook/Notebook'
import { NotebookLoadingState } from './Notebook/NotebookLoadingState'
import { notebookLogic } from './Notebook/notebookLogic'
@@ -46,9 +47,10 @@ export const scene: SceneExport<NotebookSceneLogicProps> = {
export function NotebookScene(): JSX.Element {
const { notebookId, loading } = useValues(notebookSceneLogic)
const { createNotebook } = useActions(notebookSceneLogic)
- const { notebook, conflictWarningVisible, accessDeniedToNotebook } = useValues(
+ const { notebook, content, conflictWarningVisible, accessDeniedToNotebook } = useValues(
notebookLogic({ shortId: notebookId, target: NotebookTarget.Scene })
)
+ const isMarkdownNotebook = isMarkdownNotebookContent(content)
const { selectNotebook, closeSidePanel } = useActions(notebookPanelLogic)
const { selectedNotebook, visibility } = useValues(notebookPanelLogic)
@@ -149,7 +151,8 @@ export function NotebookScene(): JSX.Element {
</LemonButton>
<NotebookTableOfContentsButton type="secondary" size="small" />
<NotebookKernelInfoButton type="secondary" size="small" />
- <NotebookExpandButton type="secondary" size="small" inPanel={false} />
+ {/* Markdown notebooks have no width toggle — they always fill the content width. */}
+ {!isMarkdownNotebook && <NotebookExpandButton type="secondary" size="small" inPanel={false} />}
<LemonButton
type="secondary"
size="small"