Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

fix: keep markdown preview in sync on local edits (#8832)

Péter Gyarmati3580d129b406
diff --git a/frontend/src/core/codemirror/cells/__tests__/extensions.test.ts b/frontend/src/core/codemirror/cells/__tests__/extensions.test.ts
new file mode 100644
index 0000000000..2668102c5a
--- /dev/null
+++ b/frontend/src/core/codemirror/cells/__tests__/extensions.test.ts
@@ -0,0 +1,114 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+// @vitest-environment jsdom
+
+import {
+ EditorState,
+ Transaction,
+ type TransactionSpec,
+} from "@codemirror/state";
+import { describe, expect, it } from "vitest";
+import { formattingChangeEffect } from "../../format";
+import { loroSyncAnnotation } from "../../rtc/loro/sync";
+import { exportedForTesting } from "../extensions";
+
+const { shouldAutorunMarkdownUpdate } = exportedForTesting;
+
+function createTransaction(spec: TransactionSpec) {
+ return EditorState.create({ doc: "" }).update(spec);
+}
+
+describe("shouldAutorunMarkdownUpdate", () => {
+ it.each([
+ "input.type",
+ "delete.backward",
+ "undo",
+ "redo",
+ ])("accepts local %s transactions", (userEvent) => {
+ const transaction = createTransaction({
+ changes: { from: 0, insert: "#" },
+ annotations: [Transaction.userEvent.of(userEvent)],
+ });
+
+ expect(
+ shouldAutorunMarkdownUpdate({
+ docChanged: transaction.docChanged,
+ transactions: [transaction],
+ }),
+ ).toBe(true);
+ });
+
+ it("ignores formatting changes", () => {
+ const transaction = createTransaction({
+ changes: { from: 0, insert: "#" },
+ annotations: [Transaction.userEvent.of("input.type")],
+ effects: [formattingChangeEffect.of(true)],
+ });
+
+ expect(
+ shouldAutorunMarkdownUpdate({
+ docChanged: transaction.docChanged,
+ transactions: [transaction],
+ }),
+ ).toBe(false);
+ });
+
+ it("ignores RTC sync transactions", () => {
+ const transaction = createTransaction({
+ changes: { from: 0, insert: "#" },
+ annotations: [
+ Transaction.userEvent.of("input.type"),
+ loroSyncAnnotation.of(true),
+ ],
+ });
+
+ expect(
+ shouldAutorunMarkdownUpdate({
+ docChanged: transaction.docChanged,
+ transactions: [transaction],
+ hasFocus: true,
+ }),
+ ).toBe(false);
+ });
+
+ it("ignores programmatic doc changes without a user event", () => {
+ const transaction = createTransaction({
+ changes: { from: 0, insert: "#" },
+ });
+
+ expect(
+ shouldAutorunMarkdownUpdate({
+ docChanged: transaction.docChanged,
+ transactions: [transaction],
+ }),
+ ).toBe(false);
+ });
+
+ it("allows focused local doc changes without user event annotations", () => {
+ const transaction = createTransaction({
+ changes: { from: 0, insert: "#" },
+ });
+
+ expect(
+ shouldAutorunMarkdownUpdate({
+ docChanged: transaction.docChanged,
+ transactions: [transaction],
+ hasFocus: true,
+ }),
+ ).toBe(true);
+ });
+
+ it("honors the predicate gate", () => {
+ const transaction = createTransaction({
+ changes: { from: 0, insert: "#" },
+ annotations: [Transaction.userEvent.of("input.type")],
+ });
+
+ expect(
+ shouldAutorunMarkdownUpdate({
+ docChanged: transaction.docChanged,
+ transactions: [transaction],
+ predicate: () => false,
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/frontend/src/core/codemirror/cells/extensions.ts b/frontend/src/core/codemirror/cells/extensions.ts
index 27afefac95..159a4505ee 100644
--- a/frontend/src/core/codemirror/cells/extensions.ts
+++ b/frontend/src/core/codemirror/cells/extensions.ts
@@ -2,9 +2,15 @@
import { closeCompletion, completionStatus } from "@codemirror/autocomplete";
import { type Extension, Prec } from "@codemirror/state";
-import { EditorView, type KeyBinding, keymap } from "@codemirror/view";
+import {
+ EditorView,
+ type KeyBinding,
+ keymap,
+ type ViewUpdate,
+} from "@codemirror/view";
import { createTracebackInfoAtom } from "@/core/cells/cells";
import { type CellId, HTMLCellId, SCRATCH_CELL_ID } from "@/core/cells/ids";
+import { loroSyncAnnotation } from "@/core/codemirror/rtc/loro/sync";
import type { KeymapConfig } from "@/core/config/config-schema";
import type { HotkeyProvider } from "@/core/hotkeys/hotkeys";
import { duplicateWithCtrlModifier } from "@/core/hotkeys/shortcuts";
@@ -330,6 +336,53 @@ function cellCodeEditing(hotkeys: HotkeyProvider): Extension[] {
return [onChangePlugin, formatKeymapExtension(hotkeys)];
}
+const MARKDOWN_AUTORUN_USER_EVENTS = ["input", "delete", "undo", "redo"];
+
+function shouldAutorunMarkdownUpdate({
+ docChanged,
+ transactions,
+ predicate = () => true,
+ hasFocus = false,
+}: Pick<ViewUpdate, "docChanged" | "transactions"> & {
+ predicate?: () => boolean;
+ hasFocus?: boolean;
+}): boolean {
+ // If the doc didn't change, ignore.
+ if (!docChanged) {
+ return false;
+ }
+
+ // The caller decides when markdown autorun is allowed, e.g. not for
+ // f-strings where rerunning on every keystroke is usually incorrect.
+ if (!predicate()) {
+ return false;
+ }
+
+ // This happens on mount when we start in markdown mode.
+ // Ignore formatting changes so language switches don't trigger autorun.
+ const isFormattingChange = transactions.some((tr) =>
+ tr.effects.some((effect) => effect.is(formattingChangeEffect)),
+ );
+ if (isFormattingChange) {
+ return false;
+ }
+
+ return transactions.some((tr) => {
+ // Ignore RTC sync changes to avoid duplicate runs from remote edits.
+ if (tr.annotation(loroSyncAnnotation) !== undefined) {
+ return false;
+ }
+
+ // Prefer explicit local edit transactions, but keep a focused fallback for
+ // local rewrite paths like split-cell, which can update markdown content
+ // without annotating a user event.
+ return (
+ MARKDOWN_AUTORUN_USER_EVENTS.some((kind) => tr.isUserEvent(kind)) ||
+ hasFocus
+ );
+ });
+}
+
/**
* Extension for auto-running markdown cells
*/
@@ -339,30 +392,16 @@ export function markdownAutoRunExtension({
predicate: () => boolean;
}): Extension {
return EditorView.updateListener.of((update) => {
- // If the doc didn't change, ignore
- if (!update.docChanged) {
- return;
- }
-
- // If not focused, ignore
- // This can cause multiple runs when in RTC mode
- if (!update.view.hasFocus) {
- return;
- }
-
- if (!predicate()) {
+ if (
+ !shouldAutorunMarkdownUpdate({
+ docChanged: update.docChanged,
+ transactions: update.transactions,
+ predicate,
+ hasFocus: update.view.hasFocus,
+ })
+ ) {
return;
}
-
- // This happens on mount when we start in markdown mode
- const isFormattingChange = update.transactions.some((tr) =>
- tr.effects.some((effect) => effect.is(formattingChangeEffect)),
- );
- if (isFormattingChange) {
- // Ignore formatting changes
- return;
- }
-
const actions = update.view.state.facet(cellActionsState);
actions.onRun();
});
@@ -388,3 +427,7 @@ export function cellBundle({
),
];
}
+
+export const exportedForTesting = {
+ shouldAutorunMarkdownUpdate,
+};
diff --git a/frontend/src/core/codemirror/rtc/loro/__tests__/sync.test.ts b/frontend/src/core/codemirror/rtc/loro/__tests__/sync.test.ts
new file mode 100644
index 0000000000..2f5ca5088c
--- /dev/null
+++ b/frontend/src/core/codemirror/rtc/loro/__tests__/sync.test.ts
@@ -0,0 +1,52 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { EditorState } from "@codemirror/state";
+import type { EditorView } from "@codemirror/view";
+import { LoroDoc, LoroText } from "loro-crdt";
+import { describe, expect, it, vi } from "vitest";
+import { LoroSyncPluginValue, loroSyncAnnotation } from "../sync";
+
+describe("LoroSyncPluginValue", () => {
+ it("annotates the initial reconciliation dispatch as RTC sync", async () => {
+ const dispatch = vi.fn();
+ const view = {
+ state: EditorState.create({ doc: "local" }),
+ dispatch,
+ } as unknown as EditorView;
+
+ const doc = new LoroDoc();
+ const text = doc
+ .getMap("codes")
+ .getOrCreateContainer("cell-1", new LoroText());
+ text.insert(0, "remote");
+
+ const plugin = new LoroSyncPluginValue(
+ view,
+ doc,
+ ["codes", "cell-1"],
+ () => text,
+ );
+
+ await Promise.resolve();
+
+ expect(dispatch).toHaveBeenCalledTimes(1);
+ expect(dispatch).toHaveBeenCalledWith(
+ expect.objectContaining({
+ changes: [
+ {
+ from: 0,
+ to: view.state.doc.length,
+ insert: "remote",
+ },
+ ],
+ annotations: [
+ expect.objectContaining({
+ type: loroSyncAnnotation,
+ }),
+ ],
+ }),
+ );
+
+ plugin.destroy();
+ });
+});
diff --git a/frontend/src/core/codemirror/rtc/loro/sync.ts b/frontend/src/core/codemirror/rtc/loro/sync.ts
index 7748acc339..1494e2d717 100644
--- a/frontend/src/core/codemirror/rtc/loro/sync.ts
+++ b/frontend/src/core/codemirror/rtc/loro/sync.ts
@@ -72,6 +72,7 @@ export class LoroSyncPluginValue implements PluginValue {
insert: text.toString(),
},
],
+ annotations: [loroSyncAnnotation.of(this)],
});
});
}