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.

Add new `NotebookDocument` model (#8842)

Trevor Manz182a89dbe374
diff --git a/frontend/src/__mocks__/requests.ts b/frontend/src/__mocks__/requests.ts
index e6b75998d5..86fdb99949 100644
--- a/frontend/src/__mocks__/requests.ts
+++ b/frontend/src/__mocks__/requests.ts
@@ -18,6 +18,7 @@ export const MockRequestClient = {
sendRename: vi.fn().mockResolvedValue({}),
sendRestart: vi.fn().mockResolvedValue({}),
syncCellIds: vi.fn().mockResolvedValue({}),
+ sendDocumentTransaction: vi.fn().mockResolvedValue({}),
sendSave: vi.fn().mockResolvedValue({}),
sendCopy: vi.fn().mockResolvedValue({}),
sendStdin: vi.fn().mockResolvedValue({}),
diff --git a/frontend/src/core/cells/__tests__/apply-transaction.test.ts b/frontend/src/core/cells/__tests__/apply-transaction.test.ts
new file mode 100644
index 0000000000..ad9689c90f
--- /dev/null
+++ b/frontend/src/core/cells/__tests__/apply-transaction.test.ts
@@ -0,0 +1,279 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+/**
+ * Tests for fromDocumentChanges / applyTransactionChanges in isolation.
+ *
+ * These test the change→action mapping for edge cases and error paths that
+ * can't be exercised via the round-trip tests (since toDocumentChanges would
+ * never produce malformed or conflicting changes). Basic correctness is
+ * covered by document-roundtrip.test.ts. This file focuses on:
+ *
+ * - Multi-change transactions (create+move, create+set-code, set-code+delete)
+ * - Cancelled changes (create+delete same cell)
+ * - Missing/nonexistent anchors and cells
+ * - Config propagation on create-cell (disabled, column)
+ */
+
+import { python } from "@codemirror/lang-python";
+import { EditorState } from "@codemirror/state";
+import { EditorView } from "@codemirror/view";
+import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import type { CellHandle } from "@/components/editor/notebook-cell";
+import { adaptiveLanguageConfiguration } from "@/core/codemirror/language/extension";
+import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";
+import { MultiColumn } from "@/utils/id-tree";
+import { exportedForTesting, type NotebookState } from "../cells";
+import {
+ applyTransactionChanges,
+ exportedForTesting as middlewareExports,
+} from "../document-changes";
+import { CellId } from "../ids";
+
+const { initialNotebookState, reducer, createActions } = exportedForTesting;
+
+function createEditor(code: string) {
+ const state = EditorState.create({
+ doc: code,
+ extensions: [
+ python(),
+ adaptiveLanguageConfiguration({
+ cellId: "cell1" as CellId,
+ completionConfig: {
+ activate_on_typing: true,
+ signature_hint_on_typing: false,
+ copilot: false,
+ codeium_api_key: null,
+ },
+ hotkeys: new OverridingHotkeyProvider({}),
+ placeholderType: "marimo-import",
+ lspConfig: {},
+ }),
+ ],
+ });
+ return new EditorView({ state, parent: document.body });
+}
+
+let state: NotebookState;
+let actions: ReturnType<typeof createActions>;
+
+function setup(...codes: string[]) {
+ state = initialNotebookState();
+ state.cellIds = MultiColumn.from([]);
+ actions = createActions((action) => {
+ state = reducer(state, action);
+ for (const [cellId, handle] of Object.entries(state.cellHandles)) {
+ if (!handle.current) {
+ const view = createEditor(state.cellData[cellId as CellId].code);
+ const h: CellHandle = { editorView: view, editorViewOrNull: view };
+ state.cellHandles[cellId as CellId] = { current: h };
+ }
+ }
+ });
+ for (const code of codes) {
+ actions.createNewCell({ cellId: "__end__", before: false, code });
+ }
+}
+
+afterEach(() => {
+ middlewareExports.cancelPendingChanges();
+});
+
+function apply(changes: Parameters<typeof applyTransactionChanges>[0]) {
+ applyTransactionChanges(changes, actions, () => state.cellIds.inOrderIds);
+}
+
+/** Snapshot of document state: ordering, code, name, config. */
+function pretty(s: NotebookState): string {
+ const lines = s.cellIds.inOrderIds.map((id) => {
+ const cell = s.cellData[id];
+ const flags: string[] = [];
+ if (cell.name && cell.name !== "_") {
+ flags.push(`name=${cell.name}`);
+ }
+ if (cell.config.hide_code) {
+ flags.push("hide_code");
+ }
+ if (cell.config.disabled) {
+ flags.push("disabled");
+ }
+ if (cell.config.column != null) {
+ flags.push(`col=${cell.config.column}`);
+ }
+ const suffix = flags.length > 0 ? ` [${flags.join(", ")}]` : "";
+ return `${id}: '${cell.code}'${suffix}`;
+ });
+ return `\n${lines.join("\n")}\n`;
+}
+
+let i = 0;
+
+beforeAll(() => {
+ CellId.create = () => `${i++}` as CellId;
+});
+
+beforeEach(() => {
+ i = 0;
+});
+
+describe("applyTransactionChanges edge cases", () => {
+ it("create-cell applies disabled and column config", () => {
+ setup("a");
+ apply([
+ {
+ type: "create-cell",
+ cellId: "new-cell",
+ code: "configured",
+ name: "",
+ config: { hide_code: true, disabled: true, column: 1 },
+ },
+ ]);
+ expect(pretty(state)).toMatchInlineSnapshot(`
+ "
+ 0: 'a'
+ new-cell: 'configured' [hide_code, disabled, col=1]
+ "
+ `);
+ });
+
+ it("create-cell then move-cell in same transaction", () => {
+ setup("a", "b");
+ const [a] = state.cellIds.inOrderIds;
+ apply([
+ {
+ type: "create-cell",
+ cellId: "new-cell",
+ code: "new",
+ name: "",
+ config: {},
+ },
+ { type: "move-cell", cellId: "new-cell", before: a },
+ ]);
+ expect(pretty(state)).toMatchInlineSnapshot(`
+ "
+ new-cell: 'new'
+ 0: 'a'
+ 1: 'b'
+ "
+ `);
+ });
+
+ it("create-cell then set-code in same transaction", () => {
+ setup("a");
+ apply([
+ {
+ type: "create-cell",
+ cellId: "new-cell",
+ code: "initial",
+ name: "",
+ config: {},
+ },
+ { type: "set-code", cellId: "new-cell", code: "updated" },
+ ]);
+ expect(pretty(state)).toMatchInlineSnapshot(`
+ "
+ 0: 'a'
+ new-cell: 'updated'
+ "
+ `);
+ });
+
+ it("create-cell then delete-cell same cell cancels out", () => {
+ setup("a");
+ apply([
+ {
+ type: "create-cell",
+ cellId: "ephemeral",
+ code: "tmp",
+ name: "",
+ config: {},
+ },
+ { type: "delete-cell", cellId: "ephemeral" },
+ ]);
+ expect(pretty(state)).toMatchInlineSnapshot(`
+ "
+ 0: 'a'
+ "
+ `);
+ });
+
+ it("multiple changes in one transaction", () => {
+ setup("a", "b", "c");
+ const [a, b, c] = state.cellIds.inOrderIds;
+ apply([
+ { type: "set-code", cellId: a, code: "x = 1" },
+ { type: "set-name", cellId: b, name: "middle" },
+ { type: "delete-cell", cellId: c },
+ ]);
+ expect(pretty(state)).toMatchInlineSnapshot(`
+ "
+ 0: 'x = 1'
+ 1: 'b' [name=middle]
+ "
+ `);
+ });
+
+ it("move-cell with no anchor appends to end", () => {
+ setup("a", "b", "c");
+ const [a] = state.cellIds.inOrderIds;
+ apply([{ type: "move-cell", cellId: a }]);
+ expect(pretty(state)).toMatchInlineSnapshot(`
+ "
+ 1: 'b'
+ 2: 'c'
+ 0: 'a'
+ "
+ `);
+ });
+
+ it("move-cell with missing after anchor falls back to end", () => {
+ setup("a", "b");
+ const [a] = state.cellIds.inOrderIds;
+ apply([{ type: "move-cell", cellId: a, after: "nonexistent" as CellId }]);
+ expect(pretty(state)).toMatchInlineSnapshot(`
+ "
+ 1: 'b'
+ 0: 'a'
+ "
+ `);
+ });
+
+ it("move-cell with missing before anchor falls back to start", () => {
+ setup("a", "b");
+ const [, b] = state.cellIds.inOrderIds;
+ apply([{ type: "move-cell", cellId: b, before: "nonexistent" as CellId }]);
+ expect(pretty(state)).toMatchInlineSnapshot(`
+ "
+ 1: 'b'
+ 0: 'a'
+ "
+ `);
+ });
+
+ it("move-cell on nonexistent cell is a no-op", () => {
+ setup("a", "b");
+ apply([
+ {
+ type: "move-cell",
+ cellId: "nonexistent" as CellId,
+ after: "0" as CellId,
+ },
+ ]);
+ expect(pretty(state)).toMatchInlineSnapshot(`
+ "
+ 0: 'a'
+ 1: 'b'
+ "
+ `);
+ });
+
+ it("empty changes is a no-op", () => {
+ setup("a", "b");
+ apply([]);
+ expect(pretty(state)).toMatchInlineSnapshot(`
+ "
+ 0: 'a'
+ 1: 'b'
+ "
+ `);
+ });
+});
diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.ts
index 6f69e45e29..e2fc3ec146 100644
--- a/frontend/src/core/cells/__tests__/cells.test.ts
+++ b/frontend/src/core/cells/__tests__/cells.test.ts
@@ -6,6 +6,7 @@ import { EditorView } from "@codemirror/view";
import { createStore } from "jotai";
import {
afterAll,
+ afterEach,
beforeAll,
beforeEach,
describe,
@@ -29,6 +30,7 @@ import {
type NotebookState,
notebookAtom,
} from "../cells";
+import { exportedForTesting as documentTransactionTestExports } from "../document-changes";
import {
focusAndScrollCellIntoView,
scrollToBottom,
@@ -147,6 +149,10 @@ describe("cell reducer", () => {
firstCellId = state.cellIds.inOrderIds[0];
});
+ afterEach(() => {
+ documentTransactionTestExports.cancelPendingChanges();
+ });
+
afterAll(() => {
CellId.create = originalCreate;
});
diff --git a/frontend/src/core/cells/__tests__/document-changes.test.ts b/frontend/src/core/cells/__tests__/document-changes.test.ts
new file mode 100644
index 0000000000..2dffa166bd
--- /dev/null
+++ b/frontend/src/core/cells/__tests__/document-changes.test.ts
@@ -0,0 +1,575 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+/**
+ * Tests for toDocumentChanges (action → change mapping) as a pure function.
+ *
+ * Each test calls the reducer to produce prevState/newState, then calls
+ * toDocumentChanges directly — no middleware, no side effects. Basic round-trip
+ * correctness is covered by document-roundtrip.test.ts. This file focuses on:
+ *
+ * - anchorOf edge cases (before vs after, first cell, __end__)
+ * - Field name mapping (hide_code → hideCode)
+ * - Column structure actions emitting reorder-cells
+ * - Actions that should NOT emit changes
+ */
+
+import { python } from "@codemirror/lang-python";
+import { EditorState } from "@codemirror/state";
+import { EditorView } from "@codemirror/view";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import { cellId } from "@/__tests__/branded";
+import type { CellHandle } from "@/components/editor/notebook-cell";
+import { adaptiveLanguageConfiguration } from "@/core/codemirror/language/extension";
+import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";
+import { MultiColumn } from "@/utils/id-tree";
+import { exportedForTesting, type NotebookState } from "../cells";
+import { type CellAction, toDocumentChanges } from "../document-changes";
+import { CellId } from "../ids";
+
+const { initialNotebookState, reducer } = exportedForTesting;
+
+function createEditor(code: string) {
+ const state = EditorState.create({
+ doc: code,
+ extensions: [
+ python(),
+ adaptiveLanguageConfiguration({
+ cellId: cellId("cell1"),
+ completionConfig: {
+ activate_on_typing: true,
+ signature_hint_on_typing: false,
+ copilot: false,
+ codeium_api_key: null,
+ },
+ hotkeys: new OverridingHotkeyProvider({}),
+ placeholderType: "marimo-import",
+ lspConfig: {},
+ }),
+ ],
+ });
+ return new EditorView({ state, parent: document.body });
+}
+
+/** Dispatch an action through the reducer and auto-create editor handles. */
+function dispatch(
+ state: NotebookState,
+ action: { type: string; payload: unknown },
+): NotebookState {
+ const next = reducer(state, action);
+ for (const [cellIdString, handle] of Object.entries(next.cellHandles)) {
+ const cid = cellIdString as CellId;
+ if (!handle.current) {
+ const view = createEditor(next.cellData[cid].code);
+ const h: CellHandle = { editorView: view, editorViewOrNull: view };
+ next.cellHandles[cid] = { current: h };
+ }
+ }
+ return next;
+}
+
+/** Dispatch an action and return the changes it produces. */
+function resolve(state: NotebookState, action: CellAction) {
+ const next = dispatch(state, action);
+ const changes = toDocumentChanges(state, next, action);
+ return { next, changes };
+}
+
+let state: NotebookState;
+
+let i = 0;
+const originalCreate = CellId.create.bind(CellId);
+
+beforeAll(() => {
+ CellId.create = () => cellId(`${i++}`);
+});
+
+beforeEach(() => {
+ i = 0;
+ state = initialNotebookState();
+ state.cellIds = MultiColumn.from([]);
+});
+
+afterAll(() => {
+ CellId.create = originalCreate;
+});
+
+function setup(...codes: string[]) {
+ for (const code of codes) {
+ state = dispatch(state, {
+ type: "createNewCell",
+ payload: {
+ cellId: "__end__",
+ before: false,
+ code,
+ newCellId: CellId.create(),
+ },
+ });
+ }
+}
+
+describe("toDocumentChanges", () => {
+ describe("anchorOf edge cases", () => {
+ it("uses before anchor when new cell is first", () => {
+ setup("a");
+ const [a] = state.cellIds.inOrderIds;
+
+ const { changes } = resolve(state, {
+ type: "createNewCell",
+ payload: {
+ cellId: a,
+ before: true,
+ code: "first",
+ newCellId: CellId.create(),
+ },
+ });
+
+ expect(changes).toMatchInlineSnapshot(`
+ [
+ {
+ "before": "0",
+ "cellId": "1",
+ "code": "first",
+ "config": {
+ "column": null,
+ "disabled": false,
+ "hide_code": false,
+ },
+ "name": "_",
+ "type": "create-cell",
+ },
+ ]
+ `);
+ });
+
+ it("uses after anchor for __end__ insertion", () => {
+ setup("a");
+ const { changes } = resolve(state, {
+ type: "createNewCell",
+ payload: {
+ cellId: "__end__",
+ before: false,
+ code: "last",
+ newCellId: CellId.create(),
+ },
+ });
+
+ expect(changes).toMatchInlineSnapshot(`
+ [
+ {
+ "after": "0",
+ "cellId": "1",
+ "code": "last",
+ "config": {
+ "column": null,
+ "disabled": false,
+ "hide_code": false,
+ },
+ "name": "_",
+ "type": "create-cell",
+ },
+ ]
+ `);
+ });
+
+ it("uses before when sendToTop moves cell to first position", () => {
+ setup("a", "b", "c");
+ const [, b] = state.cellIds.inOrderIds;
+
+ const { changes } = resolve(state, {
+ type: "sendToTop",
+ payload: { cellId: b },
+ });
+
+ expect(changes).toMatchInlineSnapshot(`
+ [
+ {
+ "before": "0",
+ "cellId": "1",
+ "type": "move-cell",
+ },
+ ]
+ `);
+ });
+ });
+
+ describe("field name mapping", () => {
+ it("maps hide_code to hideCode in set-config", () => {
+ setup("a");
+ const [a] = state.cellIds.inOrderIds;
+
+ const { changes } = resolve(state, {
+ type: "updateCellConfig",
+ payload: { cellId: a, config: { hide_code: true } },
+ });
+
+ expect(changes).toMatchInlineSnapshot(`
+ [
+ {
+ "cellId": "0",
+ "hideCode": true,
+ "type": "set-config",
+ },
+ ]
+ `);
+ });
+
+ it("includes full CellConfig in create-cell", () => {
+ setup("a");
+
+ const { changes } = resolve(state, {
+ type: "createNewCell",
+ payload: {
+ cellId: "__end__",
+ before: false,
+ code: "hidden",
+ newCellId: CellId.create(),
+ hideCode: true,
+ },
+ });
+
+ expect(changes[0]).toMatchObject({
+ type: "create-cell",
+ config: { hide_code: true },
+ });
+ });
+ });
+
+ describe("column structure actions", () => {
+ it("dropOverNewColumn emits set-config + reorder-cells", () => {
+ setup("a", "b");
+ const [, b] = state.cellIds.inOrderIds;
+
+ const { changes } = resolve(state, {
+ type: "dropOverNewColumn",
+ payload: { cellId: b },
+ });
+
+ expect(changes).toMatchInlineSnapshot(`
+ [
+ {
+ "cellId": "1",
+ "column": 1,
+ "type": "set-config",
+ },
+ {
+ "cellIds": [
+ "0",
+ "1",
+ ],
+ "type": "reorder-cells",
+ },
+ ]
+ `);
+ });
+
+ it("addColumnBreakpoint emits set-config + reorder-cells", () => {
+ setup("a", "b", "c");
+ const [, b] = state.cellIds.inOrderIds;
+
+ const { changes } = resolve(state, {
+ type: "addColumnBreakpoint",
+ payload: { cellId: b },
+ });
+
+ expect(changes).toMatchInlineSnapshot(`
+ [
+ {
+ "cellId": "1",
+ "column": 1,
+ "type": "set-config",
+ },
+ {
+ "cellId": "2",
+ "column": 1,
+ "type": "set-config",
+ },
+ {
+ "cellIds": [
+ "0",
+ "1",
+ "2",
+ ],
+ "type": "reorder-cells",
+ },
+ ]
+ `);
+ });
+
+ it("mergeAllColumns emits set-config + reorder-cells", () => {
+ setup("a", "b", "c");
+ const [, b] = state.cellIds.inOrderIds;
+ state = dispatch(state, {
+ type: "addColumnBreakpoint",
+ payload: { cellId: b },
+ });
+
+ const { changes } = resolve(state, {
+ type: "mergeAllColumns",
+ payload: {},
+ });
+
+ expect(changes).toMatchInlineSnapshot(`
+ [
+ {
+ "cellId": "1",
+ "column": 0,
+ "type": "set-config",
+ },
+ {
+ "cellId": "2",
+ "column": 0,
+ "type": "set-config",
+ },
+ {
+ "cellIds": [
+ "0",
+ "1",
+ "2",
+ ],
+ "type": "reorder-cells",
+ },
+ ]
+ `);
+ });
+ });
+
+ describe("cell lifecycle actions", () => {
+ it("addColumn emits create-cell + column layout changes", () => {
+ setup("a");
+ const [a] = state.cellIds.inOrderIds;
+ const columnId = state.cellIds.findWithId(a).id;
+
+ const { changes } = resolve(state, {
+ type: "addColumn",
+ payload: { columnId },
+ });
+
+ expect(changes).toMatchInlineSnapshot(`
+ [
+ {
+ "after": "0",
+ "cellId": "1",
+ "code": "",
+ "config": {
+ "column": null,
+ "disabled": false,
+ "hide_code": false,
+ },
+ "name": "_",
+ "type": "create-cell",
+ },
+ {
+ "cellId": "1",
+ "column": 1,
+ "type": "set-config",
+ },
+ {
+ "cellIds": [
+ "0",
+ "1",
+ ],
+ "type": "reorder-cells",
+ },
+ ]
+ `);
+ });
+
+ it("undoDeleteCell emits create-cell for restored cell", () => {
+ setup("a", "b");
+ const [, b] = state.cellIds.inOrderIds;
+
+ // Delete cell b, then undo
+ state = dispatch(state, {
+ type: "deleteCell",
+ payload: { cellId: b },
+ });
+
+ const { changes } = resolve(state, {
+ type: "undoDeleteCell",
+ payload: {},
+ });
+
+ // Restored cell should have original code
+ expect(changes[0]).toMatchObject({
+ type: "create-cell",
+ code: "b",
+ });
+ });
+
+ it("splitCell emits set-code + create-cell", () => {
+ setup("line1\nline2");
+ const [a] = state.cellIds.inOrderIds;
+
+ // Position cursor at end of "line1" (position 5)
+ const view = state.cellHandles[a].current!.editorView;
+ view.dispatch({ selection: { anchor: 5 } });
+
+ const { changes } = resolve(state, {
+ type: "splitCell",
+ payload: { cellId: a },
+ });
+
+ expect(changes).toMatchInlineSnapshot(`
+ [
+ {
+ "cellId": "0",
+ "code": "line1",
+ "type": "set-code",
+ },
+ {
+ "after": "0",
+ "cellId": "1",
+ "code": "line2",
+ "config": {
+ "column": null,
+ "disabled": false,
+ "hide_code": false,
+ },
+ "name": "_",
+ "type": "create-cell",
+ },
+ ]
+ `);
+ });
+
+ it("undoSplitCell emits set-code + delete-cell", () => {
+ setup("line1\nline2");
+ const [a] = state.cellIds.inOrderIds;
+
+ // Split the cell first
+ const view = state.cellHandles[a].current!.editorView;
+ view.dispatch({ selection: { anchor: 5 } });
+ const snapshot = view.state.doc.toString();
+ state = dispatch(state, {
+ type: "splitCell",
+ payload: { cellId: a },
+ });
+ const [, newCell] = state.cellIds.inOrderIds;
+
+ // Now undo the split
+ const { changes } = resolve(state, {
+ type: "undoSplitCell",
+ payload: { cellId: a, snapshot },
+ });
+
+ expect(changes).toMatchInlineSnapshot(`
+ [
+ {
+ "cellId": "0",
+ "code": "line1
+ line2",
+ "type": "set-code",
+ },
+ {
+ "cellId": "${newCell}",
+ "type": "delete-cell",
+ },
+ ]
+ `);
+ });
+
+ it("moveToNextCell emits create-cell when past last cell", () => {
+ setup("a");
+ const [a] = state.cellIds.inOrderIds;
+
+ const { changes } = resolve(state, {
+ type: "moveToNextCell",
+ payload: { cellId: a, before: false },
+ });
+
+ expect(changes).toMatchInlineSnapshot(`
+ [
+ {
+ "after": "0",
+ "cellId": "1",
+ "code": "",
+ "config": {
+ "column": null,
+ "disabled": false,
+ "hide_code": false,
+ },
+ "name": "_",
+ "type": "create-cell",
+ },
+ ]
+ `);
+ });
+
+ it("moveToNextCell emits nothing when moving within bounds", () => {
+ setup("a", "b");
+ const [a] = state.cellIds.inOrderIds;
+
+ const { changes } = resolve(state, {
+ type: "moveToNextCell",
+ payload: { cellId: a, before: false },
+ });
+
+ expect(changes).toHaveLength(0);
+ });
+
+ it("addSetupCellIfDoesntExist emits create-cell when new", () => {
+ setup("a");
+
+ const { changes } = resolve(state, {
+ type: "addSetupCellIfDoesntExist",
+ payload: { code: "import marimo as mo" },
+ });
+
+ expect(changes).toMatchInlineSnapshot(`
+ [
+ {
+ "before": "0",
+ "cellId": "setup",
+ "code": "import marimo as mo",
+ "config": {
+ "column": null,
+ "disabled": false,
+ "hide_code": false,
+ },
+ "name": "setup",
+ "type": "create-cell",
+ },
+ ]
+ `);
+ });
+
+ it("addSetupCellIfDoesntExist emits nothing when already exists", () => {
+ setup("a");
+ // Add setup cell first
+ state = dispatch(state, {
+ type: "addSetupCellIfDoesntExist",
+ payload: { code: "import marimo as mo" },
+ });
+
+ // Try to add again — should just focus
+ const { changes } = resolve(state, {
+ type: "addSetupCellIfDoesntExist",
+ payload: {},
+ });
+
+ expect(changes).toHaveLength(0);
+ });
+ });
+
+ describe("actions that should NOT emit changes", () => {
+ it("focusCell returns empty", () => {
+ setup("a", "b");
+ const [a] = state.cellIds.inOrderIds;
+ const { changes } = resolve(state, {
+ type: "focusCell",
+ payload: { cellId: a, where: "after" },
+ });
+ expect(changes).toHaveLength(0);
+ });
+
+ it("prepareForRun returns empty", () => {
+ setup("a");
+ const [a] = state.cellIds.inOrderIds;
+ const { changes } = resolve(state, {
+ type: "prepareForRun",
+ payload: { cellId: a },
+ });
+ expect(changes).toHaveLength(0);
+ });
+ });
+});
diff --git a/frontend/src/core/cells/__tests__/document-roundtrip.test.ts b/frontend/src/core/cells/__tests__/document-roundtrip.test.ts
new file mode 100644
index 0000000000..41eeb40133
--- /dev/null
+++ b/frontend/src/core/cells/__tests__/document-roundtrip.test.ts
@@ -0,0 +1,376 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+/**
+ * Round-trip tests: perform actions on a primary notebook (producing changes
+ * via the middleware), then apply those changes to a replica notebook via
+ * applyTransactionChanges. The two should converge to identical document state.
+ *
+ * This catches drift between what the middleware emits and what
+ * apply-transaction consumes.
+ */
+
+import { python } from "@codemirror/lang-python";
+import { EditorState } from "@codemirror/state";
+import { EditorView } from "@codemirror/view";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+} from "vitest";
+import { cellId } from "@/__tests__/branded";
+import type { CellHandle } from "@/components/editor/notebook-cell";
+import { adaptiveLanguageConfiguration } from "@/core/codemirror/language/extension";
+import { OverridingHotkeyProvider } from "@/core/hotkeys/hotkeys";
+import { MultiColumn } from "@/utils/id-tree";
+import { exportedForTesting, type NotebookState } from "../cells";
+import {
+ applyTransactionChanges,
+ exportedForTesting as middlewareExports,
+} from "../document-changes";
+import { CellId } from "../ids";
+
+const { initialNotebookState, reducer, createActions } = exportedForTesting;
+const { drainChanges } = middlewareExports;
+
+function createEditor(code: string) {
+ const state = EditorState.create({
+ doc: code,
+ extensions: [
+ python(),
+ adaptiveLanguageConfiguration({
+ cellId: cellId("cell1"),
+ completionConfig: {
+ activate_on_typing: true,
+ signature_hint_on_typing: false,
+ copilot: false,
+ codeium_api_key: null,
+ },
+ hotkeys: new OverridingHotkeyProvider({}),
+ placeholderType: "marimo-import",
+ lspConfig: {},
+ }),
+ ],
+ });
+ return new EditorView({ state, parent: document.body });
+}
+
+// --- Primary notebook: performs actions, middleware produces changes ---
+
+let primary: NotebookState;
+
+const primaryActions = createActions((action) => {
+ primary = reducer(primary, action);
+ for (const [cellIdString, handle] of Object.entries(primary.cellHandles)) {
+ // @ts-expect-error - Object.entries doesn't know keys are CellId
+ const cid: CellId = cellIdString;
+ if (!handle.current) {
+ const view = createEditor(primary.cellData[cid].code);
+ const h: CellHandle = { editorView: view, editorViewOrNull: view };
+ primary.cellHandles[cid] = { current: h };
+ }
+ }
+});
+
+// --- Replica notebook: receives changes via applyTransactionChanges ---
+
+let replica: NotebookState;
+
+const replicaActions = createActions((action) => {
+ replica = reducer(replica, action);
+ for (const [cellIdString, handle] of Object.entries(replica.cellHandles)) {
+ // @ts-expect-error - Object.entries doesn't know keys are CellId
+ const cid: CellId = cellIdString;
+ if (!handle.current) {
+ const view = createEditor(replica.cellData[cid].code);
+ const h: CellHandle = { editorView: view, editorViewOrNull: view };
+ replica.cellHandles[cid] = { current: h };
+ }
+ }
+});
+
+let i = 0;
+const originalCreate = CellId.create.bind(CellId);
+
+beforeAll(() => {
+ CellId.create = () => cellId(`${i++}`);
+});
+
+beforeEach(() => {
+ i = 0;
+ primary = initialNotebookState();
+ primary.cellIds = MultiColumn.from([]);
+ drainChanges();
+});
+
+afterEach(() => {
+ middlewareExports.cancelPendingChanges();
+});
+
+afterAll(() => {
+ CellId.create = originalCreate;
+});
+
+/** Set up both notebooks with the same initial cells. */
+function setup(...codes: string[]) {
+ for (const code of codes) {
+ primaryActions.createNewCell({
+ cellId: "__end__",
+ before: false,
+ code,
+ newCellId: CellId.create(),
+ });
+ }
+
+ // Apply the setup changes to the replica so both start identical
+ const setupChanges = drainChanges();
+ replica = initialNotebookState();
+ replica.cellIds = MultiColumn.from([]);
+ applyTransactionChanges(
+ setupChanges,
+ replicaActions,
+ () => replica.cellIds.inOrderIds,
+ );
+ // Drain any changes the replica's middleware produced
+ drainChanges();
+}
+
+/**
+ * Drain changes from the primary's middleware and apply them to the replica.
+ */
+function sync() {
+ const changes = drainChanges();
+ applyTransactionChanges(
+ changes,
+ replicaActions,
+ () => replica.cellIds.inOrderIds,
+ );
+ // Drain any changes the replica's middleware produced (we don't want those)
+ drainChanges();
+}
+
+/**
+ * Extract the document-relevant state: cell ordering, code, name, config.
+ * This is the "NotebookDocument" equivalent — what the Python side tracks.
+ *
+ * TODO(column-config): config.column is excluded because the column
+ * reducers (addColumnBreakpoint, dropOverNewColumn, moveColumn, etc.)
+ * update cellIds (MultiColumn structure) but don't sync config.column
+ * on affected cells. The middleware correctly emits set-config changes with
+ * the new column index, but the primary's config.column stays stale,
+ * causing a mismatch with the replica. Fix: have the column reducers
+ * update config.column as part of their state transition, then remove
+ * the { column: _, ...config } exclusion here.
+ */
+function documentSnapshot(state: NotebookState) {
+ return state.cellIds.inOrderIds.map((id) => {
+ const { column: _, ...config } = state.cellData[id].config;
+ return {
+ id,
+ code: state.cellData[id].code,
+ name: state.cellData[id].name,
+ config,
+ };
+ });
+}
+
+describe("document round-trip", () => {
+ it("initial setup converges", () => {
+ setup("a", "b", "c");
+ expect(documentSnapshot(primary)).toEqual(documentSnapshot(replica));
+ });
+
+ it("createNewCell at end", () => {
+ setup("a", "b");
+ primaryActions.createNewCell({
+ cellId: "__end__",
+ before: false,
+ code: "c",
+ newCellId: CellId.create(),
+ });
+ sync();
+ expect(documentSnapshot(primary)).toEqual(documentSnapshot(replica));
+ });
+
+ it("createNewCell before first cell", () => {
+ setup("a", "b");
+ const [a] = primary.cellIds.inOrderIds;
+ primaryActions.createNewCell({
+ cellId: a,
+ before: true,
+ code: "before-a",
+ newCellId: CellId.create(),
+ });
+ sync();
+ expect(documentSnapshot(primary)).toEqual(documentSnapshot(replica));
+ });
+
+ it("createNewCell between cells", () => {
+ setup("a", "b", "c");
+ const [a] = primary.cellIds.inOrderIds;
+ primaryActions.createNewCell({
+ cellId: a,
+ before: false,
+ code: "between",
+ newCellId: CellId.create(),
+ });
+ sync();
+ expect(documentSnapshot(primary)).toEqual(documentSnapshot(replica));
+ });
+
+ it("createNewCell with hideCode config", () => {
+ setup("a");
+ primaryActions.createNewCell({
+ cellId: "__end__",
+ before: false,
+ code: "hidden",
+ newCellId: CellId.create(),
+ hideCode: true,
+ });
+ sync();
+ expect(documentSnapshot(primary)).toEqual(documentSnapshot(replica));
+ });
+
+ it("deleteCell", () => {
+ setup("a", "b", "c");
+ const [, b] = primary.cellIds.inOrderIds;
+ primaryActions.deleteCell({ cellId: b });
+ sync();
+ expect(documentSnapshot(primary)).toEqual(documentSnapshot(replica));
+ });
+
+ it("updateCellCode", () => {
+ setup("a", "b");
+ const [a] = primary.cellIds.inOrderIds;
+ primaryActions.updateCellCode({
+ cellId: a,
+ code: "updated",
+ formattingChange: false,
+ });
+ sync();
+ expect(documentSnapshot(primary)).toEqual(documentSnapshot(replica));
+ });
+
+ it("updateCellName", () => {
+ setup("a");
+ const [a] = primary.cellIds.inOrderIds;
+ primaryActions.updateCellName({ cellId: a, name: "my_var" });
+ sync();
+ expect(documentSnapshot(primary)).toEqual(documentSnapshot(replica));
+ });
+
+ it("updateCellConfig", () => {
+ setup("a");
+ const [a] = primary.cellIds.inOrderIds;
+ primaryActions.updateCellConfig({
+ cellId: a,
+ config: { hide_code: true, disabled: true },
+ });
+ sync();
+ expect(documentSnapshot(primary)).toEqual(documentSnapshot(replica));
+ });
+
+ it("moveCell down", () => {
+ setup("a", "b", "c");
+ const [a] = primary.cellIds.inOrderIds;
+ primaryActions.moveCell({ cellId: a, before: false });
+ sync();
+ expect(documentSnapshot(primary)).toEqual(documentSnapshot(replica));
+ });
+
+ it("sendToTop", () => {
+ setup("a", "b", "c");
+ const c = primary.cellIds.inOrderIds[2];
+ primaryActions.sendToTop({ cellId: c });
+ sync();
+ expect(documentSnapshot(primary)).toEqual(documentSnapshot(replica));
+ });
+
+ it("sendToBottom", () => {
+ setup("a", "b", "c");
+ const [a] = primary.cellIds.inOrderIds;
+ primaryActions.sendToBottom({ cellId: a });
+ sync();
+ expect(documentSnapshot(primary)).toEqual(documentSnapshot(replica));
+ });
+
+ it("dropCellOverCell", () => {
+ setup("a", "b", "c");
+ const [a, , c] = primary.cellIds.inOrderIds;
+ primaryActions.dropCellOverCell({ cellId: c, overCellId: a });
+ sync();
+ expect(documentSnapshot(primary)).toEqual(documentSnapshot(replica));
+ });
+
+ it("multiple operations in sequence", () => {
+ setup("a", "b", "c");
+
+ // Add a cell
+ const [a] = primary.cellIds.inOrderIds;
+ primaryActions.createNewCell({
+ cellId: a,
+ before: false,
+ code: "new",
+ newCellId: CellId.create(),
+ });
+ sync();
+
+ // Rename it
+ const newId = primary.cellIds.inOrderIds[1];
+ primaryActions.updateCellName({ cellId: newId, name: "inserted" });
+ sync();
+
+ // Move it to top
+ primaryActions.sendToTop({ cellId: newId });
+ sync();
+
+ // Update code on another cell
+ const last =
+ primary.cellIds.inOrderIds[primary.cellIds.inOrderIds.length - 1];
+ primaryActions.updateCellCode({
+ cellId: last,
+ code: "modified",
+ formattingChange: false,
+ });
+ sync();
+
+ expect(documentSnapshot(primary)).toEqual(documentSnapshot(replica));
+ });
+
+ it("create then delete", () => {
+ setup("a", "b");
+ primaryActions.createNewCell({
+ cellId: "__end__",
+ before: false,
+ code: "temporary",
+ newCellId: CellId.create(),
+ });
+ sync();
+
+ const newId =
+ primary.cellIds.inOrderIds[primary.cellIds.inOrderIds.length - 1];
+ primaryActions.deleteCell({ cellId: newId });
+ sync();
+
+ expect(documentSnapshot(primary)).toEqual(documentSnapshot(replica));
+ });
+
+ it("addColumnBreakpoint", () => {
+ setup("a", "b", "c");
+ const [, b] = primary.cellIds.inOrderIds;
+ primaryActions.addColumnBreakpoint({ cellId: b });
+ sync();
+ expect(documentSnapshot(primary)).toEqual(documentSnapshot(replica));
+ });
+
+ it("dropOverNewColumn", () => {
+ setup("a", "b", "c");
+ const [, b] = primary.cellIds.inOrderIds;
+ primaryActions.dropOverNewColumn({ cellId: b });
+ sync();
+ expect(documentSnapshot(primary)).toEqual(documentSnapshot(replica));
+ });
+});
diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts
index 8bb90475b9..bf8bee26fc 100644
--- a/frontend/src/core/cells/cells.ts
+++ b/frontend/src/core/cells/cells.ts
@@ -29,6 +29,7 @@ import type { CellConfig } from "../network/types";
import { isRtcEnabled } from "../rtc/state";
import { createDeepEqualAtom, store } from "../state/jotai";
import { prepareCellForExecution, transitionCell } from "./cell";
+import { documentTransactionMiddleware } from "./document-changes";
import { CellId, SCRATCH_CELL_ID, SETUP_CELL_ID } from "./ids";
import { type CellLog, getCellLogsForMessage } from "./logs";
import {
@@ -174,6 +175,7 @@ export interface CreateNewCellAction {
*/
const {
reducer,
+ addMiddleware,
createActions,
useActions,
valueAtom: notebookAtom,
@@ -756,13 +758,28 @@ const {
},
handleCellMessage: (state, message: CellMessage) => {
const cellId = message.cell_id;
- const nextState = updateCellRuntimeState({
+ let nextState = updateCellRuntimeState({
state,
cellId,
cellReducer: (cell) => {
return transitionCell(cell, message);
},
});
+ // When a cell is queued for execution, snapshot the current code
+ // as lastCodeRun. This clears staleness for cells executed by the
+ // kernel (e.g. via code_mode). If the user edits during execution,
+ // code !== lastCodeRun keeps the cell stale.
+ if (message.status === "queued") {
+ nextState = updateCellData({
+ state: nextState,
+ cellId,
+ cellReducer: (cell) => ({
+ ...cell,
+ lastCodeRun: cell.code.trim(),
+ edited: false,
+ }),
+ });
+ }
return {
...nextState,
cellLogs: [...nextState.cellLogs, ...getCellLogsForMessage(message)],
@@ -1405,6 +1422,12 @@ const {
},
});
+// We apply the middleware here (rather than inline in createReducerAndAtoms)
+// so that the document transaction middleware can import CellActions and
+// strictly type the dispatched actions without creating a circular dependency.
+// @ts-expect-error - TODO: We should have better types for the middleware that are strict
+addMiddleware(documentTransactionMiddleware);
+
function isCellCodeHidden(state: NotebookState, cellId: CellId): boolean {
return (
Boolean(state.cellData[cellId].config.hide_code) &&
@@ -1789,8 +1812,10 @@ export function createTracebackInfoAtom(
* Use this hook to dispatch cell actions. This hook will not cause a re-render
* when cells change.
*/
-export function useCellActions(): CellActions {
- return useActions();
+export function useCellActions(
+ options: { skipMiddleware?: boolean } = {},
+): CellActions {
+ return useActions(options);
}
/**
diff --git a/frontend/src/core/cells/document-changes.ts b/frontend/src/core/cells/document-changes.ts
new file mode 100644
index 0000000000..9a717ad7c6
--- /dev/null
+++ b/frontend/src/core/cells/document-changes.ts
@@ -0,0 +1,644 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+/**
+ * Document changes: the bridge between notebook reducer actions and the
+ * document transaction wire format.
+ *
+ * Pure functions:
+ * - toDocumentChanges: reducer action + state diff → document changes
+ * - fromDocumentChanges: document changes → reducer actions
+ * - cancelledCellIds: detect create+delete cancellations
+ *
+ * Impure wrappers (for use by the reducer middleware and websocket):
+ * - documentTransactionMiddleware: debounces and sends changes to the server
+ * - applyTransactionChanges: dispatches actions from incoming changes
+ */
+
+import { debounce } from "lodash-es";
+import { assertNever } from "@/utils/assertNever";
+import type { DispatchedActionOf } from "@/utils/createReducer";
+import { Logger } from "@/utils/Logger";
+import type { NotificationMessageData } from "../kernel/messages";
+import { kioskModeAtom } from "../mode";
+import { getRequestClient } from "../network/requests";
+import type { NotebookDocumentTransactionRequest } from "../network/types";
+import { store } from "../state/jotai";
+import type { CellActions, NotebookState } from "./cells";
+import type { CellId } from "./ids";
+import type { CellData } from "./types";
+
+export type DocumentChange =
+ NotebookDocumentTransactionRequest["changes"][number];
+
+type Transaction =
+ NotificationMessageData<"notebook-document-transaction">["transaction"];
+type TransactionChange = Transaction["changes"][number];
+
+export type CellAction = DispatchedActionOf<CellActions>;
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+/**
+ * Look up a cell in state by ID. Logs a warning and returns undefined
+ * if the cell doesn't exist.
+ */
+function getCell(
+ cellId: CellId | undefined,
+ state: NotebookState,
+): CellData | undefined {
+ if (!cellId) {
+ Logger.warn("getCell: cellId is undefined");
+ return undefined;
+ }
+ const cell = state.cellData[cellId];
+ if (!cell) {
+ Logger.warn(`getCell: cell ${cellId} not found in state`);
+ return undefined;
+ }
+ return cell;
+}
+
+/**
+ * Derive the position anchor for a cell from the notebook state.
+ * Returns `{ after: prevId }` if there's a cell before it,
+ * `{ before: nextId }` if it's the first cell, or `undefined` if it's alone.
+ */
+function anchorOf(
+ cellId: CellId,
+ state: NotebookState,
+): { after: CellId } | { before: CellId } | undefined {
+ const ids = state.cellIds.inOrderIds;
+ const idx = ids.indexOf(cellId);
+ if (idx > 0) {
+ return { after: ids[idx - 1] };
+ }
+ if (idx === 0 && ids.length > 1) {
+ return { before: ids[1] };
+ }
+ return undefined;
+}
+
+/**
+ * Build a map from cellId → column index for all cells in the state.
+ */
+function columnIndexMap(state: NotebookState): Map<CellId, number> {
+ const map = new Map<CellId, number>();
+ const columns = state.cellIds.getColumns();
+ for (const [col, column] of columns.entries()) {
+ for (const id of column.inOrderIds) {
+ map.set(id, col);
+ }
+ }
+ return map;
+}
+
+/**
+ * Find cells that were added between prevState and newState and return
+ * create-cell changes for each, with position derived from newState.
+ */
+function newCellChanges(
+ prevState: NotebookState,
+ newState: NotebookState,
+): DocumentChange[] {
+ const prevIds = new Set(prevState.cellIds.inOrderIds);
+ const changes: DocumentChange[] = [];
+ for (const id of newState.cellIds.inOrderIds) {
+ if (!prevIds.has(id)) {
+ const cell = getCell(id, newState);
+ if (cell) {
+ changes.push({
+ type: "create-cell",
+ cellId: cell.id,
+ code: cell.code,
+ name: cell.name,
+ config: cell.config,
+ ...anchorOf(cell.id, newState),
+ });
+ }
+ }
+ }
+ return changes;
+}
+
+/**
+ * Find cells that were removed between prevState and newState and return
+ * delete-cell changes for each.
+ */
+function deletedCellChanges(
+ prevState: NotebookState,
+ newState: NotebookState,
+): DocumentChange[] {
+ const newIds = new Set(newState.cellIds.inOrderIds);
+ const changes: DocumentChange[] = [];
+ for (const id of prevState.cellIds.inOrderIds) {
+ if (!newIds.has(id)) {
+ changes.push({ type: "delete-cell", cellId: id });
+ }
+ }
+ return changes;
+}
+
+/**
+ * Produce set-config changes for cells whose column index changed between
+ * prevState and newState, plus a reorder-cells change for the new ordering.
+ */
+function columnChanges(
+ prevState: NotebookState,
+ newState: NotebookState,
+): DocumentChange[] {
+ const prevColumns = columnIndexMap(prevState);
+ const newColumns = columnIndexMap(newState);
+ const changes: DocumentChange[] = [];
+
+ for (const [cellId, newCol] of newColumns) {
+ const prevCol = prevColumns.get(cellId);
+ if (prevCol !== newCol) {
+ changes.push({
+ type: "set-config",
+ cellId: cellId,
+ column: newCol,
+ });
+ }
+ }
+
+ changes.push({
+ type: "reorder-cells",
+ cellIds: newState.cellIds.inOrderIds,
+ });
+
+ return changes;
+}
+
+// ---------------------------------------------------------------------------
+// toDocumentChanges: action + state → changes
+// ---------------------------------------------------------------------------
+
+/**
+ * Given a reducer action and the before/after notebook state, return the
+ * document changes that represent the diff. Returns an empty array for
+ * actions that don't affect document structure.
+ */
+export function toDocumentChanges(
+ prevState: NotebookState,
+ newState: NotebookState,
+ action: DispatchedActionOf<CellActions>,
+): DocumentChange[] {
+ switch (action.type) {
+ // createNewCell → create-cell
+ // Reads code, name, and config from the newly created cell in newState.
+ // Position is derived from newState via anchorOf (after or before neighbor).
+ case "createNewCell":
+ return newCellChanges(prevState, newState);
+
+ // deleteCell → delete-cell
+ // Direct 1:1 mapping. Only the cellId is needed.
+ case "deleteCell":
+ return [{ type: "delete-cell", cellId: action.payload.cellId }];
+
+ // moveCell/sendToTop/sendToBottom → move-cell
+ // All three change a single cell's position. We derive the final
+ // position from newState via anchorOf rather than interpreting the
+ // action's before/direction payload.
+ case "moveCell":
+ case "sendToTop":
+ case "sendToBottom": {
+ const { cellId } = action.payload;
+ return [
+ {
+ type: "move-cell",
+ cellId: cellId,
+ ...anchorOf(cellId, newState),
+ },
+ ];
+ }
+
+ // dropCellOverCell/dropCellOverColumn → set-config + reorder-cells
+ // Drag-and-drop reorders can move cells within or across columns.
+ // We emit config changes for cells whose column changed, then
+ // the full ordering.
+ case "dropCellOverCell":
+ case "dropCellOverColumn":
+ return columnChanges(prevState, newState);
+
+ // updateCellCode → set-code
+ // Reads the code from newState via getCell.
+ case "updateCellCode": {
+ const cell = getCell(action.payload.cellId, newState);
+ if (!cell) {
+ return [];
+ }
+ return [
+ {
+ type: "set-code",
+ cellId: cell.id,
+ code: cell.code,
+ },
+ ];
+ }
+
+ // updateCellName → set-name
+ // Reads the name from newState via getCell.
+ case "updateCellName": {
+ const cell = getCell(action.payload.cellId, newState);
+ if (!cell) {
+ return [];
+ }
+ return [
+ {
+ type: "set-name",
+ cellId: cell.id,
+ name: cell.name,
+ },
+ ];
+ }
+
+ // updateCellConfig → set-config
+ // Maps CellConfig's snake_case hide_code to the change's camelCase hideCode.
+ // Only includes fields that were actually specified in the partial config
+ // (from the action payload, not the full cell config).
+ case "updateCellConfig": {
+ const { cellId, config } = action.payload;
+ return [
+ {
+ type: "set-config",
+ cellId: cellId,
+ ...(config.hide_code != null && { hideCode: config.hide_code }),
+ ...(config.disabled != null && { disabled: config.disabled }),
+ ...(config.column != null && { column: config.column }),
+ },
+ ];
+ }
+
+ // Column structure changes → set-config + reorder-cells
+ // All of these change column layout. We emit config changes for
+ // cells whose column index changed, then the full ordering.
+ case "dropOverNewColumn":
+ case "moveColumn":
+ case "addColumnBreakpoint":
+ case "deleteColumn":
+ case "mergeAllColumns":
+ case "compactColumns":
+ return columnChanges(prevState, newState);
+
+ // addColumn creates a new column with a new empty cell.
+ // Emits create-cell for the new cell plus column layout changes.
+ case "addColumn":
+ return [
+ ...newCellChanges(prevState, newState),
+ ...columnChanges(prevState, newState),
+ ];
+
+ // undoDeleteCell restores a deleted cell from history.
+ case "undoDeleteCell": {
+ const changes = newCellChanges(prevState, newState);
+ const colChanges = columnChanges(prevState, newState);
+ // Only include column changes if layout actually changed
+ // (colChanges always has at least a reorder-cells change)
+ return colChanges.length > 1 ? [...changes, ...colChanges] : changes;
+ }
+
+ // splitCell: original cell gets truncated code, new cell gets remainder.
+ case "splitCell": {
+ const { cellId } = action.payload;
+ const cell = getCell(cellId, newState);
+ if (!cell) {
+ return [];
+ }
+ return [
+ { type: "set-code", cellId, code: cell.code },
+ ...newCellChanges(prevState, newState),
+ ];
+ }
+
+ // undoSplitCell: merge next cell back into current, delete the next cell.
+ case "undoSplitCell": {
+ const { cellId } = action.payload;
+ const cell = getCell(cellId, newState);
+ if (!cell) {
+ return [];
+ }
+ return [
+ { type: "set-code", cellId, code: cell.code },
+ ...deletedCellChanges(prevState, newState),
+ ];
+ }
+
+ // moveToNextCell: may create a new cell at boundary.
+ case "moveToNextCell":
+ return newCellChanges(prevState, newState);
+
+ // addSetupCellIfDoesntExist: creates setup cell if missing.
+ case "addSetupCellIfDoesntExist":
+ return newCellChanges(prevState, newState);
+
+ // UI-only actions — no document changes.
+ case "focusCell":
+ case "focusTopCell":
+ case "focusBottomCell":
+ case "scrollToTarget":
+ case "showCellIfHidden":
+ case "markTouched":
+ case "markUntouched":
+ return [];
+
+ // Kernel/runtime state — never produces document changes.
+ case "prepareForRun":
+ case "handleCellMessage":
+ case "setCellIds":
+ case "setCellCodes":
+ case "setCells":
+ case "setStdinResponse":
+ case "clearSerializedEditorState":
+ case "clearCellOutput":
+ case "clearCellConsoleOutput":
+ case "clearAllCellOutputs":
+ case "clearLogs":
+ return [];
+
+ // Editor UI state — no document changes.
+ case "foldAll":
+ case "unfoldAll":
+ case "collapseCell":
+ case "expandCell":
+ case "collapseAllCells":
+ case "expandAllCells":
+ return [];
+
+ default:
+ assertNever(action);
+ }
+}
+
+// ---------------------------------------------------------------------------
+// fromDocumentChanges: changes → actions
+// ---------------------------------------------------------------------------
+
+/**
+ * Find cell IDs that are both created and deleted in a set of changes.
+ * These cancel out and should be skipped.
+ */
+export function cancelledCellIds(changes: TransactionChange[]): Set<string> {
+ const created = new Set<string>();
+ const deleted = new Set<string>();
+ for (const change of changes) {
+ if (change.type === "create-cell") {
+ created.add(change.cellId);
+ } else if (change.type === "delete-cell") {
+ deleted.add(change.cellId);
+ }
+ }
+ return created.intersection(deleted);
+}
+
+/**
+ * Given document changes (from the server) and the current cell ordering,
+ * return the reducer actions that apply them to frontend state.
+ */
+export function fromDocumentChanges(
+ changes: TransactionChange[],
+ getCurrentCellIds: () => CellId[],
+): CellAction[] {
+ const actions: CellAction[] = [];
+
+ for (const change of changes) {
+ switch (change.type) {
+ // create-cell → createNewCell + updateCellName + updateCellConfig
+ // Translates the change's before/after anchor into createNewCell's
+ // cellId+before pair. The change carries code, name, and a full CellConfig.
+ // createNewCell only accepts hideCode, so name and remaining config
+ // (disabled, column) are applied as separate follow-up actions.
+ case "create-cell": {
+ let cellId: CellId | "__end__" = "__end__";
+ let before = false;
+ if (change.after) {
+ cellId = change.after;
+ before = false;
+ } else if (change.before) {
+ cellId = change.before;
+ before = true;
+ }
+ actions.push({
+ type: "createNewCell",
+ payload: {
+ cellId,
+ before,
+ code: change.code,
+ newCellId: change.cellId as CellId,
+ autoFocus: false,
+ hideCode: change.config?.hide_code ?? false,
+ },
+ });
+ if (change.name) {
+ actions.push({
+ type: "updateCellName",
+ payload: { cellId: change.cellId as CellId, name: change.name },
+ });
+ }
+ if (change.config?.disabled != null || change.config?.column != null) {
+ actions.push({
+ type: "updateCellConfig",
+ payload: {
+ cellId: change.cellId as CellId,
+ config: {
+ ...(change.config.disabled != null && {
+ disabled: change.config.disabled,
+ }),
+ ...(change.config.column != null && {
+ column: change.config.column,
+ }),
+ },
+ },
+ });
+ }
+ break;
+ }
+
+ // delete-cell → deleteCell
+ // Direct 1:1 mapping.
+ case "delete-cell":
+ actions.push({
+ type: "deleteCell",
+ payload: { cellId: change.cellId as CellId },
+ });
+ break;
+
+ // move-cell → setCellIds
+ // Reconstructs the full ordering by splicing the cell out and
+ // reinserting it relative to the before/after anchor. Falls back
+ // to appending (after) or prepending (before) if the anchor is
+ // missing. No-ops if the cell itself doesn't exist.
+ case "move-cell": {
+ const ids = [...getCurrentCellIds()];
+ const cellId = change.cellId as CellId;
+ const idx = ids.indexOf(cellId);
+ if (idx < 0) {
+ break;
+ }
+ ids.splice(idx, 1);
+ if (change.after) {
+ const afterIdx = ids.indexOf(change.after);
+ if (afterIdx >= 0) {
+ ids.splice(afterIdx + 1, 0, cellId);
+ } else {
+ ids.push(cellId);
+ }
+ } else if (change.before) {
+ const beforeIdx = ids.indexOf(change.before);
+ if (beforeIdx >= 0) {
+ ids.splice(beforeIdx, 0, cellId);
+ } else {
+ ids.unshift(cellId);
+ }
+ } else {
+ ids.push(cellId);
+ }
+ actions.push({
+ type: "setCellIds",
+ payload: { cellIds: ids },
+ });
+ break;
+ }
+
+ // reorder-cells → setCellIds
+ // Replaces the full cell ordering. Used for drag-and-drop and
+ // bulk reorders where expressing individual moves is impractical.
+ case "reorder-cells":
+ actions.push({
+ type: "setCellIds",
+ payload: { cellIds: change.cellIds as CellId[] },
+ });
+ break;
+
+ // set-code → setCellCodes
+ // Marks the code as stale (codeIsStale: true) since it came from
+ // an external source and hasn't been executed yet.
+ case "set-code":
+ actions.push({
+ type: "setCellCodes",
+ payload: {
+ ids: [change.cellId as CellId],
+ codes: [change.code],
+ codeIsStale: true,
+ },
+ });
+ break;
+
+ // set-name → updateCellName
+ // Direct 1:1 mapping.
+ case "set-name":
+ actions.push({
+ type: "updateCellName",
+ payload: { cellId: change.cellId as CellId, name: change.name },
+ });
+ break;
+
+ // set-config → updateCellConfig
+ // Maps the change's camelCase hideCode back to CellConfig's snake_case
+ // hide_code. Only includes fields that are non-null (null means
+ // "not specified" on the wire, not "clear the value").
+ case "set-config":
+ actions.push({
+ type: "updateCellConfig",
+ payload: {
+ cellId: change.cellId as CellId,
+ config: {
+ ...(change.hideCode != null && { hide_code: change.hideCode }),
+ ...(change.disabled != null && { disabled: change.disabled }),
+ ...(change.column != null && { column: change.column }),
+ },
+ },
+ });
+ break;
+ }
+ }
+
+ return actions;
+}
+
+// ---------------------------------------------------------------------------
+// Middleware: debounced change dispatch to the server
+// ---------------------------------------------------------------------------
+
+let pendingChanges: DocumentChange[] = [];
+
+const flushChanges = debounce(() => {
+ if (pendingChanges.length === 0) {
+ return;
+ }
+ const changes = pendingChanges;
+ pendingChanges = [];
+ void getRequestClient().sendDocumentTransaction({ changes });
+}, 400);
+
+function enqueue(change: DocumentChange) {
+ if (store.get(kioskModeAtom)) {
+ return;
+ }
+ pendingChanges.push(change);
+ flushChanges();
+}
+
+/**
+ * Middleware for the notebook reducer. Converts actions to document changes
+ * via toDocumentChanges and enqueues them for debounced dispatch.
+ */
+export function documentTransactionMiddleware(
+ prevState: NotebookState,
+ newState: NotebookState,
+ action: CellAction,
+): void {
+ for (const change of toDocumentChanges(prevState, newState, action)) {
+ enqueue(change);
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Apply: dispatch incoming changes as reducer actions
+// ---------------------------------------------------------------------------
+
+/**
+ * Apply document transaction changes to the frontend cell state.
+ *
+ * Each change is applied immediately and in order so that subsequent changes
+ * see the state produced by earlier changes (e.g. move-cell after create-cell).
+ */
+export function applyTransactionChanges(
+ changes: TransactionChange[],
+ actions: CellActions,
+ getCurrentCellIds: () => CellId[],
+): void {
+ const cancelled = cancelledCellIds(changes);
+
+ for (const change of changes) {
+ if (
+ cancelled.size > 0 &&
+ "cellId" in change &&
+ cancelled.has(change.cellId)
+ ) {
+ continue;
+ }
+ for (const action of fromDocumentChanges([change], getCurrentCellIds)) {
+ // @ts-expect-error - TypeScript is not smart enough to know we have correctly mapped type -> payload
+ actions[action.type](action.payload);
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Test helpers
+// ---------------------------------------------------------------------------
+
+export const exportedForTesting = {
+ cancelPendingChanges: () => {
+ flushChanges.cancel();
+ pendingChanges = [];
+ },
+ drainChanges: (): DocumentChange[] => {
+ flushChanges.cancel();
+ const drained = pendingChanges;
+ pendingChanges = [];
+ return drained;
+ },
+};
diff --git a/frontend/src/core/islands/bridge.ts b/frontend/src/core/islands/bridge.ts
index 7cb35d8845..b0038ee909 100644
--- a/frontend/src/core/islands/bridge.ts
+++ b/frontend/src/core/islands/bridge.ts
@@ -163,6 +163,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
saveCellConfig = throwNotImplemented;
sendRestart = throwNotImplemented;
syncCellIds = throwNotImplemented;
+ sendDocumentTransaction = throwNotImplemented;
readCode = throwNotImplemented;
readSnippets = throwNotImplemented;
previewDatasetColumn = throwNotImplemented;
diff --git a/frontend/src/core/islands/main.ts b/frontend/src/core/islands/main.ts
index d8c2b92550..2a5c43d154 100644
--- a/frontend/src/core/islands/main.ts
+++ b/frontend/src/core/islands/main.ts
@@ -196,6 +196,8 @@ export async function initialize() {
return;
case "kernel-startup-error":
return;
+ case "notebook-document-transaction":
+ return;
case "model-lifecycle":
handleWidgetMessage(MODEL_MANAGER, msg.data);
return;
diff --git a/frontend/src/core/network/requests-lazy.ts b/frontend/src/core/network/requests-lazy.ts
index e017d00e53..39b85ccc73 100644
--- a/frontend/src/core/network/requests-lazy.ts
+++ b/frontend/src/core/network/requests-lazy.ts
@@ -119,6 +119,7 @@ const ACTIONS: Record<keyof AllRequests, Action> = {
// Sync operations that wait for connection
syncCellIds: "waitForConnectionOpen",
+ sendDocumentTransaction: "waitForConnectionOpen",
sendCodeCompletionRequest: "waitForConnectionOpen",
};
diff --git a/frontend/src/core/network/requests-network.ts b/frontend/src/core/network/requests-network.ts
index b4bb0f3c60..139866cfbe 100644
--- a/frontend/src/core/network/requests-network.ts
+++ b/frontend/src/core/network/requests-network.ts
@@ -58,6 +58,15 @@ export function createNetworkRequests(): EditRequests & RunRequests {
})
.then(handleResponseReturnNull);
},
+ sendDocumentTransaction: async (request) => {
+ await waitForConnectionOpen();
+ return getClient()
+ .POST("/api/document/transaction", {
+ body: request,
+ params: getParams(),
+ })
+ .then(handleResponseReturnNull);
+ },
sendRename: (request) => {
return getClient()
.POST("/api/kernel/rename", {
diff --git a/frontend/src/core/network/requests-static.ts b/frontend/src/core/network/requests-static.ts
index 4de81be61a..bc56bfea6e 100644
--- a/frontend/src/core/network/requests-static.ts
+++ b/frontend/src/core/network/requests-static.ts
@@ -37,6 +37,7 @@ export function createStaticRequests(): EditRequests & RunRequests {
},
sendRestart: throwNotInEditMode,
syncCellIds: throwNotInEditMode,
+ sendDocumentTransaction: throwNotInEditMode,
sendRun: throwNotInEditMode,
sendRunScratchpad: throwNotInEditMode,
sendRename: throwNotInEditMode,
diff --git a/frontend/src/core/network/requests-toasting.tsx b/frontend/src/core/network/requests-toasting.tsx
index cd74cf5978..d7e0059ab6 100644
--- a/frontend/src/core/network/requests-toasting.tsx
+++ b/frontend/src/core/network/requests-toasting.tsx
@@ -22,6 +22,7 @@ export function createErrorToastingRequests(
sendFunctionRequest: "Failed to send function request",
sendRestart: "Failed to restart",
syncCellIds: "Failed to sync cell IDs",
+ sendDocumentTransaction: "Failed to sync document transaction",
sendRun: "Failed to run",
sendRunScratchpad: "Failed to run scratchpad",
sendRename: "Failed to rename",
diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.ts
index 522e532f6d..226c53ed63 100644
--- a/frontend/src/core/network/types.ts
+++ b/frontend/src/core/network/types.ts
@@ -80,6 +80,8 @@ export interface SetCellConfigRequest {
export type UpdateUIElementRequest = schemas["UpdateUIElementRequest"];
export type ModelRequest = schemas["ModelRequest"];
export type UpdateCellIdsRequest = schemas["UpdateCellIdsRequest"];
+export type NotebookDocumentTransactionRequest =
+ schemas["NotebookDocumentTransactionRequest"];
export type UpdateUserConfigRequest = schemas["UpdateUserConfigRequest"];
export type ShutdownSessionRequest = schemas["ShutdownSessionRequest"];
export type Snippet = schemas["Snippet"];
@@ -138,6 +140,9 @@ export interface EditRequests {
saveCellConfig: (request: SetCellConfigRequest) => Promise<null>;
sendRestart: () => Promise<null>;
syncCellIds: (request: UpdateCellIdsRequest) => Promise<null>;
+ sendDocumentTransaction: (
+ request: NotebookDocumentTransactionRequest,
+ ) => Promise<null>;
sendInstallMissingPackages: (
request: InstallPackagesRequest,
) => Promise<null>;
diff --git a/frontend/src/core/wasm/bridge.ts b/frontend/src/core/wasm/bridge.ts
index fef43c620f..f976da8707 100644
--- a/frontend/src/core/wasm/bridge.ts
+++ b/frontend/src/core/wasm/bridge.ts
@@ -549,6 +549,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
};
syncCellIds = () => Promise.resolve(null);
+ sendDocumentTransaction = () => Promise.resolve(null);
addPackage: EditRequests["addPackage"] = async (request) => {
return this.rpc.proxy.request.addPackage(request);
diff --git a/frontend/src/core/websocket/useMarimoKernelConnection.tsx b/frontend/src/core/websocket/useMarimoKernelConnection.tsx
index d6ce36ac66..2a110a6d4f 100644
--- a/frontend/src/core/websocket/useMarimoKernelConnection.tsx
+++ b/frontend/src/core/websocket/useMarimoKernelConnection.tsx
@@ -5,8 +5,12 @@ import { useRef } from "react";
import { useErrorBoundary } from "react-error-boundary";
import { toast } from "@/components/ui/use-toast";
import { getNotebook, useCellActions } from "@/core/cells/cells";
+import { applyTransactionChanges } from "@/core/cells/document-changes";
import { AUTOCOMPLETER } from "@/core/codemirror/completion/Autocompleter";
-import type { NotificationPayload } from "@/core/kernel/messages";
+import type {
+ NotificationMessageData,
+ NotificationPayload,
+} from "@/core/kernel/messages";
import { useConnectionTransport } from "@/core/websocket/useWebSocket";
import { renderHTML } from "@/plugins/core/RenderHTML";
import {
@@ -93,6 +97,17 @@ export function useMarimoKernelConnection(opts: {
const { showBoundary } = useErrorBoundary();
const { handleCellMessage, setCellCodes, setCellIds } = useCellActions();
+ const actionsWithoutMiddleware = useCellActions({ skipMiddleware: true });
+
+ const handleDocumentTransaction = (
+ transaction: NotificationMessageData<"notebook-document-transaction">["transaction"],
+ ) => {
+ applyTransactionChanges(
+ transaction.changes,
+ actionsWithoutMiddleware,
+ () => getNotebook().cellIds.inOrderIds,
+ );
+ };
const { addCellNotification } = useRunsActions();
const setKernelState = useSetAtom(kernelStateAtom);
const setAppConfig = useSetAppConfig();
@@ -321,6 +336,9 @@ export function useMarimoKernelConnection(opts: {
case "update-cell-ids":
setCellIds({ cellIds: msg.data.cell_ids });
return;
+ case "notebook-document-transaction":
+ handleDocumentTransaction(msg.data.transaction);
+ return;
default:
logNever(msg.data);
}
diff --git a/frontend/src/utils/createReducer.ts b/frontend/src/utils/createReducer.ts
index fb4f4cb049..9e2134b97a 100644
--- a/frontend/src/utils/createReducer.ts
+++ b/frontend/src/utils/createReducer.ts
@@ -27,6 +27,13 @@ type ReducerActions<RH extends ReducerHandlers<any>> = {
: never;
};
+/** Helper for typing middleware that receives dispatched actions. */
+export type DispatchedActionOf<T> = {
+ [Key in keyof T]: T[Key] extends (payload: infer P) => any
+ ? { type: Key; payload: P }
+ : never;
+}[keyof T & string];
+
export interface ReducerCreatorResult<
State,
RH extends ReducerHandlers<State>,
@@ -80,21 +87,20 @@ export function createReducerAndAtoms<
State,
RH extends ReducerHandlers<NoInfer<State>>,
>(initialState: () => State, reducers: RH, middleware?: Middleware<State>[]) {
+ const allMiddleware = [...(middleware ?? [])];
+ const addMiddleware = (mw: Middleware<State>) => {
+ allMiddleware.push(mw);
+ };
const { reducer, createActions } = createReducer(initialState, reducers);
const reducerWithMiddleware = (state: State, action: ReducerAction<any>) => {
try {
const newState = reducer(state, action);
- if (middleware) {
- for (const mw of middleware) {
- try {
- mw(state, newState, action);
- } catch (error) {
- Logger.error(
- `Error in middleware for action ${action.type}:`,
- error,
- );
- }
+ for (const mw of allMiddleware) {
+ try {
+ mw(state, newState, action);
+ } catch (error) {
+ Logger.error(`Error in middleware for action ${action.type}:`, error);
}
}
return newState;
@@ -108,9 +114,17 @@ export function createReducerAndAtoms<
// map of SetAtom => Actions
const actionsMap = new WeakMap();
- function useActions(): ReducerActions<RH> {
+ function useActions(
+ options: { skipMiddleware?: boolean } = {},
+ ): ReducerActions<RH> {
const setState = useSetAtom(valueAtom);
+ if (options.skipMiddleware === true) {
+ return createActions((action: ReducerAction<any>) => {
+ setState((state: State) => reducer(state, action));
+ });
+ }
+
if (!actionsMap.has(setState)) {
actionsMap.set(
setState,
@@ -126,6 +140,7 @@ export function createReducerAndAtoms<
return {
reducer: reducerWithMiddleware,
+ addMiddleware,
createActions,
valueAtom,
useActions,
diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.py
index a5488d041f..2d1928d655 100644
--- a/marimo/_cli/development/commands.py
+++ b/marimo/_cli/development/commands.py
@@ -432,6 +432,7 @@ def _generate_server_api_schema() -> dict[str, Any]:
models.SuccessResponse,
models.UpdateCellConfigRequest,
models.UpdateCellIdsRequest,
+ models.NotebookDocumentTransactionRequest,
models.FocusCellRequest,
models.UpdateUIElementValuesRequest,
models.UpdateUIElementRequest,
diff --git a/marimo/_code_mode/__init__.py b/marimo/_code_mode/__init__.py
index bb321c2a77..dfbbadd536 100644
--- a/marimo/_code_mode/__init__.py
+++ b/marimo/_code_mode/__init__.py
@@ -34,12 +34,12 @@ from __future__ import annotations
from marimo._code_mode._context import (
AsyncCodeModeContext,
- NotebookCellData,
get_context,
)
+from marimo._messaging.notebook.document import NotebookCell
__all__ = [
"AsyncCodeModeContext",
- "NotebookCellData",
+ "NotebookCell",
"get_context",
]
diff --git a/marimo/_code_mode/_context.py b/marimo/_code_mode/_context.py
index 7492c606aa..c5ef494dae 100644
--- a/marimo/_code_mode/_context.py
+++ b/marimo/_code_mode/_context.py
@@ -24,9 +24,7 @@ Usage::
from __future__ import annotations
import sys
-from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, overload
-from uuid import uuid4
from marimo import _loggers
from marimo._ast.cell import CellConfig, CellImpl
@@ -43,10 +41,21 @@ from marimo._code_mode._plan import (
_UpdateOp,
_validate_ops,
)
+from marimo._messaging.notebook.changes import (
+ CreateCell,
+ DeleteCell,
+ DocumentChange,
+ ReorderCells,
+ SetCode,
+ SetConfig,
+ SetName,
+ Transaction,
+)
+from marimo._messaging.notebook.document import NotebookCell, NotebookDocument
from marimo._messaging.notification import (
+ NotebookDocumentTransactionNotification,
Notification,
UpdateCellCodesNotification,
- UpdateCellIdsNotification,
)
from marimo._messaging.notification_utils import broadcast_notification
from marimo._runtime.commands import (
@@ -71,29 +80,9 @@ if TYPE_CHECKING:
from marimo._runtime.runtime import Kernel
-# ------------------------------------------------------------------
-# Data types
-# ------------------------------------------------------------------
-
-
-@dataclass(frozen=True)
-class NotebookCellData:
- """Read-only snapshot of a notebook cell (returned by ``ctx.cells[...]``)."""
-
- code: str | None = None
- config: CellConfig | None = None
- id: CellId_t = field(default_factory=lambda: CellId_t(str(uuid4())))
- name: str | None = field(default=None, repr=True, compare=False)
-
-
LOGGER = _loggers.marimo_logger()
-# Module-level store for cell names set via code_mode.
-# Persists across context manager invocations within the same kernel.
-_cell_names: dict[CellId_t, str] = {}
-
-
# ------------------------------------------------------------------
# Entry point
# ------------------------------------------------------------------
@@ -143,77 +132,56 @@ class _CellsView:
for cid, cell in ctx.cells.items():
...
ctx.cells.keys() # list of CellId_t
- ctx.cells.values() # list of NotebookCellData
+ ctx.cells.values() # list of NotebookCell
"my_cell" in ctx.cells # membership test
"""
def __init__(self, ctx: AsyncCodeModeContext) -> None:
self._ctx = ctx
+ @property
+ def _doc(self) -> NotebookDocument:
+ return self._ctx._document
+
def _cell_ids(self) -> list[CellId_t]:
- return list(self._ctx.graph.cells.keys())
+ return list(self._doc)
def _cell_name(self, cell_id: CellId_t) -> str | None:
- # Check code_mode's own name store first.
- name = _cell_names.get(cell_id)
- if name is not None:
- return name
- # Fall back to cell_manager if available.
- cm = self._ctx._cell_manager
- if cm is None:
+ doc_cell = self._doc.get(cell_id)
+ if doc_cell is None:
return None
- data = cm.get_cell_data(cell_id)
- return data.name if data else None
-
- def _build_at(self, cell_id: CellId_t) -> NotebookCellData:
- cell_impl = self._ctx.graph.cells[cell_id]
- meta = self._ctx._kernel.cell_metadata.get(cell_id)
- return NotebookCellData(
- code=cell_impl.code,
- config=meta.config if meta else CellConfig(),
- name=self._cell_name(cell_id),
- id=cell_id,
- )
+ return doc_cell.name or None
def _resolve(self, target: str) -> CellId_t:
"""Resolve a cell ID or cell name to a ``CellId_t``.
Raises ``KeyError`` if not found.
"""
- cell_ids = self._cell_ids()
-
- # Try cell ID first.
- cell_id_key = CellId_t(target)
- for cid in cell_ids:
- if cid == cell_id_key:
- return cid
+ if target in self._doc:
+ return CellId_t(target)
# Fall back to cell name.
- for cid in cell_ids:
- name = self._cell_name(cid)
- if name == target:
- return cid
+ for cell in self._doc.cells:
+ if cell.name == target:
+ return cell.id
raise KeyError(target)
def __len__(self) -> int:
- return len(self._ctx.graph.cells)
+ return len(self._doc)
@overload
- def __getitem__(self, key: int) -> NotebookCellData: ...
+ def __getitem__(self, key: int) -> NotebookCell: ...
@overload
- def __getitem__(self, key: str) -> NotebookCellData: ...
-
- def __getitem__(self, key: int | str) -> NotebookCellData:
- cell_ids = self._cell_ids()
+ def __getitem__(self, key: str) -> NotebookCell: ...
+ def __getitem__(self, key: int | str) -> NotebookCell:
if isinstance(key, int):
- return self._build_at(cell_ids[key])
-
- return self._build_at(self._resolve(key))
+ return self._doc.cells[key]
+ return self._doc.get_cell(self._resolve(key))
def __iter__(self) -> Iterator[CellId_t]:
- yield from self._cell_ids()
+ yield from self._doc
def __contains__(self, key: object) -> bool:
if isinstance(key, int):
@@ -228,15 +196,15 @@ class _CellsView:
def keys(self) -> list[CellId_t]:
"""Return cell IDs in notebook order."""
- return self._cell_ids()
+ return self._doc.cell_ids
- def values(self) -> list[NotebookCellData]:
+ def values(self) -> list[NotebookCell]:
"""Return cell data in notebook order."""
- return [self._build_at(cid) for cid in self._cell_ids()]
+ return self._doc.cells
- def items(self) -> list[tuple[CellId_t, NotebookCellData]]:
+ def items(self) -> list[tuple[CellId_t, NotebookCell]]:
"""Return (cell_id, cell_data) pairs in notebook order."""
- return [(cid, self._build_at(cid)) for cid in self._cell_ids()]
+ return [(c.id, c) for c in self._doc.cells]
# ------------------------------------------------------------------
@@ -266,7 +234,17 @@ class AsyncCodeModeContext:
*,
skip_validation: bool = False,
) -> None:
+ from marimo._messaging.notebook.document import get_current_document
+
+ document = get_current_document()
+ if document is None:
+ raise RuntimeError(
+ "NotebookDocument not available — code_mode must be invoked "
+ "via the /api/execute endpoint which sets the document "
+ "context variable"
+ )
self._kernel = kernel
+ self._document = document
self._cell_manager = cell_manager
self._skip_validation = skip_validation
self._ops: list[_Op] = []
@@ -428,16 +406,9 @@ class AsyncCodeModeContext:
def _cell_label(self, cell_id: CellId_t) -> str:
"""Return a display label: ``'id' (name)`` or ``'id'``."""
short = repr(str(cell_id)[:8])
- name: str | None = None
- cm = self._cell_manager
- if cm is not None:
- data = cm.get_cell_data(cell_id)
- if data and data.name:
- name = data.name
- if name is None:
- name = _cell_names.get(cell_id)
- if name:
- return f"{short} ({name})"
+ doc_cell = self._document.get(cell_id)
+ if doc_cell and doc_cell.name:
+ return f"{short} ({doc_cell.name})"
return short
# ------------------------------------------------------------------
@@ -982,90 +953,29 @@ class AsyncCodeModeContext:
self.graph.cells[cell_id].configure(cfg.asdict())
self._kernel.cell_metadata[cell_id] = CellMetadata(config=cfg)
- # Persist names from ops into the module-level store.
- for op in ops:
- op_name = getattr(op, "name", None)
- if op_name is not None:
- target_id = getattr(op, "new_cell_id", None) or op.cell_id
- _cell_names[target_id] = op_name
- # Clean up stale entry when cell_id was migrated.
- if (
- getattr(op, "new_cell_id", None) is not None
- and op.cell_id in _cell_names
- ):
- del _cell_names[op.cell_id]
-
- # Notify frontend of all changes (code and config-only).
- # Cells not queued for execution are marked as stale.
- # Config-only changes are never stale (the code didn't change).
- #
- # In autorun mode, when the caller explicitly ran at least one
- # cell, also include cells_to_run from mutate_graph (reactive
- # descendants) so the agent sees their execution synchronously
- # and the frontend isn't left showing stale for cells that are
- # about to execute. We only expand when explicit_run is
- # non-empty to preserve the "suggestion" behavior: creating
- # cells without run_cell leaves them stale/unexecuted.
- _run_set = explicit_run or set()
- if _run_set and self._kernel.reactive_execution_mode == "autorun":
- _run_set = _run_set | cells_to_run
- _code_entry_ids = {e.cell_id for e in code_entries}
- all_entries = code_entries + config_entries
- by_stale: dict[bool, list[_PlanEntry]] = {}
- for entry in all_entries:
- is_stale = (
- entry.cell_id in _code_entry_ids
- and entry.cell_id not in _run_set
- )
- by_stale.setdefault(is_stale, []).append(entry)
-
- for is_stale, entries in by_stale.items():
- names = [_cell_names.get(e.cell_id, "") for e in entries]
- codes = [
- e.code
- if e.code is not None
- else self.graph.cells[e.cell_id].code
- for e in entries
- ]
- kwargs: dict[str, Any] = {}
- if any(names):
- kwargs["names"] = names
- self.notify(
- UpdateCellCodesNotification(
- cell_ids=[e.cell_id for e in entries],
- codes=codes,
- code_is_stale=is_stale,
- configs=[resolved_configs[e.cell_id] for e in entries],
- **kwargs,
- )
- )
-
- # For name-only updates (no code change), send a notification
- # with existing code so the frontend picks up the new name.
- name_only = {
- cid: n
- for cid, n in _cell_names.items()
- if cid not in {e.cell_id for e in code_entries}
- and cid in self.graph.cells
- and any(
- getattr(op, "name", None) is not None and op.cell_id == cid
- for op in ops
- )
- }
- if name_only:
+ # Build document transaction ops from the plan and broadcast
+ # a single NotebookDocumentTransactionNotification instead of
+ # the legacy UpdateCellCodes / UpdateCellIds notifications.
+ doc_ops = _plan_to_document_ops(
+ plan=plan,
+ existing_ids=existing_id_set,
+ existing_code=existing_code,
+ resolved_configs=resolved_configs,
+ internal_ops=ops,
+ )
+ if doc_ops:
+ tx = Transaction(changes=tuple(doc_ops), source="kernel")
+ # Apply to local snapshot so _cell_label can read names.
+ self._document.apply(tx)
self.notify(
- UpdateCellCodesNotification(
- cell_ids=list(name_only.keys()),
- codes=[self.graph.cells[cid].code for cid in name_only],
- code_is_stale=False,
- names=list(name_only.values()),
- )
+ NotebookDocumentTransactionNotification(transaction=tx)
)
- self.notify(UpdateCellIdsNotification(cell_ids=target_order))
-
# Run queued cells (explicit run_cell + autorun descendants),
# filtered to cells that still exist after structural ops.
+ _run_set = explicit_run or set()
+ if _run_set and self._kernel.reactive_execution_mode == "autorun":
+ _run_set = _run_set | cells_to_run
if _run_set:
cells_to_run = _run_set & set(self.graph.cells.keys())
if cells_to_run:
@@ -1189,3 +1099,76 @@ class AsyncCodeModeContext:
def notify(self, notification: Notification) -> None:
"""Send a notification to the frontend."""
broadcast_notification(notification, stream=self._kernel.stream) # type: ignore[arg-type]
+
+
+# ------------------------------------------------------------------
+# Plan → Document Ops conversion
+# ------------------------------------------------------------------
+
+
+def _plan_to_document_ops(
+ plan: list[_PlanEntry],
+ existing_ids: set[CellId_t],
+ existing_code: dict[CellId_t, str],
+ resolved_configs: dict[CellId_t, CellConfig],
+ internal_ops: list[_Op],
+) -> list[DocumentChange]:
+ """Convert a resolved plan diff into NotebookDocument changes."""
+ doc_ops: list[DocumentChange] = []
+ plan_ids = {e.cell_id for e in plan}
+
+ # Deletions: cells present before but absent from the plan.
+ for cid in sorted(existing_ids):
+ if cid not in plan_ids:
+ doc_ops.append(DeleteCell(cell_id=cid))
+
+ # Creations and property updates.
+ for entry in plan:
+ if entry.cell_id not in existing_ids:
+ # New cell.
+ cfg = resolved_configs.get(entry.cell_id, CellConfig())
+ doc_ops.append(
+ CreateCell(
+ cell_id=entry.cell_id,
+ code=entry.code or "",
+ name=entry.name or "",
+ config=cfg,
+ )
+ )
+ else:
+ # Existing cell — emit ops for changed properties.
+ if entry.code is not None and entry.code != existing_code.get(
+ entry.cell_id
+ ):
+ doc_ops.append(SetCode(cell_id=entry.cell_id, code=entry.code))
+
+ # Names from internal ops (covers both add and update).
+ for op in internal_ops:
+ op_name = getattr(op, "name", None)
+ if op_name is None:
+ continue
+ target_id = getattr(op, "new_cell_id", None) or op.cell_id
+ # Skip if the cell was just created (name is already in CreateCell).
+ if target_id not in existing_ids:
+ continue
+ doc_ops.append(SetName(cell_id=target_id, name=op_name))
+
+ # Config updates for existing cells.
+ for entry in plan:
+ if entry.cell_id in existing_ids and entry.config is not None:
+ resolved_cfg = resolved_configs.get(entry.cell_id)
+ if resolved_cfg is not None:
+ doc_ops.append(
+ SetConfig(
+ cell_id=entry.cell_id,
+ column=resolved_cfg.column,
+ disabled=resolved_cfg.disabled,
+ hide_code=resolved_cfg.hide_code,
+ )
+ )
+
+ # Final ordering.
+ target_order = tuple(e.cell_id for e in plan)
+ doc_ops.append(ReorderCells(cell_ids=target_order))
+
+ return doc_ops
diff --git a/marimo/_messaging/notebook/__init__.py b/marimo/_messaging/notebook/__init__.py
new file mode 100644
index 0000000000..56b5f25fe3
--- /dev/null
+++ b/marimo/_messaging/notebook/__init__.py
@@ -0,0 +1,29 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""Notebook document model — canonical representation of notebook structure."""
+
+from marimo._messaging.notebook.changes import (
+ CreateCell,
+ DeleteCell,
+ DocumentChange,
+ MoveCell,
+ ReorderCells,
+ SetCode,
+ SetConfig,
+ SetName,
+ Transaction,
+)
+from marimo._messaging.notebook.document import NotebookCell, NotebookDocument
+
+__all__ = [
+ "CreateCell",
+ "DeleteCell",
+ "DocumentChange",
+ "MoveCell",
+ "NotebookCell",
+ "NotebookDocument",
+ "ReorderCells",
+ "SetCode",
+ "SetConfig",
+ "SetName",
+ "Transaction",
+]
diff --git a/marimo/_messaging/notebook/changes.py b/marimo/_messaging/notebook/changes.py
new file mode 100644
index 0000000000..c01bfde2ef
--- /dev/null
+++ b/marimo/_messaging/notebook/changes.py
@@ -0,0 +1,106 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""Typed operations and transactions for notebook structural changes."""
+
+from __future__ import annotations
+
+from typing import Optional, Union
+
+import msgspec
+
+from marimo._ast.cell import CellConfig
+from marimo._types.ids import CellId_t
+
+# ------------------------------------------------------------------
+# Structural changes (change the cell list)
+# ------------------------------------------------------------------
+
+
+class CreateCell(
+ msgspec.Struct, frozen=True, tag="create-cell", rename="camel"
+):
+ """Insert a new cell into the notebook."""
+
+ cell_id: CellId_t
+ code: str
+ name: str
+ config: CellConfig
+ before: Optional[CellId_t] = None
+ after: Optional[CellId_t] = None
+
+
+class DeleteCell(
+ msgspec.Struct, frozen=True, tag="delete-cell", rename="camel"
+):
+ """Remove a cell from the notebook."""
+
+ cell_id: CellId_t
+
+
+class MoveCell(msgspec.Struct, frozen=True, tag="move-cell", rename="camel"):
+ """Reposition a cell in the notebook."""
+
+ cell_id: CellId_t
+ before: Optional[CellId_t] = None
+ after: Optional[CellId_t] = None
+
+
+class ReorderCells(
+ msgspec.Struct, frozen=True, tag="reorder-cells", rename="camel"
+):
+ """Replace the full cell ordering.
+
+ Cell IDs present in the document but missing from ``cell_ids``
+ are appended at the end. IDs not in the document are ignored.
+ """
+
+ cell_ids: tuple[CellId_t, ...]
+
+
+# ------------------------------------------------------------------
+# Property changes (change cell content)
+# ------------------------------------------------------------------
+
+
+class SetCode(msgspec.Struct, frozen=True, tag="set-code", rename="camel"):
+ """Replace a cell's source code."""
+
+ cell_id: CellId_t
+ code: str
+
+
+class SetName(msgspec.Struct, frozen=True, tag="set-name", rename="camel"):
+ """Rename a cell."""
+
+ cell_id: CellId_t
+ name: str
+
+
+class SetConfig(msgspec.Struct, frozen=True, tag="set-config", rename="camel"):
+ """Partially update a cell's config. None fields are unchanged."""
+
+ cell_id: CellId_t
+ column: Optional[int] = None
+ disabled: Optional[bool] = None
+ hide_code: Optional[bool] = None
+
+
+DocumentChange = Union[
+ CreateCell, DeleteCell, MoveCell, ReorderCells, SetCode, SetName, SetConfig
+]
+
+# ------------------------------------------------------------------
+# Transaction
+# ------------------------------------------------------------------
+
+
+class Transaction(msgspec.Struct, frozen=True, rename="camel"):
+ """An atomic batch of changes applied to a NotebookDocument.
+
+ ``source`` identifies the writer (e.g. ``"frontend"``, ``"kernel"``).
+ ``version`` is ``None`` when created and stamped by
+ ``NotebookDocument.apply()``.
+ """
+
+ changes: tuple[DocumentChange, ...]
+ source: str
+ version: Optional[int] = None
diff --git a/marimo/_messaging/notebook/document.py b/marimo/_messaging/notebook/document.py
new file mode 100644
index 0000000000..b57cc8100c
--- /dev/null
+++ b/marimo/_messaging/notebook/document.py
@@ -0,0 +1,336 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""Canonical notebook document model.
+
+``NotebookDocument`` maintains an ordered list of ``NotebookCell`` entries and
+applies ``Transaction``s atomically. It is a pure state machine — no IO, no
+notifications, no kernel interaction.
+
+Concurrency model
+-----------------
+The session holds the single ``NotebookDocument`` and applies
+transactions sequentially. There is no concurrent access. Everything
+that goes through this model is last-write-wins with intra-transaction
+conflict detection (``_validate`` catches contradictions like delete +
+update on the same cell within one batch).
+
+``SetCode`` is a wholesale replacement without character-level
+merge. Loro CRDT may handle real-time collaborative text editing in
+the future, but cell code would then live outside this model entirely.
+"""
+
+from __future__ import annotations
+
+from contextlib import contextmanager
+from contextvars import ContextVar
+from typing import TYPE_CHECKING, Optional
+
+from marimo._utils.assert_never import assert_never
+
+if TYPE_CHECKING:
+ from collections.abc import Generator, Iterable, Iterator
+
+import msgspec
+from msgspec.structs import replace as structs_replace
+
+from marimo._ast.cell import CellConfig
+from marimo._messaging.notebook.changes import (
+ CreateCell,
+ DeleteCell,
+ DocumentChange,
+ MoveCell,
+ ReorderCells,
+ SetCode,
+ SetConfig,
+ SetName,
+ Transaction,
+)
+from marimo._types.ids import CellId_t
+
+
+class NotebookCell(msgspec.Struct):
+ """A single cell in the document. Mutable — owned by the document."""
+
+ id: CellId_t
+ code: str
+ name: str
+ config: CellConfig
+
+
+class NotebookDocument:
+ """Ordered collection of cells with transactional updates.
+
+ Usage::
+
+ doc = NotebookDocument(
+ [
+ NotebookCell(CellId_t("a"), "x = 1", "__", CellConfig()),
+ ]
+ )
+ tx = Transaction(
+ changes=(SetCode(CellId_t("a"), "x = 2"),), source="kernel"
+ )
+ applied = doc.apply(tx)
+ assert applied.version == 1
+ assert doc.get_cell(CellId_t("a")).code == "x = 2"
+ """
+
+ def __init__(self, cells: Optional[Iterable[NotebookCell]] = None) -> None:
+ self._cells: list[NotebookCell] = list(cells) if cells else []
+ self._version: int = 0
+
+ # ------------------------------------------------------------------
+ # Read-only accessors
+ # ------------------------------------------------------------------
+
+ @property
+ def cells(self) -> list[NotebookCell]:
+ """Return a shallow copy of the cell list."""
+ return list(self._cells)
+
+ @property
+ def cell_ids(self) -> list[CellId_t]:
+ """Cell IDs in document order."""
+ return [c.id for c in self._cells]
+
+ @property
+ def version(self) -> int:
+ return self._version
+
+ def get_cell(self, cell_id: CellId_t) -> NotebookCell:
+ """Lookup by ID. Raises ``KeyError`` if not found."""
+ for cell in self._cells:
+ if cell.id == cell_id:
+ return cell
+ raise KeyError(f"Cell {cell_id!r} not found in document")
+
+ def get(self, cell_id: CellId_t) -> NotebookCell | None:
+ """Lookup by ID, returning ``None`` if not found."""
+ for cell in self._cells:
+ if cell.id == cell_id:
+ return cell
+ return None
+
+ def __contains__(self, cell_id: object) -> bool:
+ return any(c.id == cell_id for c in self._cells)
+
+ def __len__(self) -> int:
+ return len(self._cells)
+
+ def __iter__(self) -> Iterator[CellId_t]:
+ return (c.id for c in self._cells)
+
+ # ------------------------------------------------------------------
+ # Transaction application
+ # ------------------------------------------------------------------
+
+ def apply(self, tx: Transaction) -> Transaction:
+ """Validate and apply *tx*, return it with ``version`` assigned.
+
+ Raises ``ValueError`` for validation failures and ``KeyError``
+ when a change references a non-existent cell.
+ """
+ if not tx.changes:
+ return structs_replace(tx, version=self._version)
+
+ _validate(tx.changes, self._cells)
+
+ for change in tx.changes:
+ self._apply_change(change)
+
+ self._version += 1
+ return structs_replace(tx, version=self._version)
+
+ def _apply_change(self, change: DocumentChange) -> None:
+ # TODO: refactor to use match/case (min Python is 3.10) once
+ # ruff target-version is bumped from py39.
+ if isinstance(change, CreateCell):
+ cell = NotebookCell(
+ id=change.cell_id,
+ code=change.code,
+ name=change.name,
+ config=change.config,
+ )
+ if change.after is not None:
+ idx = self._find_index(change.after)
+ self._cells.insert(idx + 1, cell)
+ elif change.before is not None:
+ idx = self._find_index(change.before)
+ self._cells.insert(idx, cell)
+ else:
+ self._cells.append(cell)
+
+ elif isinstance(change, DeleteCell):
+ idx = self._find_index(change.cell_id)
+ del self._cells[idx]
+
+ elif isinstance(change, MoveCell):
+ idx = self._find_index(change.cell_id)
+ cell = self._cells.pop(idx)
+ if change.after is not None:
+ target = self._find_index(change.after)
+ self._cells.insert(target + 1, cell)
+ elif change.before is not None:
+ target = self._find_index(change.before)
+ self._cells.insert(target, cell)
+ else:
+ raise ValueError("MoveCell requires 'before' or 'after'")
+
+ elif isinstance(change, ReorderCells):
+ by_id = {c.id: c for c in self._cells}
+ seen: set[CellId_t] = set()
+ reordered: list[NotebookCell] = []
+ for cid in change.cell_ids:
+ if cid in by_id and cid not in seen:
+ reordered.append(by_id[cid])
+ seen.add(cid)
+ # Append any cells not mentioned in the new ordering.
+ for c in self._cells:
+ if c.id not in seen:
+ reordered.append(c)
+ self._cells = reordered
+
+ elif isinstance(change, SetCode):
+ self._find_cell(change.cell_id).code = change.code
+
+ elif isinstance(change, SetName):
+ self._find_cell(change.cell_id).name = change.name
+
+ elif isinstance(change, SetConfig):
+ cell = self._find_cell(change.cell_id)
+ cell.config = CellConfig(
+ column=change.column
+ if change.column is not None
+ else cell.config.column,
+ disabled=change.disabled
+ if change.disabled is not None
+ else cell.config.disabled,
+ hide_code=change.hide_code
+ if change.hide_code is not None
+ else cell.config.hide_code,
+ )
+ else:
+ assert_never(change)
+
+ # ------------------------------------------------------------------
+ # Helpers
+ # ------------------------------------------------------------------
+
+ def _find_index(self, cell_id: CellId_t) -> int:
+ for i, cell in enumerate(self._cells):
+ if cell.id == cell_id:
+ return i
+ raise KeyError(f"Cell {cell_id!r} not found in document")
+
+ def _find_cell(self, cell_id: CellId_t) -> NotebookCell:
+ for cell in self._cells:
+ if cell.id == cell_id:
+ return cell
+ raise KeyError(f"Cell {cell_id!r} not found in document")
+
+ def __repr__(self) -> str:
+ lines = [f"NotebookDocument({len(self._cells)} cells):"]
+ for i, c in enumerate(self._cells):
+ code_preview = c.code[:40].replace("\n", "\\n")
+ lines.append(f" {i}: {c.id} {code_preview!r}")
+ return "\n".join(lines)
+
+
+# ------------------------------------------------------------------
+# Context variable
+# ------------------------------------------------------------------
+
+#: Document snapshot for the current scratchpad execution. Set by the
+#: kernel before running code_mode so ``AsyncCodeModeContext`` can read
+#: cell ordering, code, names, and configs without the kernel carrying
+#: mutable document state.
+_current_document: ContextVar[NotebookDocument | None] = ContextVar(
+ "_current_document", default=None
+)
+
+
+def get_current_document() -> NotebookDocument | None:
+ """Return the document for the current execution, if any."""
+ return _current_document.get()
+
+
+@contextmanager
+def notebook_document_context(
+ doc: NotebookDocument | None,
+) -> Generator[None, None, None]:
+ """Context manager for setting and resetting the current document."""
+ token = _current_document.set(doc)
+ try:
+ yield
+ finally:
+ _current_document.reset(token)
+
+
+# ------------------------------------------------------------------
+# Validation
+# ------------------------------------------------------------------
+
+
+def _validate(
+ changes: tuple[DocumentChange, ...], cells: list[NotebookCell]
+) -> None:
+ """Check for conflicting changes. Raises ``ValueError``."""
+ existing_ids = {c.id for c in cells}
+ created: set[CellId_t] = set()
+ deleted: set[CellId_t] = set()
+ updated: set[CellId_t] = set()
+ moved: set[CellId_t] = set()
+
+ for change in changes:
+ if isinstance(change, CreateCell):
+ if change.cell_id in existing_ids or change.cell_id in created:
+ raise ValueError(f"Cell {change.cell_id!r} already exists")
+ if change.before is not None and change.after is not None:
+ raise ValueError(
+ "CreateCell cannot specify both 'before' and 'after'"
+ )
+ created.add(change.cell_id)
+
+ elif isinstance(change, DeleteCell):
+ if change.cell_id in deleted:
+ raise ValueError(
+ f"Cell {change.cell_id!r} is deleted more than once"
+ )
+ if change.cell_id in updated:
+ raise ValueError(
+ f"Cannot delete cell {change.cell_id!r} that is also "
+ f"updated in the same transaction"
+ )
+ if change.cell_id in moved:
+ raise ValueError(
+ f"Cannot delete cell {change.cell_id!r} that is also "
+ f"moved in the same transaction"
+ )
+ deleted.add(change.cell_id)
+
+ elif isinstance(change, MoveCell):
+ if change.cell_id in deleted:
+ raise ValueError(
+ f"Cannot move cell {change.cell_id!r} that is also "
+ f"deleted in the same transaction"
+ )
+ if change.before is not None and change.after is not None:
+ raise ValueError(
+ "MoveCell cannot specify both 'before' and 'after'"
+ )
+ if change.before is None and change.after is None:
+ raise ValueError("MoveCell requires 'before' or 'after'")
+ moved.add(change.cell_id)
+
+ elif isinstance(change, ReorderCells):
+ pass # No conflicts — replaces full ordering
+
+ elif isinstance(change, (SetCode, SetName, SetConfig)):
+ if change.cell_id in deleted:
+ raise ValueError(
+ f"Cannot update cell {change.cell_id!r} that is also "
+ f"deleted in the same transaction"
+ )
+ updated.add(change.cell_id)
+
+ else:
+ raise TypeError(f"Unknown change type: {type(change)!r}")
diff --git a/marimo/_messaging/notification.py b/marimo/_messaging/notification.py
index 94fb16d71d..97e1b8779f 100644
--- a/marimo/_messaging/notification.py
+++ b/marimo/_messaging/notification.py
@@ -31,6 +31,7 @@ from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.cell_output import CellOutput
from marimo._messaging.completion_option import CompletionOption
from marimo._messaging.context import RUN_ID_CTX, RunId_t
+from marimo._messaging.notebook.changes import Transaction
from marimo._plugins.core.web_component import JSONType
from marimo._runtime.layout.layout import LayoutConfig
from marimo._secrets.models import SecretKeysWithProvider
@@ -785,6 +786,19 @@ class UpdateCellIdsNotification(Notification, tag="update-cell-ids"):
cell_ids: list[CellId_t]
+class NotebookDocumentTransactionNotification(
+ Notification, tag="notebook-document-transaction"
+):
+ """Broadcasts an applied transaction to the frontend.
+
+ Sent by the session when the document changes (from any source).
+ The frontend applies the ops to update its local state.
+ """
+
+ name: ClassVar[str] = "notebook-document-transaction"
+ transaction: Transaction
+
+
NotificationMessage = Union[
# Cell operations
CellNotification,
@@ -835,4 +849,6 @@ NotificationMessage = Union[
FocusCellNotification,
UpdateCellCodesNotification,
UpdateCellIdsNotification,
+ # Document
+ NotebookDocumentTransactionNotification,
]
diff --git a/marimo/_messaging/serde.py b/marimo/_messaging/serde.py
index a66f491bf6..5766284b66 100644
--- a/marimo/_messaging/serde.py
+++ b/marimo/_messaging/serde.py
@@ -41,3 +41,18 @@ def deserialize_kernel_notification_name(message: KernelMessage) -> str:
"""
# We use the _NotificationName type to deserialize the message because it is slimmer than NotificationMessage
return msgspec.json.decode(message, strict=True, type=_NotificationName).op
+
+
+def try_deserialize_kernel_notification_name(
+ message: KernelMessage,
+) -> str | None:
+ """
+ Try to deserialize a KernelMessage to a NotificationMessage name.
+ """
+ # We use the _NotificationName type to deserialize the message because it is slimmer than NotificationMessage
+ try:
+ return msgspec.json.decode(
+ message, strict=True, type=_NotificationName
+ ).op
+ except msgspec.DecodeError:
+ return None
diff --git a/marimo/_runtime/commands.py b/marimo/_runtime/commands.py
index cde38d176d..5db2cad6ff 100644
--- a/marimo/_runtime/commands.py
+++ b/marimo/_runtime/commands.py
@@ -22,6 +22,7 @@ from marimo import _loggers
from marimo._ast.app_config import _AppConfig
from marimo._config.config import MarimoConfig
from marimo._data.models import DataTableSource
+from marimo._messaging.notebook.document import NotebookCell
from marimo._types.ids import CellId_t, RequestId, UIElementId, WidgetModelId
LOGGER = _loggers.marimo_logger()
@@ -325,11 +326,16 @@ class ExecuteScratchpadCommand(Command):
Attributes:
code: Python code to execute.
request: HTTP request context if available.
+ notebook_cells: Snapshot of notebook cells from the session document.
+ Used to populate the document ContextVar so code_mode can read
+ cell ordering, code, names, and configs.
"""
code: str
# incoming request, e.g. from Starlette or FastAPI
request: Optional[HTTPRequest] = None
+ # Document snapshot — set by the execution endpoint from session.document.
+ notebook_cells: Optional[tuple[NotebookCell, ...]] = None
class RenameNotebookCommand(Command):
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index a06b56f861..96744d07c7 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -63,6 +63,10 @@ from marimo._messaging.errors import (
MarimoSyntaxError,
UnknownError,
)
+from marimo._messaging.notebook.document import (
+ NotebookDocument,
+ notebook_document_context,
+)
from marimo._messaging.notification import (
CacheClearedNotification,
CacheInfoNotification,
@@ -2288,7 +2292,15 @@ class Kernel:
async def handle_execute_scratchpad(
request: ExecuteScratchpadCommand,
) -> None:
- with http_request_context(request.request):
+ doc = (
+ NotebookDocument(list(request.notebook_cells))
+ if request.notebook_cells is not None
+ else None
+ )
+ with (
+ notebook_document_context(doc),
+ http_request_context(request.request),
+ ):
await self.run_scratchpad(request.code)
broadcast_notification(CompletedRunNotification())
diff --git a/marimo/_server/api/endpoints/document.py b/marimo/_server/api/endpoints/document.py
new file mode 100644
index 0000000000..324e3452be
--- /dev/null
+++ b/marimo/_server/api/endpoints/document.py
@@ -0,0 +1,62 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from starlette.authentication import requires
+
+from marimo._messaging.notebook.changes import Transaction
+from marimo._messaging.notification import (
+ NotebookDocumentTransactionNotification,
+)
+from marimo._server.api.deps import AppState
+from marimo._server.api.utils import parse_request
+from marimo._server.models.models import (
+ BaseResponse,
+ NotebookDocumentTransactionRequest,
+ SuccessResponse,
+)
+from marimo._server.router import APIRouter
+from marimo._types.ids import ConsumerId
+
+if TYPE_CHECKING:
+ from starlette.requests import Request
+
+router = APIRouter()
+
+
[email protected]("/transaction")
+@requires("edit")
+async def document_transaction(request: Request) -> BaseResponse:
+ """
+ parameters:
+ - in: header
+ name: Marimo-Session-Id
+ schema:
+ type: string
+ required: true
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/NotebookDocumentTransactionRequest"
+ responses:
+ 200:
+ description: Apply a document transaction
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/SuccessResponse"
+ """
+ app_state = AppState(request)
+ body = await parse_request(request, cls=NotebookDocumentTransactionRequest)
+ session = app_state.require_current_session()
+ session_id = app_state.require_current_session_id()
+
+ transaction = Transaction(changes=tuple(body.changes), source="frontend")
+ session.notify(
+ NotebookDocumentTransactionNotification(transaction=transaction),
+ from_consumer_id=ConsumerId(session_id),
+ )
+
+ return SuccessResponse()
diff --git a/marimo/_server/api/endpoints/execution.py b/marimo/_server/api/endpoints/execution.py
index 5e8d2c70a2..e6782bfdbf 100644
--- a/marimo/_server/api/endpoints/execution.py
+++ b/marimo/_server/api/endpoints/execution.py
@@ -302,6 +302,7 @@ async def execute_code(
ExecuteScratchpadCommand(
code=body.code,
request=HTTPRequest.from_request(request),
+ notebook_cells=tuple(session.document.cells),
),
from_consumer_id=None,
)
diff --git a/marimo/_server/api/router.py b/marimo/_server/api/router.py
index 8037a02add..fe942ec421 100644
--- a/marimo/_server/api/router.py
+++ b/marimo/_server/api/router.py
@@ -10,6 +10,7 @@ from marimo._server.api.endpoints.config import router as config_router
from marimo._server.api.endpoints.datasources import (
router as datasources_router,
)
+from marimo._server.api.endpoints.document import router as document_router
from marimo._server.api.endpoints.documentation import (
router as documentation_router,
)
@@ -59,6 +60,9 @@ def build_routes(base_url: str = "") -> list[BaseRoute]:
app_router.include_router(
documentation_router, prefix="/api/documentation", name="documentation"
)
+ app_router.include_router(
+ document_router, prefix="/api/document", name="document"
+ )
app_router.include_router(
datasources_router, prefix="/api/datasources", name="datasources"
)
diff --git a/marimo/_server/models/models.py b/marimo/_server/models/models.py
index 7521cb45bb..f592de5a9a 100644
--- a/marimo/_server/models/models.py
+++ b/marimo/_server/models/models.py
@@ -6,6 +6,7 @@ from typing import Any, Literal, Optional
import msgspec
from marimo._ast.cell import CellConfig
+from marimo._messaging.notebook.changes import DocumentChange
from marimo._runtime.commands import (
ClearCacheCommand,
CodeCompletionCommand,
@@ -242,6 +243,10 @@ class UpdateCellIdsRequest(msgspec.Struct, rename="camel"):
cell_ids: list[CellId_t]
+class NotebookDocumentTransactionRequest(msgspec.Struct, rename="camel"):
+ changes: list[DocumentChange]
+
+
class FocusCellRequest(msgspec.Struct, rename="camel"):
cell_id: CellId_t
diff --git a/marimo/_session/session.py b/marimo/_session/session.py
index 42d3b2dfe1..04db26cccb 100644
--- a/marimo/_session/session.py
+++ b/marimo/_session/session.py
@@ -12,13 +12,20 @@ import contextlib
from typing import TYPE_CHECKING, Optional
from uuid import uuid4
+import msgspec
+
from marimo import _loggers
from marimo._cli.sandbox import SandboxMode
from marimo._config.manager import MarimoConfigManager, ScriptConfigManager
+from marimo._messaging.notebook.document import NotebookCell, NotebookDocument
from marimo._messaging.notification import (
+ NotebookDocumentTransactionNotification,
NotificationMessage,
)
-from marimo._messaging.serde import serialize_kernel_message
+from marimo._messaging.serde import (
+ serialize_kernel_message,
+ try_deserialize_kernel_notification_name,
+)
from marimo._messaging.types import KernelMessage
from marimo._runtime import commands
from marimo._runtime.commands import (
@@ -61,6 +68,7 @@ from marimo._utils.repr import format_repr
if TYPE_CHECKING:
from collections.abc import Iterator, Mapping
+ from marimo._ast.cell_manager import CellManager
from marimo._server.models.models import InstantiateNotebookRequest
from marimo._session.app_host import AppHostContext
@@ -71,6 +79,29 @@ _DEFAULT_TTL_SECONDS = 120
__all__ = ["Session", "SessionImpl"]
+def _document_from_cell_manager(cell_manager: CellManager) -> NotebookDocument:
+ """Build a NotebookDocument from a CellManager's current state.
+
+ TODO: CellManager and NotebookDocument track overlapping state (cell
+ ordering, code, names, configs). Once the document model is wired
+ into all consumers, we should reconcile these — either CellManager
+ wraps a NotebookDocument internally, or it is replaced by a
+ different composition. For now, the document is populated from the
+ cell manager at session startup and the two coexist.
+ """
+ return NotebookDocument(
+ [
+ NotebookCell(
+ id=cd.cell_id,
+ code=cd.code,
+ name=cd.name,
+ config=cd.config,
+ )
+ for cd in cell_manager.cell_data()
+ ]
+ )
+
+
class SessionImpl(Session):
"""A client session.
@@ -230,6 +261,9 @@ class SessionImpl(Session):
self.ttl_seconds = (
ttl_seconds if ttl_seconds is not None else _DEFAULT_TTL_SECONDS
)
+ self.document = _document_from_cell_manager(
+ app_file_manager.app.cell_manager
+ )
self.session_view = SessionView()
self.config_manager = config_manager
self.extensions = extensions
@@ -388,13 +422,45 @@ class SessionImpl(Session):
from_consumer_id: Optional[ConsumerId],
) -> None:
"""Write an operation to the session consumer and the session view."""
+ # Intercept document transactions: apply to session.document
+ # (stamps version), then re-serialize for broadcast.
+ # Kernel notifications arrive as bytes via the stream distributor;
+ # server-side callers (e.g. file-watch) pass typed objects.
+ if isinstance(operation, bytes):
+ name = try_deserialize_kernel_notification_name(operation)
+ if name == NotebookDocumentTransactionNotification.name:
+ try:
+ operation = self._apply_document_transaction(
+ msgspec.json.decode(
+ operation,
+ type=NotebookDocumentTransactionNotification,
+ )
+ )
+ except Exception:
+ LOGGER.warning("Failed to decode document transaction")
+ elif isinstance(operation, NotebookDocumentTransactionNotification):
+ operation = self._apply_document_transaction(operation)
+
if isinstance(operation, bytes):
notification = operation
else:
notification = serialize_kernel_message(operation)
+
self.room.broadcast(notification, except_consumer=from_consumer_id)
self._event_bus.emit_notification_sent(self, notification)
+ def _apply_document_transaction(
+ self,
+ notif: NotebookDocumentTransactionNotification,
+ ) -> NotebookDocumentTransactionNotification:
+ """Apply to session.document, return with version stamped."""
+ try:
+ applied = self.document.apply(notif.transaction)
+ return NotebookDocumentTransactionNotification(transaction=applied)
+ except (ValueError, KeyError):
+ LOGGER.warning("Failed to apply document transaction")
+ return notif
+
def close(self) -> None:
"""
Close the session.
diff --git a/marimo/_session/types.py b/marimo/_session/types.py
index b4ea4a6e7a..3fbd0076ec 100644
--- a/marimo/_session/types.py
+++ b/marimo/_session/types.py
@@ -18,6 +18,7 @@ if TYPE_CHECKING:
from collections.abc import Iterator, Mapping
from marimo._config.manager import MarimoConfigManager
+ from marimo._messaging.notebook.document import NotebookDocument
from marimo._messaging.notification import NotificationMessage
from marimo._messaging.types import KernelMessage
from marimo._runtime import commands
@@ -109,6 +110,7 @@ class Session(Protocol):
initialization_id: str
app_file_manager: AppFileManager
config_manager: MarimoConfigManager
+ document: NotebookDocument
session_view: SessionView
ttl_seconds: int
scratchpad_lock: asyncio.Lock
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index 221df796e7..a0978a8f2d 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -827,6 +827,38 @@ components:
- destination
title: CopyNotebookRequest
type: object
+ CreateCell:
+ description: Insert a new cell into the notebook.
+ properties:
+ after:
+ anyOf:
+ - $ref: '#/components/schemas/CellId'
+ - type: 'null'
+ default: null
+ before:
+ anyOf:
+ - $ref: '#/components/schemas/CellId'
+ - type: 'null'
+ default: null
+ cellId:
+ type: string
+ code:
+ type: string
+ config:
+ $ref: '#/components/schemas/CellConfig'
+ name:
+ type: string
+ type:
+ enum:
+ - create-cell
+ required:
+ - type
+ - cellId
+ - code
+ - name
+ - config
+ title: CreateCell
+ type: object
CreateNotebookCommand:
description: "Instantiate and initialize a notebook.\n\n Sent when a notebook\
\ is first loaded. Contains all cells and initial UI element values.\n\n \
@@ -1219,6 +1251,19 @@ components:
- cellId
title: DebugCellRequest
type: object
+ DeleteCell:
+ description: Remove a cell from the notebook.
+ properties:
+ cellId:
+ type: string
+ type:
+ enum:
+ - delete-cell
+ required:
+ - type
+ - cellId
+ title: DeleteCell
+ type: object
DeleteCellCommand:
description: "Delete a cell from the notebook.\n\n Removes cell from the\
\ dependency graph and cleans up its variables.\n Dependent cells may become\
@@ -1448,10 +1493,20 @@ components:
\ execution environment that doesn't affect\n the notebook's cells or dependencies.\
\ Runs in an isolated cell with a copy\n of the global namespace, useful\
\ for experimentation.\n\n Attributes:\n code: Python code to execute.\n\
- \ request: HTTP request context if available."
+ \ request: HTTP request context if available.\n notebook_cells:\
+ \ Snapshot of notebook cells from the session document.\n Used\
+ \ to populate the document ContextVar so code_mode can read\n cell\
+ \ ordering, code, names, and configs."
properties:
code:
type: string
+ notebookCells:
+ anyOf:
+ - items:
+ $ref: '#/components/schemas/NotebookCell'
+ type: array
+ - type: 'null'
+ default: null
request:
anyOf:
- $ref: '#/components/schemas/HTTPRequest'
@@ -1469,6 +1524,13 @@ components:
properties:
code:
type: string
+ notebookCells:
+ anyOf:
+ - items:
+ $ref: '#/components/schemas/NotebookCell'
+ type: array
+ - type: 'null'
+ default: null
request:
anyOf:
- $ref: '#/components/schemas/HTTPRequest'
@@ -2505,6 +2567,7 @@ components:
- $ref: '#/components/schemas/FocusCellNotification'
- $ref: '#/components/schemas/UpdateCellCodesNotification'
- $ref: '#/components/schemas/UpdateCellIdsNotification'
+ - $ref: '#/components/schemas/NotebookDocumentTransactionNotification'
discriminator:
mapping:
alert: '#/components/schemas/AlertNotification'
@@ -2525,6 +2588,7 @@ components:
kernel-startup-error: '#/components/schemas/KernelStartupErrorNotification'
missing-package-alert: '#/components/schemas/MissingPackageAlertNotification'
model-lifecycle: '#/components/schemas/ModelLifecycleNotification'
+ notebook-document-transaction: '#/components/schemas/NotebookDocumentTransactionNotification'
query-params-append: '#/components/schemas/QueryParamsAppendNotification'
query-params-clear: '#/components/schemas/QueryParamsClearNotification'
query-params-delete: '#/components/schemas/QueryParamsDeleteNotification'
@@ -3314,6 +3378,29 @@ components:
- bufferPaths
title: ModelUpdateMessage
type: object
+ MoveCell:
+ description: Reposition a cell in the notebook.
+ properties:
+ after:
+ anyOf:
+ - $ref: '#/components/schemas/CellId'
+ - type: 'null'
+ default: null
+ before:
+ anyOf:
+ - $ref: '#/components/schemas/CellId'
+ - type: 'null'
+ default: null
+ cellId:
+ type: string
+ type:
+ enum:
+ - move-cell
+ required:
+ - type
+ - cellId
+ title: MoveCell
+ type: object
MultipleDefinitionError:
properties:
cells:
@@ -3331,6 +3418,66 @@ components:
- cells
title: MultipleDefinitionError
type: object
+ NotebookCell:
+ description: "A single cell in the document. Mutable \u2014 owned by the document."
+ properties:
+ code:
+ type: string
+ config:
+ $ref: '#/components/schemas/CellConfig'
+ id:
+ $ref: '#/components/schemas/CellId'
+ name:
+ type: string
+ required:
+ - id
+ - code
+ - name
+ - config
+ title: NotebookCell
+ type: object
+ NotebookDocumentTransactionNotification:
+ description: "Broadcasts an applied transaction to the frontend.\n\n Sent\
+ \ by the session when the document changes (from any source).\n The frontend\
+ \ applies the ops to update its local state."
+ properties:
+ op:
+ enum:
+ - notebook-document-transaction
+ transaction:
+ $ref: '#/components/schemas/Transaction'
+ required:
+ - op
+ - transaction
+ title: NotebookDocumentTransactionNotification
+ type: object
+ NotebookDocumentTransactionRequest:
+ properties:
+ changes:
+ items:
+ anyOf:
+ - $ref: '#/components/schemas/CreateCell'
+ - $ref: '#/components/schemas/DeleteCell'
+ - $ref: '#/components/schemas/MoveCell'
+ - $ref: '#/components/schemas/ReorderCells'
+ - $ref: '#/components/schemas/SetCode'
+ - $ref: '#/components/schemas/SetName'
+ - $ref: '#/components/schemas/SetConfig'
+ discriminator:
+ mapping:
+ create-cell: '#/components/schemas/CreateCell'
+ delete-cell: '#/components/schemas/DeleteCell'
+ move-cell: '#/components/schemas/MoveCell'
+ reorder-cells: '#/components/schemas/ReorderCells'
+ set-code: '#/components/schemas/SetCode'
+ set-config: '#/components/schemas/SetConfig'
+ set-name: '#/components/schemas/SetName'
+ propertyName: type
+ type: array
+ required:
+ - changes
+ title: NotebookDocumentTransactionRequest
+ type: object
OpenAiConfig:
description: "Configuration options for OpenAI or OpenAI-compatible services.\n\
\n **Keys.**\n\n - `api_key`: the OpenAI API key\n - `base_url`:\
@@ -3761,6 +3908,23 @@ components:
- filename
title: RenameNotebookRequest
type: object
+ ReorderCells:
+ description: "Replace the full cell ordering.\n\n Cell IDs present in the\
+ \ document but missing from ``cell_ids``\n are appended at the end. IDs\
+ \ not in the document are ignored."
+ properties:
+ cellIds:
+ items:
+ type: string
+ type: array
+ type:
+ enum:
+ - reorder-cells
+ required:
+ - type
+ - cellIds
+ title: ReorderCells
+ type: object
RequestId:
type: string
RunningNotebooksResponse:
@@ -4119,6 +4283,66 @@ components:
type: object
SessionId:
type: string
+ SetCode:
+ description: Replace a cell's source code.
+ properties:
+ cellId:
+ type: string
+ code:
+ type: string
+ type:
+ enum:
+ - set-code
+ required:
+ - type
+ - cellId
+ - code
+ title: SetCode
+ type: object
+ SetConfig:
+ description: Partially update a cell's config. None fields are unchanged.
+ properties:
+ cellId:
+ type: string
+ column:
+ anyOf:
+ - type: integer
+ - type: 'null'
+ default: null
+ disabled:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ default: null
+ hideCode:
+ anyOf:
+ - type: boolean
+ - type: 'null'
+ default: null
+ type:
+ enum:
+ - set-config
+ required:
+ - type
+ - cellId
+ title: SetConfig
+ type: object
+ SetName:
+ description: Rename a cell.
+ properties:
+ cellId:
+ type: string
+ name:
+ type: string
+ type:
+ enum:
+ - set-name
+ required:
+ - type
+ - cellId
+ - name
+ title: SetName
+ type: object
SetupRootError:
properties:
edges_with_vars:
@@ -4648,6 +4872,44 @@ components:
- mode
title: ToolDefinition
type: object
+ Transaction:
+ description: "An atomic batch of changes applied to a NotebookDocument.\n\n\
+ \ ``source`` identifies the writer (e.g. ``\"frontend\"``, ``\"kernel\"\
+ ``).\n ``version`` is ``None`` when created and stamped by\n ``NotebookDocument.apply()``."
+ properties:
+ changes:
+ items:
+ anyOf:
+ - $ref: '#/components/schemas/CreateCell'
+ - $ref: '#/components/schemas/DeleteCell'
+ - $ref: '#/components/schemas/MoveCell'
+ - $ref: '#/components/schemas/ReorderCells'
+ - $ref: '#/components/schemas/SetCode'
+ - $ref: '#/components/schemas/SetName'
+ - $ref: '#/components/schemas/SetConfig'
+ discriminator:
+ mapping:
+ create-cell: '#/components/schemas/CreateCell'
+ delete-cell: '#/components/schemas/DeleteCell'
+ move-cell: '#/components/schemas/MoveCell'
+ reorder-cells: '#/components/schemas/ReorderCells'
+ set-code: '#/components/schemas/SetCode'
+ set-config: '#/components/schemas/SetConfig'
+ set-name: '#/components/schemas/SetName'
+ propertyName: type
+ type: array
+ source:
+ type: string
+ version:
+ anyOf:
+ - type: integer
+ - type: 'null'
+ default: null
+ required:
+ - changes
+ - source
+ title: Transaction
+ type: object
TyLanguageServerConfig:
description: 'Configuration options for Ty Language Server.
@@ -5444,6 +5706,26 @@ paths:
schema:
$ref: '#/components/schemas/SuccessResponse'
description: Preview a list of tables in an SQL schema
+ /api/document/transaction:
+ post:
+ parameters:
+ - in: header
+ name: Marimo-Session-Id
+ required: true
+ schema:
+ type: string
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/NotebookDocumentTransactionRequest'
+ responses:
+ 200:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/SuccessResponse'
+ description: Apply a document transaction
/api/documentation/snippets:
get:
parameters:
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index 42495a7b53..5c68e20e42 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -530,6 +530,47 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/api/document/transaction": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ post: {
+ parameters: {
+ query?: never;
+ header: {
+ "Marimo-Session-Id": string;
+ };
+ path?: never;
+ cookie?: never;
+ };
+ requestBody?: {
+ content: {
+ "application/json": components["schemas"]["NotebookDocumentTransactionRequest"];
+ };
+ };
+ responses: {
+ /** @description Apply a document transaction */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["SuccessResponse"];
+ };
+ };
+ };
+ };
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/api/documentation/snippets": {
parameters: {
query?: never;
@@ -3741,6 +3782,22 @@ export interface components {
destination: string;
source: string;
};
+ /**
+ * CreateCell
+ * @description Insert a new cell into the notebook.
+ */
+ CreateCell: {
+ /** @default null */
+ after?: components["schemas"]["CellId"] | null;
+ /** @default null */
+ before?: components["schemas"]["CellId"] | null;
+ cellId: string;
+ code: string;
+ config: components["schemas"]["CellConfig"];
+ name: string;
+ /** @enum {unknown} */
+ type: "create-cell";
+ };
/**
* CreateNotebookCommand
* @description Instantiate and initialize a notebook.
@@ -3973,6 +4030,15 @@ export interface components {
/** @default null */
request?: components["schemas"]["HTTPRequest"] | null;
};
+ /**
+ * DeleteCell
+ * @description Remove a cell from the notebook.
+ */
+ DeleteCell: {
+ cellId: string;
+ /** @enum {unknown} */
+ type: "delete-cell";
+ };
/**
* DeleteCellCommand
* @description Delete a cell from the notebook.
@@ -4119,10 +4185,15 @@ export interface components {
* Attributes:
* code: Python code to execute.
* request: HTTP request context if available.
+ * notebook_cells: Snapshot of notebook cells from the session document.
+ * Used to populate the document ContextVar so code_mode can read
+ * cell ordering, code, names, and configs.
*/
ExecuteScratchpadCommand: {
code: string;
/** @default null */
+ notebookCells?: components["schemas"]["NotebookCell"][] | null;
+ /** @default null */
request?: components["schemas"]["HTTPRequest"] | null;
/** @enum {unknown} */
type: "execute-scratchpad";
@@ -4131,6 +4202,8 @@ export interface components {
ExecuteScratchpadRequest: {
code: string;
/** @default null */
+ notebookCells?: components["schemas"]["NotebookCell"][] | null;
+ /** @default null */
request?: components["schemas"]["HTTPRequest"] | null;
};
/**
@@ -4769,7 +4842,8 @@ export interface components {
| components["schemas"]["CacheInfoNotification"]
| components["schemas"]["FocusCellNotification"]
| components["schemas"]["UpdateCellCodesNotification"]
- | components["schemas"]["UpdateCellIdsNotification"];
+ | components["schemas"]["UpdateCellIdsNotification"]
+ | components["schemas"]["NotebookDocumentTransactionNotification"];
};
/**
* LanguageServersConfig
@@ -5203,6 +5277,19 @@ export interface components {
method: "update";
state: Record<string, any>;
};
+ /**
+ * MoveCell
+ * @description Reposition a cell in the notebook.
+ */
+ MoveCell: {
+ /** @default null */
+ after?: components["schemas"]["CellId"] | null;
+ /** @default null */
+ before?: components["schemas"]["CellId"] | null;
+ cellId: string;
+ /** @enum {unknown} */
+ type: "move-cell";
+ };
/** MultipleDefinitionError */
MultipleDefinitionError: {
cells: components["schemas"]["CellId"][];
@@ -5210,6 +5297,40 @@ export interface components {
/** @enum {unknown} */
type: "multiple-defs";
};
+ /**
+ * NotebookCell
+ * @description A single cell in the document. Mutable — owned by the document.
+ */
+ NotebookCell: {
+ code: string;
+ config: components["schemas"]["CellConfig"];
+ id: components["schemas"]["CellId"];
+ name: string;
+ };
+ /**
+ * NotebookDocumentTransactionNotification
+ * @description Broadcasts an applied transaction to the frontend.
+ *
+ * Sent by the session when the document changes (from any source).
+ * The frontend applies the ops to update its local state.
+ */
+ NotebookDocumentTransactionNotification: {
+ /** @enum {unknown} */
+ op: "notebook-document-transaction";
+ transaction: components["schemas"]["Transaction"];
+ };
+ /** NotebookDocumentTransactionRequest */
+ NotebookDocumentTransactionRequest: {
+ changes: (
+ | components["schemas"]["CreateCell"]
+ | components["schemas"]["DeleteCell"]
+ | components["schemas"]["MoveCell"]
+ | components["schemas"]["ReorderCells"]
+ | components["schemas"]["SetCode"]
+ | components["schemas"]["SetName"]
+ | components["schemas"]["SetConfig"]
+ )[];
+ };
/**
* OpenAiConfig
* @description Configuration options for OpenAI or OpenAI-compatible services.
@@ -5503,6 +5624,18 @@ export interface components {
RenameNotebookRequest: {
filename: string;
};
+ /**
+ * ReorderCells
+ * @description Replace the full cell ordering.
+ *
+ * Cell IDs present in the document but missing from ``cell_ids``
+ * are appended at the end. IDs not in the document are ignored.
+ */
+ ReorderCells: {
+ cellIds: string[];
+ /** @enum {unknown} */
+ type: "reorder-cells";
+ };
RequestId: TypedString<"RequestId">;
/** RunningNotebooksResponse */
RunningNotebooksResponse: {
@@ -5724,6 +5857,41 @@ export interface components {
follow_symlink: boolean;
};
SessionId: TypedString<"SessionId">;
+ /**
+ * SetCode
+ * @description Replace a cell's source code.
+ */
+ SetCode: {
+ cellId: string;
+ code: string;
+ /** @enum {unknown} */
+ type: "set-code";
+ };
+ /**
+ * SetConfig
+ * @description Partially update a cell's config. None fields are unchanged.
+ */
+ SetConfig: {
+ cellId: string;
+ /** @default null */
+ column?: number | null;
+ /** @default null */
+ disabled?: boolean | null;
+ /** @default null */
+ hideCode?: boolean | null;
+ /** @enum {unknown} */
+ type: "set-config";
+ };
+ /**
+ * SetName
+ * @description Rename a cell.
+ */
+ SetName: {
+ cellId: string;
+ name: string;
+ /** @enum {unknown} */
+ type: "set-name";
+ };
/** SetupRootError */
SetupRootError: {
edges_with_vars: [string, string[], string][];
@@ -6058,6 +6226,28 @@ export interface components {
/** @enum {unknown} */
source: "backend" | "frontend" | "mcp";
};
+ /**
+ * Transaction
+ * @description An atomic batch of changes applied to a NotebookDocument.
+ *
+ * ``source`` identifies the writer (e.g. ``"frontend"``, ``"kernel"``).
+ * ``version`` is ``None`` when created and stamped by
+ * ``NotebookDocument.apply()``.
+ */
+ Transaction: {
+ changes: (
+ | components["schemas"]["CreateCell"]
+ | components["schemas"]["DeleteCell"]
+ | components["schemas"]["MoveCell"]
+ | components["schemas"]["ReorderCells"]
+ | components["schemas"]["SetCode"]
+ | components["schemas"]["SetName"]
+ | components["schemas"]["SetConfig"]
+ )[];
+ source: string;
+ /** @default null */
+ version?: number | null;
+ };
/**
* TyLanguageServerConfig
* @description Configuration options for Ty Language Server.
diff --git a/tests/_code_mode/test_cells_view.py b/tests/_code_mode/test_cells_view.py
index a1c130ba48..51bee8bde5 100644
--- a/tests/_code_mode/test_cells_view.py
+++ b/tests/_code_mode/test_cells_view.py
@@ -1,9 +1,20 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+from contextlib import contextmanager
+from typing import TYPE_CHECKING
+
import pytest
-from marimo._code_mode._context import AsyncCodeModeContext, NotebookCellData
+if TYPE_CHECKING:
+ from collections.abc import Generator
+
+from marimo._code_mode._context import AsyncCodeModeContext
+from marimo._messaging.notebook.document import (
+ NotebookCell,
+ NotebookDocument,
+ notebook_document_context,
+)
from marimo._runtime.commands import ExecuteCellCommand
from marimo._runtime.runtime import Kernel
from marimo._types.ids import CellId_t
@@ -13,6 +24,19 @@ def cmd(cell_id: str, code: str) -> ExecuteCellCommand:
return ExecuteCellCommand(cell_id=CellId_t(cell_id), code=code)
+@contextmanager
+def _ctx(k: Kernel) -> Generator[AsyncCodeModeContext, None, None]:
+ """Build an AsyncCodeModeContext with a document snapshot from the kernel."""
+ doc = NotebookDocument(
+ [
+ NotebookCell(id=cid, code=cell.code, name="", config=cell.config)
+ for cid, cell in k.graph.cells.items()
+ ]
+ )
+ with notebook_document_context(doc):
+ yield AsyncCodeModeContext(k)
+
+
class TestCellsViewIndex:
"""Test integer indexing (positive and negative)."""
@@ -24,11 +48,10 @@ class TestCellsViewIndex:
cmd(cell_id="c", code="z = 3"),
]
)
- ctx = AsyncCodeModeContext(k)
-
- assert ctx.cells[0].id == "a"
- assert ctx.cells[1].id == "b"
- assert ctx.cells[2].id == "c"
+ with _ctx(k) as ctx:
+ assert ctx.cells[0].id == "a"
+ assert ctx.cells[1].id == "b"
+ assert ctx.cells[2].id == "c"
async def test_negative_index(self, k: Kernel) -> None:
await k.run(
@@ -38,21 +61,19 @@ class TestCellsViewIndex:
cmd(cell_id="c", code="z = 3"),
]
)
- ctx = AsyncCodeModeContext(k)
-
- assert ctx.cells[-1].id == "c"
- assert ctx.cells[-2].id == "b"
- assert ctx.cells[-3].id == "a"
+ with _ctx(k) as ctx:
+ assert ctx.cells[-1].id == "c"
+ assert ctx.cells[-2].id == "b"
+ assert ctx.cells[-3].id == "a"
async def test_index_out_of_range(self, k: Kernel) -> None:
await k.run([cmd(cell_id="a", code="x = 1")])
- ctx = AsyncCodeModeContext(k)
-
- with pytest.raises(IndexError):
- ctx.cells[5]
+ with _ctx(k) as ctx:
+ with pytest.raises(IndexError):
+ ctx.cells[5]
- with pytest.raises(IndexError):
- ctx.cells[-5]
+ with pytest.raises(IndexError):
+ ctx.cells[-5]
class TestCellsViewCellId:
@@ -65,18 +86,16 @@ class TestCellsViewCellId:
cmd(cell_id="def", code="y = 2"),
]
)
- ctx = AsyncCodeModeContext(k)
-
- cell = ctx.cells["def"]
- assert cell.id == "def"
- assert cell.code == "y = 2"
+ with _ctx(k) as ctx:
+ cell = ctx.cells["def"]
+ assert cell.id == "def"
+ assert cell.code == "y = 2"
async def test_lookup_by_cell_id_not_found(self, k: Kernel) -> None:
await k.run([cmd(cell_id="abc", code="x = 1")])
- ctx = AsyncCodeModeContext(k)
-
- with pytest.raises(KeyError):
- ctx.cells["nonexistent"]
+ with _ctx(k) as ctx:
+ with pytest.raises(KeyError):
+ ctx.cells["nonexistent"]
class TestCellsViewCellName:
@@ -84,26 +103,20 @@ class TestCellsViewCellName:
async def test_name_lookup_without_cell_manager(self, k: Kernel) -> None:
await k.run([cmd(cell_id="a", code="x = 1")])
- ctx = AsyncCodeModeContext(k)
-
- # No cell manager → name lookup fails
- with pytest.raises(KeyError):
- ctx.cells["my_cell"]
+ with _ctx(k) as ctx:
+ # No cell manager → name lookup fails
+ with pytest.raises(KeyError):
+ ctx.cells["my_cell"]
class TestCellsViewNameField:
- """Test that the name field is populated on NotebookCellData."""
+ """Test that the name field is populated on NotebookCell."""
- async def test_name_is_none_without_cell_manager(self, k: Kernel) -> None:
+ async def test_name_is_empty_without_cell_manager(self, k: Kernel) -> None:
await k.run([cmd(cell_id="a", code="x = 1")])
- ctx = AsyncCodeModeContext(k)
-
- cell = ctx.cells[0]
- assert cell.name is None
-
- async def test_name_field_on_constructed_cell(self) -> None:
- cell = NotebookCellData(code="x = 1", name="my_cell")
- assert cell.name == "my_cell"
+ with _ctx(k) as ctx:
+ cell = ctx.cells[0]
+ assert cell.name == ""
class TestCellsViewIteration:
@@ -116,8 +129,8 @@ class TestCellsViewIteration:
cmd(cell_id="b", code="y = 2"),
]
)
- ctx = AsyncCodeModeContext(k)
- assert len(ctx.cells) == 2
+ with _ctx(k) as ctx:
+ assert len(ctx.cells) == 2
async def test_iteration_yields_cell_ids(self, k: Kernel) -> None:
await k.run(
@@ -126,10 +139,9 @@ class TestCellsViewIteration:
cmd(cell_id="b", code="y = 2"),
]
)
- ctx = AsyncCodeModeContext(k)
-
- ids = list(ctx.cells)
- assert ids == ["a", "b"]
+ with _ctx(k) as ctx:
+ ids = list(ctx.cells)
+ assert ids == ["a", "b"]
async def test_keys(self, k: Kernel) -> None:
await k.run(
@@ -138,8 +150,8 @@ class TestCellsViewIteration:
cmd(cell_id="b", code="y = 2"),
]
)
- ctx = AsyncCodeModeContext(k)
- assert ctx.cells.keys() == ["a", "b"]
+ with _ctx(k) as ctx:
+ assert ctx.cells.keys() == ["a", "b"]
async def test_values(self, k: Kernel) -> None:
await k.run(
@@ -148,10 +160,10 @@ class TestCellsViewIteration:
cmd(cell_id="b", code="y = 2"),
]
)
- ctx = AsyncCodeModeContext(k)
- vals = ctx.cells.values()
- assert [v.id for v in vals] == ["a", "b"]
- assert [v.code for v in vals] == ["x = 1", "y = 2"]
+ with _ctx(k) as ctx:
+ vals = ctx.cells.values()
+ assert [v.id for v in vals] == ["a", "b"]
+ assert [v.code for v in vals] == ["x = 1", "y = 2"]
async def test_items(self, k: Kernel) -> None:
await k.run(
@@ -160,12 +172,12 @@ class TestCellsViewIteration:
cmd(cell_id="b", code="y = 2"),
]
)
- ctx = AsyncCodeModeContext(k)
- items = ctx.cells.items()
- assert [(cid, cell.code) for cid, cell in items] == [
- ("a", "x = 1"),
- ("b", "y = 2"),
- ]
+ with _ctx(k) as ctx:
+ items = ctx.cells.items()
+ assert [(cid, cell.code) for cid, cell in items] == [
+ ("a", "x = 1"),
+ ("b", "y = 2"),
+ ]
async def test_contains(self, k: Kernel) -> None:
await k.run(
@@ -174,8 +186,8 @@ class TestCellsViewIteration:
cmd(cell_id="b", code="y = 2"),
]
)
- ctx = AsyncCodeModeContext(k)
- assert "a" in ctx.cells
- assert "nonexistent" not in ctx.cells
- assert 0 in ctx.cells
- assert 5 not in ctx.cells
+ with _ctx(k) as ctx:
+ assert "a" in ctx.cells
+ assert "nonexistent" not in ctx.cells
+ assert 0 in ctx.cells
+ assert 5 not in ctx.cells
diff --git a/tests/_code_mode/test_context.py b/tests/_code_mode/test_context.py
index 6c9c644039..881722de09 100644
--- a/tests/_code_mode/test_context.py
+++ b/tests/_code_mode/test_context.py
@@ -1,34 +1,58 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+from contextlib import contextmanager
+from typing import TYPE_CHECKING
from unittest.mock import AsyncMock, patch
+if TYPE_CHECKING:
+ from collections.abc import Generator
+
import msgspec
import pytest
from inline_snapshot import snapshot
from marimo._code_mode._context import AsyncCodeModeContext
+from marimo._messaging.notebook.document import (
+ NotebookCell,
+ NotebookDocument,
+ notebook_document_context,
+)
from marimo._messaging.notification import (
+ NotebookDocumentTransactionNotification,
UpdateCellCodesNotification,
- UpdateCellIdsNotification,
)
from marimo._runtime.commands import ExecuteCellCommand
from marimo._runtime.runtime import Kernel
-def _code_notifs(k: Kernel) -> list[UpdateCellCodesNotification]:
- return [
- op
- for op in k.stream.operations
- if isinstance(op, UpdateCellCodesNotification)
- ]
+@contextmanager
+def _ctx(k: Kernel) -> Generator[AsyncCodeModeContext, None, None]:
+ """Build an AsyncCodeModeContext with a document snapshot from the kernel."""
+ doc = NotebookDocument(
+ [
+ NotebookCell(id=cid, code=cell.code, name="", config=cell.config)
+ for cid, cell in k.graph.cells.items()
+ ]
+ )
+ with notebook_document_context(doc):
+ yield AsyncCodeModeContext(k)
-def _ids_notifs(k: Kernel) -> list[UpdateCellIdsNotification]:
+def _tx_ops(k: Kernel) -> list[dict[str, object]]:
+ """Serialize all document transaction ops for snapshot comparison."""
+ ops: list[dict[str, object]] = []
+ for notif in k.stream.operations:
+ if isinstance(notif, NotebookDocumentTransactionNotification):
+ ops.extend(msgspec.to_builtins(notif.transaction.changes))
+ return ops
+
+
+def _code_notifs(k: Kernel) -> list[UpdateCellCodesNotification]:
return [
op
for op in k.stream.operations
- if isinstance(op, UpdateCellIdsNotification)
+ if isinstance(op, UpdateCellCodesNotification)
]
@@ -42,26 +66,36 @@ def _graph_codes(k: Kernel) -> dict[str, str]:
class TestAddCell:
async def test_add_into_empty(self, k: Kernel) -> None:
- ctx = AsyncCodeModeContext(k)
- _clear_messages(k)
-
- async with ctx as nb:
- cid = nb.create_cell("x = 1")
- nb.run_cell(cid)
-
- assert len(k.graph.cells) == 1
- cell = list(k.graph.cells.values())[0]
- assert cell.code == "x = 1"
- assert k.globals["x"] == 1
-
- code_notifs = msgspec.to_builtins(_code_notifs(k))
- assert len(code_notifs) == 1
- assert code_notifs[0]["codes"] == ["x = 1"]
- assert code_notifs[0]["code_is_stale"] is False
+ with _ctx(k) as ctx:
+ _clear_messages(k)
- ids_notifs = msgspec.to_builtins(_ids_notifs(k))
- assert len(ids_notifs) == 1
- assert len(ids_notifs[0]["cell_ids"]) == 1
+ async with ctx as nb:
+ cid = nb.create_cell("x = 1")
+ nb.run_cell(cid)
+
+ assert len(k.graph.cells) == 1
+ cell = list(k.graph.cells.values())[0]
+ assert cell.code == "x = 1"
+ assert k.globals["x"] == 1
+
+ assert _tx_ops(k) == snapshot(
+ [
+ {
+ "type": "create-cell",
+ "cellId": "Hbol",
+ "code": "x = 1",
+ "name": "",
+ "config": {
+ "column": None,
+ "disabled": False,
+ "hide_code": True,
+ },
+ "before": None,
+ "after": None,
+ },
+ {"type": "reorder-cells", "cellIds": ("Hbol",)},
+ ]
+ )
async def test_add_appends_by_default(self, k: Kernel) -> None:
await k.run(
@@ -70,22 +104,22 @@ class TestAddCell:
ExecuteCellCommand(cell_id="1", code="b = 20"),
]
)
- ctx = AsyncCodeModeContext(k)
- _clear_messages(k)
+ with _ctx(k) as ctx:
+ _clear_messages(k)
- async with ctx as nb:
- cid = nb.create_cell("c = a + b")
- nb.run_cell(cid)
+ async with ctx as nb:
+ cid = nb.create_cell("c = a + b")
+ nb.run_cell(cid)
- assert len(k.graph.cells) == 3
- assert k.globals["c"] == 30
+ assert len(k.graph.cells) == 3
+ assert k.globals["c"] == 30
- # New cell should be last in the ordering notification.
- ids_notifs = _ids_notifs(k)
- assert len(ids_notifs) == 1
- cell_ids = ids_notifs[0].cell_ids
- assert cell_ids[:2] == ["0", "1"]
- assert len(cell_ids) == 3
+ # New cell should be last in the ordering.
+ ops = _tx_ops(k)
+ reorder = [o for o in ops if o["type"] == "reorder-cells"]
+ assert len(reorder) == 1
+ assert reorder[0]["cellIds"][:2] == ("0", "1")
+ assert len(reorder[0]["cellIds"]) == 3
async def test_add_with_after(self, k: Kernel) -> None:
await k.run(
@@ -94,53 +128,52 @@ class TestAddCell:
ExecuteCellCommand(cell_id="1", code="b = 20"),
]
)
- ctx = AsyncCodeModeContext(k)
- _clear_messages(k)
+ with _ctx(k) as ctx:
+ _clear_messages(k)
- async with ctx as nb:
- nb.create_cell("c = a + b", after="0")
+ async with ctx as nb:
+ nb.create_cell("c = a + b", after="0")
- ids_notifs = _ids_notifs(k)
- cell_ids = ids_notifs[0].cell_ids
- assert cell_ids[0] == "0"
- # New cell should be after "0", before "1".
- assert cell_ids[2] == "1"
+ ops = _tx_ops(k)
+ reorder = [o for o in ops if o["type"] == "reorder-cells"][0]
+ assert reorder["cellIds"][0] == "0"
+ # New cell should be after "0", before "1".
+ assert reorder["cellIds"][2] == "1"
async def test_add_without_run_does_not_execute(self, k: Kernel) -> None:
- ctx = AsyncCodeModeContext(k)
- _clear_messages(k)
+ with _ctx(k) as ctx:
+ _clear_messages(k)
- async with ctx as nb:
- nb.create_cell("x = 999")
+ async with ctx as nb:
+ nb.create_cell("x = 999")
- assert len(k.graph.cells) == 1
- assert "x" not in k.globals
+ assert len(k.graph.cells) == 1
+ assert "x" not in k.globals
- code_notifs = msgspec.to_builtins(_code_notifs(k))
- assert len(code_notifs) == 1
- assert code_notifs[0]["codes"] == ["x = 999"]
- assert code_notifs[0]["code_is_stale"] is True
+ # Cell should appear as a CreateCell op (frontend marks it stale).
+ ops = _tx_ops(k)
+ creates = [o for o in ops if o["type"] == "create-cell"]
+ assert len(creates) == 1
+ assert creates[0]["code"] == "x = 999"
async def test_add_returns_cell_id(self, k: Kernel) -> None:
- ctx = AsyncCodeModeContext(k)
-
- async with ctx as nb:
- cid = nb.create_cell("x = 1")
- assert isinstance(cid, str)
- assert len(cid) > 0
+ with _ctx(k) as ctx:
+ async with ctx as nb:
+ cid = nb.create_cell("x = 1")
+ assert isinstance(cid, str)
+ assert len(cid) > 0
async def test_add_chain_after(self, k: Kernel) -> None:
"""Can reference a just-added cell's ID in a subsequent add."""
- ctx = AsyncCodeModeContext(k)
+ with _ctx(k) as ctx:
+ async with ctx as nb:
+ cid1 = nb.create_cell("x = 1")
+ cid2 = nb.create_cell("y = 2", after=cid1)
+ nb.run_cell(cid1)
+ nb.run_cell(cid2)
- async with ctx as nb:
- cid1 = nb.create_cell("x = 1")
- cid2 = nb.create_cell("y = 2", after=cid1)
- nb.run_cell(cid1)
- nb.run_cell(cid2)
-
- assert k.globals["x"] == 1
- assert k.globals["y"] == 2
+ assert k.globals["x"] == 1
+ assert k.globals["y"] == 2
class TestDeleteCell:
@@ -154,17 +187,20 @@ class TestDeleteCell:
)
assert len(k.graph.cells) == 3
- ctx = AsyncCodeModeContext(k)
- _clear_messages(k)
+ with _ctx(k) as ctx:
+ _clear_messages(k)
- async with ctx as nb:
- nb.delete_cell("1")
+ async with ctx as nb:
+ nb.delete_cell("1")
- assert _graph_codes(k) == snapshot({"0": "a = 1", "2": "c = 3"})
+ assert _graph_codes(k) == snapshot({"0": "a = 1", "2": "c = 3"})
- assert msgspec.to_builtins(_ids_notifs(k)) == snapshot(
- [{"op": "update-cell-ids", "cell_ids": ["0", "2"]}]
- )
+ assert _tx_ops(k) == snapshot(
+ [
+ {"type": "delete-cell", "cellId": "1"},
+ {"type": "reorder-cells", "cellIds": ("0", "2")},
+ ]
+ )
async def test_delete_cleans_globals(self, k: Kernel) -> None:
"""Deleting a cell removes its defs from kernel globals."""
@@ -177,12 +213,12 @@ class TestDeleteCell:
assert k.globals["a"] == 1
assert k.globals["b"] == 2
- ctx = AsyncCodeModeContext(k)
- async with ctx as nb:
- nb.delete_cell("1")
+ with _ctx(k) as ctx:
+ async with ctx as nb:
+ nb.delete_cell("1")
- assert k.globals["a"] == 1
- assert "b" not in k.globals
+ assert k.globals["a"] == 1
+ assert "b" not in k.globals
async def test_delete_multiple(self, k: Kernel) -> None:
await k.run(
@@ -192,14 +228,14 @@ class TestDeleteCell:
ExecuteCellCommand(cell_id="2", code="c = 3"),
]
)
- ctx = AsyncCodeModeContext(k)
- _clear_messages(k)
+ with _ctx(k) as ctx:
+ _clear_messages(k)
- async with ctx as nb:
- nb.delete_cell("0")
- nb.delete_cell("2")
+ async with ctx as nb:
+ nb.delete_cell("0")
+ nb.delete_cell("2")
- assert _graph_codes(k) == snapshot({"1": "b = 2"})
+ assert _graph_codes(k) == snapshot({"1": "b = 2"})
class TestUpdateCell:
@@ -207,34 +243,22 @@ class TestUpdateCell:
await k.run([ExecuteCellCommand(cell_id="0", code="x = 1")])
assert k.globals["x"] == 1
- ctx = AsyncCodeModeContext(k)
- _clear_messages(k)
+ with _ctx(k) as ctx:
+ _clear_messages(k)
- async with ctx as nb:
- nb.edit_cell("0", code="x = 42")
- nb.run_cell("0")
+ async with ctx as nb:
+ nb.edit_cell("0", code="x = 42")
+ nb.run_cell("0")
- assert k.globals["x"] == 42
- assert _graph_codes(k) == snapshot({"0": "x = 42"})
+ assert k.globals["x"] == 42
+ assert _graph_codes(k) == snapshot({"0": "x = 42"})
- assert msgspec.to_builtins(_code_notifs(k)) == snapshot(
- [
- {
- "op": "update-cell-codes",
- "cell_ids": ["0"],
- "codes": ["x = 42"],
- "code_is_stale": False,
- "names": [],
- "configs": [
- {
- "column": None,
- "disabled": False,
- "hide_code": False,
- }
- ],
- }
- ]
- )
+ assert _tx_ops(k) == snapshot(
+ [
+ {"type": "set-code", "cellId": "0", "code": "x = 42"},
+ {"type": "reorder-cells", "cellIds": ("0",)},
+ ]
+ )
async def test_update_cleans_stale_globals(self, k: Kernel) -> None:
"""Updating code removes old defs that are no longer defined."""
@@ -242,30 +266,30 @@ class TestUpdateCell:
assert k.globals["x"] == 1
assert k.globals["y"] == 2
- ctx = AsyncCodeModeContext(k)
- async with ctx as nb:
- nb.edit_cell("0", code="x = 42")
- nb.run_cell("0")
+ with _ctx(k) as ctx:
+ async with ctx as nb:
+ nb.edit_cell("0", code="x = 42")
+ nb.run_cell("0")
- assert k.globals["x"] == 42
- assert "y" not in k.globals
+ assert k.globals["x"] == 42
+ assert "y" not in k.globals
async def test_update_preserves_config(self, k: Kernel) -> None:
"""Updating only code preserves the cell's existing config."""
await k.run([ExecuteCellCommand(cell_id="0", code="x = 1")])
# Set hide_code=True on the cell.
- ctx = AsyncCodeModeContext(k)
- async with ctx as nb:
- nb.edit_cell("0", hide_code=True)
+ with _ctx(k) as ctx:
+ async with ctx as nb:
+ nb.edit_cell("0", hide_code=True)
assert k.cell_metadata["0"].config.hide_code is True
# Update code without touching config — hide_code should stick.
- ctx = AsyncCodeModeContext(k)
- async with ctx as nb:
- nb.edit_cell("0", code="x = 42")
- nb.run_cell("0")
+ with _ctx(k) as ctx:
+ async with ctx as nb:
+ nb.edit_cell("0", code="x = 42")
+ nb.run_cell("0")
assert k.globals["x"] == 42
assert k.cell_metadata["0"].config.hide_code is True
@@ -273,32 +297,26 @@ class TestUpdateCell:
async def test_update_config_only(self, k: Kernel) -> None:
await k.run([ExecuteCellCommand(cell_id="0", code="x = 1")])
- ctx = AsyncCodeModeContext(k)
- _clear_messages(k)
-
- async with ctx as nb:
- nb.edit_cell("0", hide_code=True)
+ with _ctx(k) as ctx:
+ _clear_messages(k)
- assert k.globals["x"] == 1
- assert _graph_codes(k) == snapshot({"0": "x = 1"})
- assert msgspec.to_builtins(_code_notifs(k)) == snapshot(
- [
- {
- "op": "update-cell-codes",
- "cell_ids": ["0"],
- "codes": ["x = 1"],
- "code_is_stale": False,
- "names": [],
- "configs": [
- {
- "column": None,
- "disabled": False,
- "hide_code": True,
- }
- ],
- }
- ]
- )
+ async with ctx as nb:
+ nb.edit_cell("0", hide_code=True)
+
+ assert k.globals["x"] == 1
+ assert _graph_codes(k) == snapshot({"0": "x = 1"})
+ assert _tx_ops(k) == snapshot(
+ [
+ {
+ "type": "set-config",
+ "cellId": "0",
+ "column": None,
+ "disabled": False,
+ "hideCode": True,
+ },
+ {"type": "reorder-cells", "cellIds": ("0",)},
+ ]
+ )
class TestCombined:
@@ -311,17 +329,17 @@ class TestCombined:
]
)
- ctx = AsyncCodeModeContext(k)
- _clear_messages(k)
+ with _ctx(k) as ctx:
+ _clear_messages(k)
- async with ctx as nb:
- nb.delete_cell("1")
- cid = nb.create_cell("d = a + c", after="0")
- nb.run_cell(cid)
+ async with ctx as nb:
+ nb.delete_cell("1")
+ cid = nb.create_cell("d = a + c", after="0")
+ nb.run_cell(cid)
- assert k.globals["d"] == 4
- codes = _graph_codes(k)
- assert "1" not in codes
+ assert k.globals["d"] == 4
+ codes = _graph_codes(k)
+ assert "1" not in codes
async def test_delete_and_add_same_defs(self, k: Kernel) -> None:
"""Delete a cell and add a replacement defining the same names."""
@@ -333,57 +351,55 @@ class TestCombined:
)
assert k.globals["b"] == 2
- ctx = AsyncCodeModeContext(k)
- _clear_messages(k)
+ with _ctx(k) as ctx:
+ _clear_messages(k)
- # Delete cell "1" and create a new cell that also defines "b".
- # This must not raise a multiply-defined error.
- async with ctx as nb:
- nb.delete_cell("1")
- cid = nb.create_cell("b = a + 100")
- nb.run_cell(cid)
+ # Delete cell "1" and create a new cell that also defines "b".
+ # This must not raise a multiply-defined error.
+ async with ctx as nb:
+ nb.delete_cell("1")
+ cid = nb.create_cell("b = a + 100")
+ nb.run_cell(cid)
- assert k.globals["b"] == 101
- assert "1" not in _graph_codes(k)
+ assert k.globals["b"] == 101
+ assert "1" not in _graph_codes(k)
async def test_noop_batch(self, k: Kernel) -> None:
"""An empty context manager does nothing."""
await k.run([ExecuteCellCommand(cell_id="0", code="x = 1")])
- ctx = AsyncCodeModeContext(k)
- _clear_messages(k)
+ with _ctx(k) as ctx:
+ _clear_messages(k)
- async with ctx as nb: # noqa: B018
- pass
+ async with ctx as nb: # noqa: B018
+ pass
- assert _graph_codes(k) == snapshot({"0": "x = 1"})
+ assert _graph_codes(k) == snapshot({"0": "x = 1"})
async def test_exception_discards_ops(self, k: Kernel) -> None:
"""If an exception occurs, queued ops are discarded."""
await k.run([ExecuteCellCommand(cell_id="0", code="x = 1")])
- ctx = AsyncCodeModeContext(k)
-
- try:
- async with ctx as nb:
- nb.create_cell("y = 2")
- raise ValueError("oops")
- except ValueError:
- pass
-
- # The add should not have been applied.
- assert _graph_codes(k) == snapshot({"0": "x = 1"})
- assert len(k.graph.cells) == 1
+ with _ctx(k) as ctx:
+ try:
+ async with ctx as nb:
+ nb.create_cell("y = 2")
+ raise ValueError("oops")
+ except ValueError:
+ pass
+
+ # The add should not have been applied.
+ assert _graph_codes(k) == snapshot({"0": "x = 1"})
+ assert len(k.graph.cells) == 1
async def test_rerun_without_structural_ops(self, k: Kernel) -> None:
"""run_cell without any create/edit/delete still executes."""
await k.run([ExecuteCellCommand(cell_id="0", code="x = 1")])
- ctx = AsyncCodeModeContext(k)
+ with _ctx(k) as ctx:
+ # Mutate the global so we can detect re-execution.
+ k.globals["x"] = 0
+ async with ctx as nb:
+ nb.run_cell("0")
- # Mutate the global so we can detect re-execution.
- k.globals["x"] = 0
- async with ctx as nb:
- nb.run_cell("0")
-
- assert k.globals["x"] == 1
+ assert k.globals["x"] == 1
async def test_rerun_alongside_structural_ops(self, k: Kernel) -> None:
"""run_cell on an unchanged cell works even with other structural ops."""
@@ -393,73 +409,67 @@ class TestCombined:
ExecuteCellCommand(cell_id="1", code="y = x + 1"),
]
)
- ctx = AsyncCodeModeContext(k)
+ with _ctx(k) as ctx:
+ # Mutate so we can detect re-execution of "0".
+ k.globals["x"] = 0
+ async with ctx as nb:
+ nb.create_cell("z = 99", name="new")
+ nb.run_cell("0")
- # Mutate so we can detect re-execution of "0".
- k.globals["x"] = 0
- async with ctx as nb:
- nb.create_cell("z = 99", name="new")
- nb.run_cell("0")
-
- assert k.globals["x"] == 1
+ assert k.globals["x"] == 1
async def test_run_deleted_cell_raises(self, k: Kernel) -> None:
"""Calling run_cell on a cell queued for deletion raises."""
await k.run([ExecuteCellCommand(cell_id="0", code="x = 1")])
- ctx = AsyncCodeModeContext(k)
-
- async with ctx as nb:
- nb.delete_cell("0")
- with pytest.raises(ValueError, match="queued for deletion"):
- nb.run_cell("0")
+ with _ctx(k) as ctx:
+ async with ctx as nb:
+ nb.delete_cell("0")
+ with pytest.raises(ValueError, match="queued for deletion"):
+ nb.run_cell("0")
class TestSummary:
async def test_create_prints_summary(
self, k: Kernel, capsys: object
) -> None:
- ctx = AsyncCodeModeContext(k)
-
- async with ctx as nb:
- nb.create_cell("x = 1", name="my_cell")
+ with _ctx(k) as ctx:
+ async with ctx as nb:
+ nb.create_cell("x = 1", name="my_cell")
- captured = capsys.readouterr() # type: ignore[attr-defined]
- assert captured.out == snapshot("created cell 'Hbol' (my_cell)\n")
+ captured = capsys.readouterr() # type: ignore[attr-defined]
+ assert captured.out == snapshot("created cell 'Hbol' (my_cell)\n")
async def test_edit_prints_summary(
self, k: Kernel, capsys: object
) -> None:
await k.run([ExecuteCellCommand(cell_id="0", code="x = 1")])
- ctx = AsyncCodeModeContext(k)
-
- async with ctx as nb:
- nb.edit_cell("0", code="x = 2")
+ with _ctx(k) as ctx:
+ async with ctx as nb:
+ nb.edit_cell("0", code="x = 2")
- captured = capsys.readouterr() # type: ignore[attr-defined]
- assert captured.out == snapshot("edited code of cell '0'\n")
+ captured = capsys.readouterr() # type: ignore[attr-defined]
+ assert captured.out == snapshot("edited code of cell '0'\n")
async def test_delete_prints_summary(
self, k: Kernel, capsys: object
) -> None:
await k.run([ExecuteCellCommand(cell_id="0", code="x = 1")])
- ctx = AsyncCodeModeContext(k)
-
- async with ctx as nb:
- nb.delete_cell("0")
+ with _ctx(k) as ctx:
+ async with ctx as nb:
+ nb.delete_cell("0")
- captured = capsys.readouterr() # type: ignore[attr-defined]
- assert captured.out == snapshot("deleted cell '0'\n")
+ captured = capsys.readouterr() # type: ignore[attr-defined]
+ assert captured.out == snapshot("deleted cell '0'\n")
async def test_noop_prints_nothing(
self, k: Kernel, capsys: object
) -> None:
- ctx = AsyncCodeModeContext(k)
-
- async with ctx as nb: # noqa: B018
- pass
+ with _ctx(k) as ctx:
+ async with ctx as nb: # noqa: B018
+ pass
- captured = capsys.readouterr() # type: ignore[attr-defined]
- assert captured.out == ""
+ captured = capsys.readouterr() # type: ignore[attr-defined]
+ assert captured.out == ""
async def test_batch_summary(self, k: Kernel, capsys: object) -> None:
"""Full batch: create+run, edit+run, delete, create (staged), re-run."""
@@ -470,24 +480,23 @@ class TestSummary:
ExecuteCellCommand(cell_id="2", code="c = 3"),
]
)
- ctx = AsyncCodeModeContext(k)
-
- async with ctx as nb:
- # delete
- nb.delete_cell("1")
- # create + run
- nb.create_cell("d = 4", name="new_cell")
- nb.run_cell("new_cell")
- # create without run (staged)
- nb.create_cell("e = 5", name="staged")
- # edit + run
- nb.edit_cell("0", code="a = 10")
- nb.run_cell("0")
- # re-run existing cell without editing
- nb.run_cell("2")
-
- captured = capsys.readouterr() # type: ignore[attr-defined]
- assert captured.out == snapshot("""\
+ with _ctx(k) as ctx:
+ async with ctx as nb:
+ # delete
+ nb.delete_cell("1")
+ # create + run
+ nb.create_cell("d = 4", name="new_cell")
+ nb.run_cell("new_cell")
+ # create without run (staged)
+ nb.create_cell("e = 5", name="staged")
+ # edit + run
+ nb.edit_cell("0", code="a = 10")
+ nb.run_cell("0")
+ # re-run existing cell without editing
+ nb.run_cell("2")
+
+ captured = capsys.readouterr() # type: ignore[attr-defined]
+ assert captured.out == snapshot("""\
deleted cell '1'
created and ran cell 'Hbol' (new_cell)
created cell 'MJUe' (staged)
@@ -499,21 +508,20 @@ re-ran cell '2'
class TestResolveTarget:
async def test_create_after_pending_add_by_name(self, k: Kernel) -> None:
"""Can reference a just-added cell by name in a subsequent add."""
- ctx = AsyncCodeModeContext(k)
-
- async with ctx as nb:
- cid1 = nb.create_cell("x = 1", name="first")
- cid2 = nb.create_cell("y = x + 1", after="first")
- nb.run_cell(cid1)
- nb.run_cell(cid2)
+ with _ctx(k) as ctx:
+ async with ctx as nb:
+ cid1 = nb.create_cell("x = 1", name="first")
+ cid2 = nb.create_cell("y = x + 1", after="first")
+ nb.run_cell(cid1)
+ nb.run_cell(cid2)
- assert k.globals["x"] == 1
- assert k.globals["y"] == 2
+ assert k.globals["x"] == 1
+ assert k.globals["y"] == 2
- # "first" should come before the second cell in ordering.
- ids_notifs = _ids_notifs(k)
- cell_ids = ids_notifs[0].cell_ids
- assert len(cell_ids) == 2
+ # "first" should come before the second cell in ordering.
+ ops = _tx_ops(k)
+ reorder = [o for o in ops if o["type"] == "reorder-cells"][0]
+ assert len(reorder["cellIds"]) == 2
async def test_create_after_renamed_cell(self, k: Kernel) -> None:
"""Can reference a cell by its new name after edit_cell renames it."""
@@ -523,60 +531,62 @@ class TestResolveTarget:
ExecuteCellCommand(cell_id="1", code="b = 2"),
]
)
- ctx = AsyncCodeModeContext(k)
- _clear_messages(k)
+ with _ctx(k) as ctx:
+ _clear_messages(k)
- async with ctx as nb:
- nb.edit_cell("0", name="renamed")
- cid = nb.create_cell("c = a + b", after="renamed")
- nb.run_cell(cid)
+ async with ctx as nb:
+ nb.edit_cell("0", name="renamed")
+ cid = nb.create_cell("c = a + b", after="renamed")
+ nb.run_cell(cid)
- assert k.globals["c"] == 3
+ assert k.globals["c"] == 3
- # New cell should be after "0" (renamed), before "1".
- ids_notifs = _ids_notifs(k)
- cell_ids = ids_notifs[0].cell_ids
- assert cell_ids[0] == "0"
- assert cell_ids[2] == "1"
+ # New cell should be after "0" (renamed), before "1".
+ ops = _tx_ops(k)
+ reorder = [o for o in ops if o["type"] == "reorder-cells"][0]
+ assert reorder["cellIds"][0] == "0"
+ assert reorder["cellIds"][2] == "1"
class TestInstallPackages:
async def test_install_single(self, k: Kernel) -> None:
- ctx = AsyncCodeModeContext(k)
- pm = k.packages_callbacks.package_manager
- assert pm is not None
-
- with patch.object(
- pm, "install", new_callable=AsyncMock, return_value=True
- ) as mock_install:
- async with ctx:
- ctx.install_packages("pandas")
- # Not installed yet — still queued.
- assert mock_install.call_count == 0
-
- assert mock_install.call_count == 1
- assert mock_install.call_args_list[0].args[0] == "pandas"
- assert mock_install.call_args_list[0].kwargs["version"] == ""
+ with _ctx(k) as ctx:
+ pm = k.packages_callbacks.package_manager
+ assert pm is not None
+
+ with patch.object(
+ pm, "install", new_callable=AsyncMock, return_value=True
+ ) as mock_install:
+ async with ctx:
+ ctx.install_packages("pandas")
+ # Not installed yet — still queued.
+ assert mock_install.call_count == 0
+
+ assert mock_install.call_count == 1
+ assert mock_install.call_args_list[0].args[0] == "pandas"
+ assert mock_install.call_args_list[0].kwargs["version"] == ""
async def test_install_multiple_with_specifiers(self, k: Kernel) -> None:
- ctx = AsyncCodeModeContext(k)
- pm = k.packages_callbacks.package_manager
- assert pm is not None
-
- with patch.object(
- pm, "install", new_callable=AsyncMock, return_value=True
- ) as mock_install:
- async with ctx:
- ctx.install_packages("pandas", "polars>=0.20", "numpy==1.26")
-
- # Each package should have been installed one-by-one.
- installed = {
- call.args[0]: call.kwargs["version"]
- for call in mock_install.call_args_list
- }
- assert installed["pandas"] == ""
- assert installed["polars>=0.20"] == ""
- assert installed["numpy==1.26"] == ""
+ with _ctx(k) as ctx:
+ pm = k.packages_callbacks.package_manager
+ assert pm is not None
+
+ with patch.object(
+ pm, "install", new_callable=AsyncMock, return_value=True
+ ) as mock_install:
+ async with ctx:
+ ctx.install_packages(
+ "pandas", "polars>=0.20", "numpy==1.26"
+ )
+
+ # Each package should have been installed one-by-one.
+ installed = {
+ call.args[0]: call.kwargs["version"]
+ for call in mock_install.call_args_list
+ }
+ assert installed["pandas"] == ""
+ assert installed["polars>=0.20"] == ""
+ assert installed["numpy==1.26"] == ""
class TestAutorunStaleState:
@@ -586,30 +596,24 @@ class TestAutorunStaleState:
"""Running the root cell should mark reactive descendants as
non-stale in autorun mode so the frontend doesn't show them
as 'needs run'."""
- ctx = AsyncCodeModeContext(k)
- _clear_messages(k)
+ with _ctx(k) as ctx:
+ _clear_messages(k)
- async with ctx as nb:
- a = nb.create_cell("x = 1")
- b = nb.create_cell("y = x + 1")
- nb.run_cell(a)
+ async with ctx as nb:
+ a = nb.create_cell("x = 1")
+ b = nb.create_cell("y = x + 1")
+ nb.run_cell(a)
- # Both cells should have executed.
- assert k.globals["x"] == 1
- assert k.globals["y"] == 2
+ # Both cells should have executed.
+ assert k.globals["x"] == 1
+ assert k.globals["y"] == 2
- # The notification for b should be code_is_stale=False because
- # autorun will execute it.
- code_notifs = msgspec.to_builtins(_code_notifs(k))
- stale_flags = {
- cid: n["code_is_stale"]
- for n in code_notifs
- for cid in n["cell_ids"]
- }
- a_id = list(k.graph.cells.keys())[0]
- b_id = list(k.graph.cells.keys())[1]
- assert stale_flags[str(a_id)] is False
- assert stale_flags[str(b_id)] is False
+ # Both cells should appear as CreateCell ops in the transaction.
+ ops = _tx_ops(k)
+ creates = [o for o in ops if o["type"] == "create-cell"]
+ assert len(creates) == 2
+ assert creates[0]["code"] == "x = 1"
+ assert creates[1]["code"] == "y = x + 1"
async def test_dependent_chain_lazy_mode(
self, lazy_kernel: Kernel
@@ -617,45 +621,41 @@ class TestAutorunStaleState:
"""In lazy mode, only the explicitly run cell should be non-stale.
Downstream cells stay stale."""
k = lazy_kernel
- ctx = AsyncCodeModeContext(k)
- _clear_messages(k)
+ with _ctx(k) as ctx:
+ _clear_messages(k)
- async with ctx as nb:
- a = nb.create_cell("x = 1")
- b = nb.create_cell("y = x + 1")
- nb.run_cell(a)
+ async with ctx as nb:
+ a = nb.create_cell("x = 1")
+ b = nb.create_cell("y = x + 1")
+ nb.run_cell(a)
- assert k.globals["x"] == 1
- # b should NOT have executed in lazy mode.
- assert "y" not in k.globals
+ assert k.globals["x"] == 1
+ # b should NOT have executed in lazy mode.
+ assert "y" not in k.globals
- code_notifs = msgspec.to_builtins(_code_notifs(k))
- stale_flags = {
- cid: n["code_is_stale"]
- for n in code_notifs
- for cid in n["cell_ids"]
- }
- a_id = list(k.graph.cells.keys())[0]
- b_id = list(k.graph.cells.keys())[1]
- assert stale_flags[str(a_id)] is False
- assert stale_flags[str(b_id)] is True
+ # Both cells should appear as CreateCell ops in the transaction.
+ ops = _tx_ops(k)
+ creates = [o for o in ops if o["type"] == "create-cell"]
+ assert len(creates) == 2
+ assert creates[0]["code"] == "x = 1"
+ assert creates[1]["code"] == "y = x + 1"
async def test_two_step_edit_then_run(self, k: Kernel) -> None:
"""edit_cell in one flush, run_cell in a separate flush should
send code_is_stale=false so the frontend clears the stale state."""
await k.run([ExecuteCellCommand(cell_id="0", code="x = 1")])
- ctx = AsyncCodeModeContext(k)
# Flush 1: edit only
- async with ctx as nb:
- nb.edit_cell("0", code="x = 42")
+ with _ctx(k) as ctx:
+ async with ctx as nb:
+ nb.edit_cell("0", code="x = 42")
_clear_messages(k)
# Flush 2: run only
- ctx2 = AsyncCodeModeContext(k)
- async with ctx2 as nb:
- nb.run_cell("0")
+ with _ctx(k) as ctx:
+ async with ctx as nb:
+ nb.run_cell("0")
assert k.globals["x"] == 42
diff --git a/tests/_messaging/notebook/__init__.py b/tests/_messaging/notebook/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/_messaging/notebook/test_changes.py b/tests/_messaging/notebook/test_changes.py
new file mode 100644
index 0000000000..56827ad45c
--- /dev/null
+++ b/tests/_messaging/notebook/test_changes.py
@@ -0,0 +1,91 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import pytest
+from msgspec.structs import replace as structs_replace
+
+from marimo._ast.cell import CellConfig
+from marimo._messaging.notebook.changes import (
+ CreateCell,
+ DeleteCell,
+ MoveCell,
+ ReorderCells,
+ SetCode,
+ SetConfig,
+ SetName,
+ Transaction,
+)
+from marimo._types.ids import CellId_t
+
+
+class TestChangesFrozen:
+ """All change types must be immutable."""
+
+ def test_create_cell_frozen(self) -> None:
+ op = CreateCell(
+ cell_id=CellId_t("a"), code="x", name="__", config=CellConfig()
+ )
+ with pytest.raises(AttributeError):
+ op.code = "y" # type: ignore[misc]
+
+ def test_delete_cell_frozen(self) -> None:
+ op = DeleteCell(cell_id=CellId_t("a"))
+ with pytest.raises(AttributeError):
+ op.cell_id = CellId_t("b") # type: ignore[misc]
+
+ def test_move_cell_frozen(self) -> None:
+ op = MoveCell(cell_id=CellId_t("a"), after=CellId_t("b"))
+ with pytest.raises(AttributeError):
+ op.after = CellId_t("c") # type: ignore[misc]
+
+ def test_set_code_frozen(self) -> None:
+ op = SetCode(cell_id=CellId_t("a"), code="x")
+ with pytest.raises(AttributeError):
+ op.code = "y" # type: ignore[misc]
+
+ def test_set_name_frozen(self) -> None:
+ op = SetName(cell_id=CellId_t("a"), name="foo")
+ with pytest.raises(AttributeError):
+ op.name = "bar" # type: ignore[misc]
+
+ def test_set_config_frozen(self) -> None:
+ op = SetConfig(cell_id=CellId_t("a"), hide_code=True)
+ with pytest.raises(AttributeError):
+ op.hide_code = False # type: ignore[misc]
+
+ def test_reorder_cells_frozen(self) -> None:
+ op = ReorderCells(cell_ids=(CellId_t("a"), CellId_t("b")))
+ with pytest.raises(AttributeError):
+ op.cell_ids = () # type: ignore[misc]
+
+
+class TestTransaction:
+ def test_creation(self) -> None:
+ tx = Transaction(
+ changes=(SetCode(cell_id=CellId_t("a"), code="x"),),
+ source="kernel",
+ )
+ assert tx.source == "kernel"
+ assert tx.version is None
+ assert len(tx.changes) == 1
+
+ def test_frozen(self) -> None:
+ tx = Transaction(changes=(), source="test")
+ with pytest.raises(AttributeError):
+ tx.source = "other" # type: ignore[misc]
+
+ def test_version_stamping(self) -> None:
+ tx = Transaction(changes=(), source="test")
+ stamped = structs_replace(tx, version=42)
+ assert stamped.version == 42
+ assert tx.version is None # original unchanged
+
+ def test_changes_is_tuple(self) -> None:
+ tx = Transaction(
+ changes=(
+ SetCode(cell_id=CellId_t("a"), code="x"),
+ SetName(cell_id=CellId_t("a"), name="foo"),
+ ),
+ source="test",
+ )
+ assert isinstance(tx.changes, tuple)
diff --git a/tests/_messaging/notebook/test_document.py b/tests/_messaging/notebook/test_document.py
new file mode 100644
index 0000000000..1a9e6a4dc4
--- /dev/null
+++ b/tests/_messaging/notebook/test_document.py
@@ -0,0 +1,577 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import pytest
+from inline_snapshot import snapshot
+
+from marimo._ast.cell import CellConfig
+from marimo._messaging.notebook.changes import (
+ CreateCell,
+ DeleteCell,
+ DocumentChange,
+ MoveCell,
+ ReorderCells,
+ SetCode,
+ SetConfig,
+ SetName,
+ Transaction,
+)
+from marimo._messaging.notebook.document import NotebookCell, NotebookDocument
+from marimo._types.ids import CellId_t
+
+# ------------------------------------------------------------------
+# Helpers
+# ------------------------------------------------------------------
+
+
+def _cell(name: str) -> NotebookCell:
+ return NotebookCell(
+ id=CellId_t(name), code="", name="__", config=CellConfig()
+ )
+
+
+def _doc(*names: str) -> NotebookDocument:
+ return NotebookDocument([_cell(n) for n in names])
+
+
+def _tx(*changes: DocumentChange, source: str = "test") -> Transaction:
+ return Transaction(changes=changes, source=source)
+
+
+def _ids(doc: NotebookDocument) -> list[str]:
+ return [str(cid) for cid in doc.cell_ids]
+
+
+# ------------------------------------------------------------------
+# CreateCell
+# ------------------------------------------------------------------
+
+
+class TestCreateCell:
+ def test_append_at_end(self) -> None:
+ doc = _doc("a", "b")
+ doc.apply(
+ _tx(
+ CreateCell(
+ cell_id=CellId_t("new"),
+ code="x",
+ name="__",
+ config=CellConfig(),
+ )
+ )
+ )
+ assert _ids(doc) == snapshot(["a", "b", "new"])
+
+ def test_insert_after(self) -> None:
+ doc = _doc("a", "b", "c")
+ doc.apply(
+ _tx(
+ CreateCell(
+ cell_id=CellId_t("new"),
+ code="x",
+ name="__",
+ config=CellConfig(),
+ after=CellId_t("a"),
+ )
+ )
+ )
+ assert _ids(doc) == snapshot(["a", "new", "b", "c"])
+
+ def test_insert_before(self) -> None:
+ doc = _doc("a", "b", "c")
+ doc.apply(
+ _tx(
+ CreateCell(
+ cell_id=CellId_t("new"),
+ code="x",
+ name="__",
+ config=CellConfig(),
+ before=CellId_t("b"),
+ )
+ )
+ )
+ assert _ids(doc) == snapshot(["a", "new", "b", "c"])
+
+ def test_insert_into_empty(self) -> None:
+ doc = _doc()
+ doc.apply(
+ _tx(
+ CreateCell(
+ cell_id=CellId_t("new"),
+ code="x",
+ name="__",
+ config=CellConfig(),
+ )
+ )
+ )
+ assert _ids(doc) == snapshot(["new"])
+
+ def test_multiple(self) -> None:
+ doc = _doc("a")
+ doc.apply(
+ _tx(
+ CreateCell(
+ cell_id=CellId_t("x"),
+ code="1",
+ name="__",
+ config=CellConfig(),
+ ),
+ CreateCell(
+ cell_id=CellId_t("y"),
+ code="2",
+ name="__",
+ config=CellConfig(),
+ ),
+ )
+ )
+ assert _ids(doc) == snapshot(["a", "x", "y"])
+
+ def test_after_pending(self) -> None:
+ """A create can reference a cell added earlier in the same tx."""
+ doc = _doc("a")
+ doc.apply(
+ _tx(
+ CreateCell(
+ cell_id=CellId_t("x"),
+ code="1",
+ name="__",
+ config=CellConfig(),
+ ),
+ CreateCell(
+ cell_id=CellId_t("y"),
+ code="2",
+ name="__",
+ config=CellConfig(),
+ after=CellId_t("x"),
+ ),
+ )
+ )
+ assert _ids(doc) == snapshot(["a", "x", "y"])
+
+ def test_duplicate_id_raises(self) -> None:
+ doc = _doc("a")
+ with pytest.raises(ValueError, match="already exists"):
+ doc.apply(
+ _tx(
+ CreateCell(
+ cell_id=CellId_t("a"),
+ code="x",
+ name="__",
+ config=CellConfig(),
+ )
+ )
+ )
+
+ def test_stores_code_and_config(self) -> None:
+ doc = _doc()
+ cfg = CellConfig(hide_code=True, disabled=True)
+ doc.apply(
+ _tx(
+ CreateCell(
+ cell_id=CellId_t("a"),
+ code="import os",
+ name="imports",
+ config=cfg,
+ )
+ )
+ )
+ cell = doc.get_cell(CellId_t("a"))
+ assert cell.code == "import os"
+ assert cell.name == "imports"
+ assert cell.config.hide_code is True
+ assert cell.config.disabled is True
+
+
+# ------------------------------------------------------------------
+# DeleteCell
+# ------------------------------------------------------------------
+
+
+class TestDeleteCell:
+ def test_delete_single(self) -> None:
+ doc = _doc("a", "b", "c")
+ doc.apply(_tx(DeleteCell(cell_id=CellId_t("b"))))
+ assert _ids(doc) == snapshot(["a", "c"])
+
+ def test_delete_multiple(self) -> None:
+ doc = _doc("a", "b", "c")
+ doc.apply(
+ _tx(
+ DeleteCell(cell_id=CellId_t("a")),
+ DeleteCell(cell_id=CellId_t("c")),
+ )
+ )
+ assert _ids(doc) == snapshot(["b"])
+
+ def test_delete_all(self) -> None:
+ doc = _doc("a", "b")
+ doc.apply(
+ _tx(
+ DeleteCell(cell_id=CellId_t("a")),
+ DeleteCell(cell_id=CellId_t("b")),
+ )
+ )
+ assert _ids(doc) == snapshot([])
+
+ def test_delete_not_found(self) -> None:
+ doc = _doc("a")
+ with pytest.raises(KeyError):
+ doc.apply(_tx(DeleteCell(cell_id=CellId_t("missing"))))
+
+
+# ------------------------------------------------------------------
+# MoveCell
+# ------------------------------------------------------------------
+
+
+class TestMoveCell:
+ def test_move_after(self) -> None:
+ doc = _doc("a", "b", "c")
+ doc.apply(_tx(MoveCell(cell_id=CellId_t("a"), after=CellId_t("c"))))
+ assert _ids(doc) == snapshot(["b", "c", "a"])
+
+ def test_move_before(self) -> None:
+ doc = _doc("a", "b", "c")
+ doc.apply(_tx(MoveCell(cell_id=CellId_t("c"), before=CellId_t("a"))))
+ assert _ids(doc) == snapshot(["c", "a", "b"])
+
+ def test_no_anchor_raises(self) -> None:
+ doc = _doc("a", "b")
+ with pytest.raises(ValueError, match="before.*after"):
+ doc.apply(_tx(MoveCell(cell_id=CellId_t("a"))))
+
+
+# ------------------------------------------------------------------
+# SetCode
+# ------------------------------------------------------------------
+
+
+class TestSetCode:
+ def test_update_code(self) -> None:
+ doc = _doc("a", "b")
+ doc.apply(_tx(SetCode(cell_id=CellId_t("b"), code="new")))
+ assert doc.get_cell(CellId_t("b")).code == "new"
+ assert doc.get_cell(CellId_t("a")).code == "" # unchanged
+
+ def test_not_found(self) -> None:
+ doc = _doc("a")
+ with pytest.raises(KeyError):
+ doc.apply(_tx(SetCode(cell_id=CellId_t("missing"), code="x")))
+
+
+# ------------------------------------------------------------------
+# SetName
+# ------------------------------------------------------------------
+
+
+class TestSetName:
+ def test_update_name(self) -> None:
+ doc = _doc("a")
+ doc.apply(_tx(SetName(cell_id=CellId_t("a"), name="my_cell")))
+ assert doc.get_cell(CellId_t("a")).name == "my_cell"
+
+
+# ------------------------------------------------------------------
+# SetConfig
+# ------------------------------------------------------------------
+
+
+class TestSetConfig:
+ def test_partial_hide_code(self) -> None:
+ doc = _doc("a")
+ doc.apply(_tx(SetConfig(cell_id=CellId_t("a"), hide_code=True)))
+ cfg = doc.get_cell(CellId_t("a")).config
+ assert cfg.hide_code is True
+ assert cfg.disabled is False # unchanged default
+
+ def test_partial_disabled(self) -> None:
+ doc = _doc("a")
+ doc.apply(_tx(SetConfig(cell_id=CellId_t("a"), disabled=True)))
+ cfg = doc.get_cell(CellId_t("a")).config
+ assert cfg.disabled is True
+ assert cfg.hide_code is False # unchanged default
+
+ def test_multiple_fields(self) -> None:
+ doc = _doc("a")
+ doc.apply(
+ _tx(
+ SetConfig(cell_id=CellId_t("a"), hide_code=True, disabled=True)
+ )
+ )
+ cfg = doc.get_cell(CellId_t("a")).config
+ assert cfg.hide_code is True
+ assert cfg.disabled is True
+
+ def test_all_none_is_noop(self) -> None:
+ doc = _doc("a")
+ doc.apply(_tx(SetConfig(cell_id=CellId_t("a"))))
+ cfg = doc.get_cell(CellId_t("a")).config
+ assert cfg == CellConfig()
+
+ def test_preserves_existing(self) -> None:
+ """Setting one field preserves other non-default fields."""
+ doc = NotebookDocument(
+ [
+ NotebookCell(
+ id=CellId_t("a"),
+ code="",
+ name="__",
+ config=CellConfig(hide_code=True, column=2),
+ )
+ ]
+ )
+ doc.apply(_tx(SetConfig(cell_id=CellId_t("a"), disabled=True)))
+ cfg = doc.get_cell(CellId_t("a")).config
+ assert cfg.disabled is True
+ assert cfg.hide_code is True # preserved
+ assert cfg.column == 2 # preserved
+
+
+# ------------------------------------------------------------------
+# Validation
+# ------------------------------------------------------------------
+
+
+class TestValidation:
+ def test_delete_and_set_code_same_cell(self) -> None:
+ doc = _doc("a")
+ with pytest.raises(ValueError, match="delete.*update"):
+ doc.apply(
+ _tx(
+ SetCode(cell_id=CellId_t("a"), code="x"),
+ DeleteCell(cell_id=CellId_t("a")),
+ )
+ )
+
+ def test_set_code_and_delete_same_cell(self) -> None:
+ doc = _doc("a")
+ with pytest.raises(ValueError, match="update.*delete"):
+ doc.apply(
+ _tx(
+ DeleteCell(cell_id=CellId_t("a")),
+ SetCode(cell_id=CellId_t("a"), code="x"),
+ )
+ )
+
+ def test_delete_and_move_same_cell(self) -> None:
+ doc = _doc("a", "b")
+ with pytest.raises(ValueError, match="delete.*move"):
+ doc.apply(
+ _tx(
+ MoveCell(cell_id=CellId_t("a"), after=CellId_t("b")),
+ DeleteCell(cell_id=CellId_t("a")),
+ )
+ )
+
+ def test_double_delete(self) -> None:
+ doc = _doc("a")
+ with pytest.raises(ValueError, match="deleted more than once"):
+ doc.apply(
+ _tx(
+ DeleteCell(cell_id=CellId_t("a")),
+ DeleteCell(cell_id=CellId_t("a")),
+ )
+ )
+
+ def test_valid_mixed_ops(self) -> None:
+ doc = _doc("a", "b")
+ doc.apply(
+ _tx(
+ CreateCell(
+ cell_id=CellId_t("new"),
+ code="x",
+ name="__",
+ config=CellConfig(),
+ ),
+ SetCode(cell_id=CellId_t("a"), code="y"),
+ DeleteCell(cell_id=CellId_t("b")),
+ )
+ )
+ assert _ids(doc) == snapshot(["a", "new"])
+
+
+# ------------------------------------------------------------------
+# Versioning
+# ------------------------------------------------------------------
+
+
+class TestVersion:
+ def test_increments_on_apply(self) -> None:
+ doc = _doc("a")
+ assert doc.version == 0
+ doc.apply(_tx(SetCode(cell_id=CellId_t("a"), code="x")))
+ assert doc.version == 1
+ doc.apply(_tx(SetCode(cell_id=CellId_t("a"), code="y")))
+ assert doc.version == 2
+
+ def test_stamped_on_returned_tx(self) -> None:
+ doc = _doc("a")
+ tx = _tx(SetCode(cell_id=CellId_t("a"), code="x"))
+ assert tx.version is None
+ applied = doc.apply(tx)
+ assert applied.version == 1
+
+ def test_empty_tx_no_increment(self) -> None:
+ doc = _doc("a")
+ doc.apply(_tx(SetCode(cell_id=CellId_t("a"), code="x")))
+ assert doc.version == 1
+ applied = doc.apply(_tx())
+ assert doc.version == 1
+ assert applied.version == 1
+
+
+# ------------------------------------------------------------------
+# Combined ops
+# ------------------------------------------------------------------
+
+
+class TestCombined:
+ def test_delete_then_create(self) -> None:
+ doc = _doc("a", "b", "c")
+ doc.apply(
+ _tx(
+ DeleteCell(cell_id=CellId_t("b")),
+ CreateCell(
+ cell_id=CellId_t("new"),
+ code="d",
+ name="__",
+ config=CellConfig(),
+ after=CellId_t("a"),
+ ),
+ )
+ )
+ assert _ids(doc) == snapshot(["a", "new", "c"])
+
+ def test_create_then_set_code(self) -> None:
+ doc = _doc("a")
+ doc.apply(
+ _tx(
+ CreateCell(
+ cell_id=CellId_t("new"),
+ code="tmp",
+ name="__",
+ config=CellConfig(),
+ ),
+ SetCode(cell_id=CellId_t("new"), code="final"),
+ )
+ )
+ assert _ids(doc) == snapshot(["a", "new"])
+ assert doc.get_cell(CellId_t("new")).code == "final"
+
+ def test_create_then_move(self) -> None:
+ doc = _doc("a", "b")
+ doc.apply(
+ _tx(
+ CreateCell(
+ cell_id=CellId_t("new"),
+ code="x",
+ name="__",
+ config=CellConfig(),
+ ),
+ MoveCell(cell_id=CellId_t("new"), before=CellId_t("a")),
+ )
+ )
+ assert _ids(doc) == snapshot(["new", "a", "b"])
+
+ def test_source_preserved(self) -> None:
+ doc = _doc("a")
+ applied = doc.apply(
+ _tx(
+ SetCode(cell_id=CellId_t("a"), code="x"),
+ source="kernel",
+ )
+ )
+ assert applied.source == "kernel"
+
+
+# ------------------------------------------------------------------
+# Initialization
+# ------------------------------------------------------------------
+
+
+class TestInit:
+ def test_from_cells(self) -> None:
+ doc = _doc("a", "b", "c")
+ assert _ids(doc) == ["a", "b", "c"]
+
+ def test_empty(self) -> None:
+ doc = NotebookDocument()
+ assert _ids(doc) == []
+ assert doc.version == 0
+
+ def test_get_cell(self) -> None:
+ doc = _doc("a", "b")
+ cell = doc.get_cell(CellId_t("b"))
+ assert cell.id == CellId_t("b")
+
+ def test_get_cell_not_found(self) -> None:
+ doc = _doc("a")
+ with pytest.raises(KeyError):
+ doc.get_cell(CellId_t("missing"))
+
+ def test_get_returns_none(self) -> None:
+ doc = _doc("a")
+ assert doc.get(CellId_t("missing")) is None
+ assert doc.get(CellId_t("a")) is not None
+
+ def test_contains(self) -> None:
+ doc = _doc("a", "b")
+ assert CellId_t("a") in doc
+ assert CellId_t("missing") not in doc
+
+ def test_len(self) -> None:
+ assert len(_doc()) == 0
+ assert len(_doc("a", "b")) == 2
+
+ def test_iter(self) -> None:
+ doc = _doc("a", "b", "c")
+ assert list(doc) == [CellId_t("a"), CellId_t("b"), CellId_t("c")]
+
+ def test_repr(self) -> None:
+ doc = _doc("a")
+ assert "NotebookDocument(1 cells)" in repr(doc)
+
+
+# ------------------------------------------------------------------
+# ReorderCells
+# ------------------------------------------------------------------
+
+
+class TestReorderCells:
+ def test_reorder(self) -> None:
+ doc = _doc("a", "b", "c")
+ doc.apply(
+ _tx(
+ ReorderCells(
+ cell_ids=(CellId_t("c"), CellId_t("a"), CellId_t("b"))
+ )
+ )
+ )
+ assert _ids(doc) == snapshot(["c", "a", "b"])
+
+ def test_missing_ids_appended(self) -> None:
+ """Cells not in the reorder list are appended at the end."""
+ doc = _doc("a", "b", "c")
+ doc.apply(_tx(ReorderCells(cell_ids=(CellId_t("c"), CellId_t("a")))))
+ assert _ids(doc) == snapshot(["c", "a", "b"])
+
+ def test_unknown_ids_ignored(self) -> None:
+ """IDs not in the document are silently skipped."""
+ doc = _doc("a", "b")
+ doc.apply(
+ _tx(
+ ReorderCells(
+ cell_ids=(
+ CellId_t("b"),
+ CellId_t("unknown"),
+ CellId_t("a"),
+ )
+ )
+ )
+ )
+ assert _ids(doc) == snapshot(["b", "a"])
+
+ def test_reorder_single(self) -> None:
+ doc = _doc("a", "b", "c")
+ doc.apply(_tx(ReorderCells(cell_ids=(CellId_t("b"),))))
+ assert _ids(doc) == snapshot(["b", "a", "c"])
diff --git a/tests/_session/app_host/test_app_host.py b/tests/_session/app_host/test_app_host.py
index 847d50e71e..4917afeded 100644
--- a/tests/_session/app_host/test_app_host.py
+++ b/tests/_session/app_host/test_app_host.py
@@ -442,7 +442,12 @@ class TestAppHostMultipleClients:
session_consumer=Mock(),
mode=SessionMode.RUN,
app_metadata=Mock(),
- app_file_manager=Mock(path="/tmp/test_app.py"),
+ app_file_manager=Mock(
+ path="/tmp/test_app.py",
+ app=Mock(
+ cell_manager=Mock(cell_data=Mock(return_value=[]))
+ ),
+ ),
config_manager=Mock(
with_overrides=Mock(
return_value=Mock(