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 editable document model with local drafts (#11354)

Trevor Manz4b8be62dcb73
diff --git a/frontend/src/core/document/__tests__/draft.test.ts b/frontend/src/core/document/__tests__/draft.test.ts
new file mode 100644
index 0000000000..f470c6e30d
--- /dev/null
+++ b/frontend/src/core/document/__tests__/draft.test.ts
@@ -0,0 +1,322 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { describe, expect, it } from "vitest";
+import {
+ acknowledge,
+ createCell,
+ deleteCell,
+ type Draft,
+ type EditableCell,
+ editCell,
+ EMPTY_DRAFT,
+ setOrder,
+ toChanges,
+ viewDocument,
+} from "../draft";
+import { cell, CONFIG, document, withCells } from "./fixtures";
+
+const confirmed = document();
+
+function edits(...steps: Parameters<typeof editCell>[3][]): Draft {
+ return steps.reduce(
+ (draft, edit) => editCell(confirmed, draft, "c1", edit),
+ EMPTY_DRAFT,
+ );
+}
+
+describe("editCell", () => {
+ it("lets later fields win and merges config field by field", () => {
+ const draft = edits(
+ { code: "a", config: { hide_code: true } },
+ { name: "n", config: { column: 1, hide_code: undefined } },
+ );
+ expect(viewDocument(confirmed, draft).cells.get("c1")).toEqual({
+ id: "c1",
+ code: "a",
+ name: "n",
+ config: { ...CONFIG, hide_code: true, column: 1 },
+ });
+ });
+
+ it("keeps a reversal to the confirmed value as a draft", () => {
+ const draft = edits({ code: "local" }, { code: "x = 1" });
+ const remote = withCells(confirmed, { c1: cell("c1", "earlier edit") });
+ expect(viewDocument(remote, draft).cells.get("c1")?.code).toBe("x = 1");
+ });
+
+ it("accepts empty strings, false and null while ignoring undefined", () => {
+ const draft = edits(
+ { code: "", config: { column: 1, disabled: true } },
+ {
+ code: undefined,
+ config: { column: null, disabled: false, hide_code: undefined },
+ },
+ );
+ expect(viewDocument(confirmed, draft).cells.get("c1")).toEqual({
+ id: "c1",
+ code: "",
+ name: "_",
+ config: CONFIG,
+ });
+ });
+});
+
+describe("createCell and deleteCell", () => {
+ it("fills protocol defaults and places the cell in the view", () => {
+ const atEnd = createCell(EMPTY_DRAFT, { id: "c3", code: "3" });
+ const after = createCell(
+ EMPTY_DRAFT,
+ { id: "c3", code: "3" },
+ { after: "c1" },
+ );
+ const before = createCell(
+ EMPTY_DRAFT,
+ { id: "c3", code: "3" },
+ { before: "c1" },
+ );
+ const orphan = createCell(
+ EMPTY_DRAFT,
+ { id: "c3", code: "3" },
+ { after: "gone" },
+ );
+ expect(viewDocument(confirmed, atEnd).order).toEqual(["c1", "c2", "c3"]);
+ expect(viewDocument(confirmed, after).order).toEqual(["c1", "c3", "c2"]);
+ expect(viewDocument(confirmed, before).order).toEqual(["c3", "c1", "c2"]);
+ expect(viewDocument(confirmed, orphan).order).toEqual(["c1", "c2", "c3"]);
+ expect(viewDocument(confirmed, atEnd).cells.get("c3")).toEqual({
+ id: "c3",
+ code: "3",
+ name: "_",
+ config: CONFIG,
+ });
+ });
+
+ it("forgets a created cell when it is deleted", () => {
+ const draft = deleteCell(
+ createCell(EMPTY_DRAFT, { id: "c3", code: "" }),
+ "c3",
+ );
+ expect(toChanges(confirmed, draft)).toEqual([]);
+ expect(viewDocument(confirmed, draft).order).toEqual(["c1", "c2"]);
+ });
+});
+
+describe("viewDocument", () => {
+ it("preserves withheld source separately from an empty cell", () => {
+ const hidden = cell("c1", "", { code: null });
+ const empty = cell("c2", "");
+ const source = withCells(confirmed, { c1: hidden, c2: empty });
+ expect(viewDocument(source, EMPTY_DRAFT)).toEqual({
+ order: ["c1", "c2"],
+ cells: new Map([
+ ["c1", hidden],
+ ["c2", empty],
+ ]),
+ });
+ expect(toChanges(source, EMPTY_DRAFT)).toEqual([]);
+ });
+
+ it("follows the host for untouched fields, cells and order", () => {
+ const draft = edits({ code: "local", config: { hide_code: true } });
+ const remote = withCells(
+ confirmed,
+ {
+ c1: cell("c1", "remote", {
+ name: "renamed",
+ config: { ...CONFIG, disabled: true },
+ version: 2,
+ }),
+ c2: cell("c2", "remote too"),
+ },
+ ["c2", "c1"],
+ );
+ expect(viewDocument(remote, draft)).toEqual({
+ order: ["c2", "c1"],
+ cells: new Map<string, EditableCell | undefined>([
+ [
+ "c1",
+ {
+ id: "c1",
+ code: "local",
+ name: "renamed",
+ config: { ...CONFIG, disabled: true, hide_code: true },
+ },
+ ],
+ ["c2", remote.cells.get("c2")],
+ ]),
+ });
+ });
+});
+
+describe("toChanges", () => {
+ it.each([{ name: "renamed" }, { config: { hide_code: true } }])(
+ "withholds the whole request when an edited cell lacks source: %o",
+ (edit) => {
+ const hidden = withCells(confirmed, {
+ c1: cell("c1", "", { code: null }),
+ });
+ const created = createCell(EMPTY_DRAFT, { id: "c3", code: "" });
+ const draft = editCell(hidden, created, "c1", edit);
+ expect(toChanges(hidden, draft)).toBeNull();
+ expect(viewDocument(hidden, draft).cells.get("c1")?.code).toBeNull();
+ },
+ );
+
+ it.each(["replacement", ""])(
+ "uses explicitly supplied source %j when the host withholds it",
+ (code) => {
+ const hidden = withCells(confirmed, {
+ c1: cell("c1", "", { code: null }),
+ });
+ const draft = editCell(hidden, EMPTY_DRAFT, "c1", {
+ name: "renamed",
+ code,
+ });
+ expect(toChanges(hidden, draft)).toEqual([
+ {
+ kind: "put_cell",
+ base_etag: "c1-etag",
+ cell: { id: "c1", code, name: "renamed", config: CONFIG },
+ },
+ ]);
+ },
+ );
+
+ it("can delete and reorder cells without their source", () => {
+ const hidden = withCells(confirmed, {
+ c1: cell("c1", "", { code: null }),
+ c2: cell("c2", "", { code: null }),
+ });
+ expect(toChanges(hidden, deleteCell(EMPTY_DRAFT, "c1"))).toEqual([
+ { kind: "delete_cell", id: "c1", base_etag: "c1-etag" },
+ ]);
+ expect(toChanges(hidden, setOrder(EMPTY_DRAFT, ["c2", "c1"]))).toEqual([
+ { kind: "set_order", base_etag: "order-1", order: ["c2", "c1"] },
+ ]);
+ });
+
+ it("is empty for an empty draft and omits puts that change nothing", () => {
+ expect(toChanges(confirmed, EMPTY_DRAFT)).toEqual([]);
+ expect(
+ toChanges(confirmed, edits({ code: "local" }, { code: "x = 1" })),
+ ).toEqual([]);
+ });
+
+ it("puts the merged cell against the confirmed etag", () => {
+ const draft = edits({ code: "local" });
+ const remote = withCells(confirmed, {
+ c1: cell("c1", "remote", { name: "renamed", etag: "c1-etag-2" }),
+ });
+ expect(toChanges(remote, draft)).toEqual([
+ {
+ kind: "put_cell",
+ base_etag: "c1-etag-2",
+ cell: { id: "c1", code: "local", name: "renamed", config: CONFIG },
+ },
+ ]);
+ });
+
+ it.each([{ after: "c3" }, { before: "c3" }])(
+ "can anchor to a cell created earlier in the request: %o",
+ (placement) => {
+ let draft = createCell(EMPTY_DRAFT, { id: "c3", code: "3" });
+ draft = createCell(draft, { id: "c4", code: "4" }, placement);
+ expect(toChanges(confirmed, draft)).toEqual([
+ {
+ kind: "put_cell",
+ base_etag: null,
+ cell: { id: "c3", code: "3", name: "_", config: CONFIG },
+ },
+ {
+ kind: "put_cell",
+ base_etag: null,
+ cell: { id: "c4", code: "4", name: "_", config: CONFIG },
+ ...placement,
+ },
+ ]);
+ },
+ );
+
+ it.each([{ after: "c2" }, { before: "c2" }])(
+ "omits an anchor deleted earlier in the request: %o",
+ (placement) => {
+ let draft = deleteCell(EMPTY_DRAFT, "c2");
+ draft = createCell(draft, { id: "c3", code: "3" }, placement);
+ expect(toChanges(confirmed, draft)).toEqual([
+ { kind: "delete_cell", id: "c2", base_etag: "c2-etag" },
+ {
+ kind: "put_cell",
+ base_etag: null,
+ cell: { id: "c3", code: "3", name: "_", config: CONFIG },
+ },
+ ]);
+ },
+ );
+
+ it("creates, deletes, then sets the reconciled order", () => {
+ let draft = setOrder(EMPTY_DRAFT, ["c2", "c1"]);
+ draft = createCell(draft, { id: "c3", code: "3" }, { after: "c2" });
+ draft = deleteCell(draft, "c1");
+ expect(toChanges(confirmed, draft)).toEqual([
+ {
+ kind: "put_cell",
+ base_etag: null,
+ cell: { id: "c3", code: "3", name: "_", config: CONFIG },
+ after: "c2",
+ },
+ { kind: "delete_cell", id: "c1", base_etag: "c1-etag" },
+ { kind: "set_order", base_etag: "order-1", order: ["c2", "c3"] },
+ ]);
+ });
+});
+
+describe("acknowledge", () => {
+ it("releases accepted fields independently, keeping later code and config edits", () => {
+ const sent = edits({
+ code: "sent",
+ config: { hide_code: true, column: 1 },
+ });
+ const later = editCell(confirmed, sent, "c1", {
+ code: "typed more",
+ config: { column: 2 },
+ });
+ const remote = withCells(confirmed, {
+ c1: cell("c1", "remote", { config: { ...CONFIG, column: 1 } }),
+ });
+ expect(
+ viewDocument(remote, acknowledge(later, sent)).cells.get("c1"),
+ ).toEqual({
+ id: "c1",
+ code: "typed more",
+ name: "_",
+ config: { ...CONFIG, column: 2 },
+ });
+ });
+
+ it("turns an accepted creation into an edit of only the fields changed since", () => {
+ const sent = createCell(EMPTY_DRAFT, { id: "c3", code: "3" });
+ const later = editCell(confirmed, sent, "c3", { name: "named" });
+ const remote = withCells(confirmed, { c3: cell("c3", "remote code") });
+ expect(toChanges(remote, acknowledge(later, sent))).toEqual([
+ {
+ kind: "put_cell",
+ base_etag: "c3-etag",
+ cell: { id: "c3", code: "remote code", name: "named", config: CONFIG },
+ },
+ ]);
+ });
+
+ it("releases an accepted order but preserves a subsequent reorder", () => {
+ const sent = setOrder(EMPTY_DRAFT, ["c2", "c1"]);
+ const later = setOrder(sent, ["c1", "c2"]);
+ const remote = withCells(confirmed, {}, ["c2", "c1"]);
+ expect(toChanges(remote, acknowledge(sent, sent))).toEqual([]);
+ expect(toChanges(remote, acknowledge(later, sent))).toEqual([
+ {
+ kind: "set_order",
+ base_etag: remote.revision.order_etag,
+ order: ["c1", "c2"],
+ },
+ ]);
+ });
+});
diff --git a/frontend/src/core/document/__tests__/fixtures.ts b/frontend/src/core/document/__tests__/fixtures.ts
new file mode 100644
index 0000000000..252b1ac5f5
--- /dev/null
+++ b/frontend/src/core/document/__tests__/fixtures.ts
@@ -0,0 +1,92 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import type { Document } from "../../host/resources/document";
+import type * as Protocol from "@marimo-team/client/protocol";
+
+export const CONFIG: Protocol.CellConfig = {
+ column: null,
+ disabled: false,
+ hide_code: false,
+ expand_output: false,
+};
+
+export function cell(
+ id: Protocol.CellId,
+ code: string,
+ overrides: Partial<Protocol.Cell> = {},
+): Protocol.Cell {
+ return {
+ id,
+ notebook_id: "n1",
+ code,
+ name: "_",
+ config: CONFIG,
+ etag: `${id}-etag`,
+ code_hash: `${id}-hash`,
+ version: 1,
+ ...overrides,
+ };
+}
+
+/** A two-cell document, `c1` then `c2`. */
+export function document(notebookId: Protocol.NotebookId = "n1"): Document {
+ const cells = [
+ cell("c1", "x = 1", { notebook_id: notebookId }),
+ cell("c2", "y = 2", { notebook_id: notebookId }),
+ ];
+ return {
+ revision: {
+ notebook_id: notebookId,
+ order: cells.map((c) => c.id),
+ app_config: { width: "medium" },
+ etag: "document-1",
+ saved_etag: "document-1",
+ order_etag: "order-1",
+ app_config_etag: "config-1",
+ version: 1,
+ },
+ cells: new Map(cells.map((c) => [c.id, c])),
+ };
+}
+
+/** The document with some cells replaced or removed and the order updated. */
+export function withCells(
+ base: Document,
+ changes: Record<Protocol.CellId, Protocol.Cell | null>,
+ order?: readonly Protocol.CellId[],
+): Document {
+ const cells = new Map(base.cells);
+ for (const [id, next] of Object.entries(changes)) {
+ if (next === null) {
+ cells.delete(id);
+ } else {
+ cells.set(id, next);
+ }
+ }
+ const nextOrder = order
+ ? [...order]
+ : [
+ ...base.revision.order.filter((id) => cells.has(id)),
+ ...[...cells.keys()].filter((id) => !base.cells.has(id)),
+ ];
+ const orderChanged =
+ nextOrder.length !== base.revision.order.length ||
+ nextOrder.some((id, index) => id !== base.revision.order[index]);
+ const orderEtag = orderChanged
+ ? `order:${JSON.stringify(nextOrder)}`
+ : base.revision.order_etag;
+ return {
+ revision: {
+ ...base.revision,
+ order: nextOrder,
+ order_etag: orderEtag,
+ version: base.revision.version + 1,
+ etag: JSON.stringify([
+ orderEtag,
+ base.revision.app_config_etag,
+ ...nextOrder.map((id) => cells.get(id)?.etag),
+ ]),
+ },
+ cells,
+ };
+}
diff --git a/frontend/src/core/document/__tests__/model.test.ts b/frontend/src/core/document/__tests__/model.test.ts
new file mode 100644
index 0000000000..5eeaec276c
--- /dev/null
+++ b/frontend/src/core/document/__tests__/model.test.ts
@@ -0,0 +1,434 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { atom, createStore } from "jotai/vanilla";
+import { describe, expect, it, vi } from "vitest";
+import type { Document } from "../../host/resources/document";
+import {
+ createDocumentModel,
+ type DocumentEdit,
+ type DocumentEditor,
+} from "../model";
+import { cell, document, withCells } from "./fixtures";
+
+function setup(initial: Document | null = document()) {
+ const store = createStore();
+ const source = atom(initial);
+ const model = createDocumentModel(store, source);
+ return {
+ store,
+ source,
+ ...model,
+ edit: (callback: DocumentEdit) => store.set(model.editAtom, callback),
+ };
+}
+
+describe("document model", () => {
+ it("distinguishes unavailable changes from an unchanged document", () => {
+ const { store, source, changesAtom } = setup(null);
+ expect(store.get(changesAtom)).toBeNull();
+ store.set(source, document());
+ expect(store.get(changesAtom)).toEqual([]);
+ store.set(source, null);
+ expect(store.get(changesAtom)).toBeNull();
+ });
+
+ it("keeps metadata drafts while source is unavailable and follows its return", () => {
+ const initial = document();
+ const { store, source, cellAtom, changesAtom, edit } = setup(initial);
+ edit((tx) => tx.setName("c1", "local name"));
+ const hidden = withCells(initial, {
+ c1: cell("c1", "", { code: null }),
+ });
+ store.set(source, hidden);
+ expect(store.get(cellAtom("c1"))).toEqual({
+ id: "c1",
+ code: null,
+ name: "local name",
+ config: cell("c1", "").config,
+ });
+ expect(store.get(changesAtom)).toBeNull();
+
+ store.set(
+ source,
+ withCells(hidden, {
+ c1: cell("c1", "updated source", { etag: "latest" }),
+ }),
+ );
+ expect(store.get(changesAtom)).toEqual([
+ {
+ kind: "put_cell",
+ base_etag: "latest",
+ cell: {
+ id: "c1",
+ code: "updated source",
+ name: "local name",
+ config: cell("c1", "").config,
+ },
+ },
+ ]);
+ });
+
+ it("rebases a local order onto the latest host order and its precondition", () => {
+ const { store, source, orderAtom, changesAtom, edit } = setup();
+ edit((tx) => tx.setOrder(["c2", "c1"]));
+ store.set(
+ source,
+ withCells(document(), { c3: cell("c3", "new") }, ["c1", "c3", "c2"]),
+ );
+ expect(store.get(orderAtom)).toEqual(["c2", "c1", "c3"]);
+ expect(store.get(changesAtom)).toEqual([
+ {
+ kind: "set_order",
+ base_etag: 'order:["c1","c3","c2"]',
+ order: ["c2", "c1", "c3"],
+ },
+ ]);
+ });
+
+ it.each(["before", "after"] as const)(
+ "appends a creation when its %s anchor was removed remotely",
+ (direction) => {
+ const { store, source, orderAtom, changesAtom, edit } = setup();
+ edit((tx) =>
+ tx.createCell({ id: "c3", code: "" }, { [direction]: "c1" }),
+ );
+ store.set(source, withCells(document(), { c1: null }));
+ expect(store.get(orderAtom)).toEqual(["c2", "c3"]);
+ expect(store.get(changesAtom)).toEqual([
+ {
+ kind: "put_cell",
+ base_etag: null,
+ cell: {
+ id: "c3",
+ code: "",
+ name: "_",
+ config: cell("c3", "").config,
+ },
+ },
+ ]);
+ },
+ );
+
+ it("publishes the visible order when an anchor is deleted later in the draft", () => {
+ const { store, orderAtom, changesAtom, edit } = setup();
+ edit((tx) => {
+ tx.setCode("c1", "edited before creation");
+ tx.createCell({ id: "c3", code: "" }, { after: "c1" });
+ tx.deleteCell("c1");
+ });
+ expect(store.get(orderAtom)).toEqual(["c3", "c2"]);
+ expect(store.get(changesAtom)).toEqual([
+ { kind: "delete_cell", id: "c1", base_etag: "c1-etag" },
+ {
+ kind: "put_cell",
+ base_etag: null,
+ cell: { id: "c3", code: "", name: "_", config: cell("c3", "").config },
+ },
+ { kind: "set_order", base_etag: "order-1", order: ["c3", "c2"] },
+ ]);
+ });
+
+ it("does not release a draft because the host caught up", () => {
+ const initial = document();
+ const { store, source, cellAtom, edit } = setup(initial);
+ edit((tx) => tx.setCode("c1", "local"));
+ for (const code of ["local", "later remote edit"]) {
+ store.set(source, withCells(initial, { c1: cell("c1", code) }));
+ expect(store.get(cellAtom("c1"))?.code).toBe("local");
+ }
+ });
+
+ it("keeps drafts separate when notebooks reuse cell ids", () => {
+ const { store, source, cellAtom, edit } = setup();
+ edit((tx) => tx.setCode("c1", "first notebook"));
+ store.set(source, document("n2"));
+ expect(store.get(cellAtom("c1"))?.code).toBe("x = 1");
+ edit((tx) => tx.setCode("c1", "second notebook"));
+ store.set(source, document("n1"));
+ expect(store.get(cellAtom("c1"))?.code).toBe("first notebook");
+ store.set(source, document("n2"));
+ expect(store.get(cellAtom("c1"))?.code).toBe("second notebook");
+ });
+
+ it("does not repeat a satisfied deletion without mounted readers", () => {
+ const { store, source, cellAtom, changesAtom, edit } = setup();
+ edit((tx) => {
+ tx.deleteCell("c1");
+ tx.setCode("c2", "keep this draft");
+ });
+ const removed = withCells(document(), { c1: null });
+ store.set(source, removed);
+ // No reads between snapshots: reconciliation must observe the removal.
+ store.set(
+ source,
+ withCells(removed, { c1: cell("c1", "restored") }, ["c1", "c2"]),
+ );
+ expect(store.get(cellAtom("c1"))?.code).toBe("restored");
+ expect(store.get(cellAtom("c2"))?.code).toBe("keep this draft");
+ expect(store.get(changesAtom)).toEqual([
+ {
+ kind: "put_cell",
+ base_etag: "c2-etag",
+ cell: {
+ id: "c2",
+ code: "keep this draft",
+ name: "_",
+ config: cell("c2", "").config,
+ },
+ },
+ ]);
+ });
+
+ it("retains edits when the host removes a cell and blocks partial submissions", () => {
+ const { store, source, cellAtom, changesAtom, edit } = setup();
+ edit((tx) => {
+ tx.setCode("c1", "recover this code");
+ tx.setCode("c2", "another edit");
+ });
+ const removed = withCells(document(), { c1: null });
+ store.set(source, removed);
+ expect(store.get(changesAtom)).toBeNull();
+ store.set(source, withCells(removed, { c1: cell("c1", "restored") }));
+ expect(store.get(cellAtom("c1"))?.code).toBe("recover this code");
+ expect(store.get(changesAtom)).toHaveLength(2);
+ });
+
+ it("composes creation, field edits, deletion and order in one publication", () => {
+ const { store, cellAtom, orderAtom, edit } = setup();
+ const onOrder = vi.fn(() => {
+ expect(store.get(cellAtom("c3"))).toEqual({
+ id: "c3",
+ code: "updated",
+ name: "example",
+ config: { ...cell("c3", "").config, hide_code: true },
+ });
+ expect(store.get(cellAtom("c1"))).toBeUndefined();
+ });
+ const unsubscribeOrder = store.sub(orderAtom, onOrder);
+ edit((tx) => {
+ tx.createCell({ id: "c3", code: "3" }, { after: "c2" });
+ tx.setCode("c3", "updated");
+ tx.setName("c3", "example");
+ tx.updateConfig("c3", { hide_code: true });
+ tx.deleteCell("c1");
+ tx.setOrder(["c3", "c2"]);
+ expect(store.get(orderAtom)).toEqual(["c1", "c2"]);
+ expect(store.get(cellAtom("c3"))).toBeUndefined();
+ });
+ expect(store.get(orderAtom)).toEqual(["c3", "c2"]);
+ expect(onOrder).toHaveBeenCalledOnce();
+ unsubscribeOrder();
+ });
+
+ it("does not notify subscribers for edits that change nothing", () => {
+ const { store, cellAtom, orderAtom, edit } = setup();
+ const onCell = vi.fn();
+ const onOrder = vi.fn();
+ const unsubscribeCell = store.sub(cellAtom("c1"), onCell);
+ const unsubscribeOrder = store.sub(orderAtom, onOrder);
+ edit((tx) => {
+ tx.setCode("c1", "x = 1");
+ tx.updateConfig("c1", { column: null });
+ });
+ expect(onCell).not.toHaveBeenCalled();
+ edit((tx) => tx.setCode("c1", "local"));
+ edit((tx) => tx.setCode("c1", "local"));
+ edit((tx) => tx.setOrder(["c1", "c2"]));
+ expect(onCell).toHaveBeenCalledOnce();
+ expect(onOrder).not.toHaveBeenCalled();
+ unsubscribeCell();
+ unsubscribeOrder();
+ });
+
+ it("isolates cell, order and configuration subscriptions across local and host updates", () => {
+ const initial = document();
+ const { store, source, cellAtom, orderAtom, appConfigAtom, edit } =
+ setup(initial);
+ edit((tx) => {
+ tx.setCode("c1", "local");
+ tx.createCell({ id: "c3", code: "new" });
+ });
+ const c1 = cellAtom("c1");
+ const first = store.get(c1);
+ const order = store.get(orderAtom);
+ const config = store.get(appConfigAtom);
+ const onFirst = vi.fn();
+ const onSecond = vi.fn();
+ const onOrder = vi.fn();
+ const onConfig = vi.fn();
+ const unsubscribe = [
+ store.sub(c1, onFirst),
+ store.sub(cellAtom("c2"), onSecond),
+ store.sub(orderAtom, onOrder),
+ store.sub(appConfigAtom, onConfig),
+ ];
+
+ edit((tx) => tx.setCode("c2", "other local"));
+ const remote = withCells(initial, {
+ c1: cell("c1", "remote", { version: 2, etag: "new-etag" }),
+ });
+ store.set(source, {
+ ...remote,
+ revision: {
+ ...remote.revision,
+ order: [...initial.revision.order],
+ app_config: { ...initial.revision.app_config },
+ },
+ });
+ expect(store.get(c1)).toBe(first);
+ expect(store.get(orderAtom)).toBe(order);
+ expect(store.get(appConfigAtom)).toBe(config);
+ expect(onFirst).not.toHaveBeenCalled();
+ expect(onSecond).toHaveBeenCalledOnce();
+ expect(onOrder).not.toHaveBeenCalled();
+ expect(onConfig).not.toHaveBeenCalled();
+
+ store.set(
+ source,
+ withCells(remote, {
+ c1: cell("c1", "remote", { name: "renamed" }),
+ }),
+ );
+ expect(store.get(cellAtom("c1"))).toEqual({
+ id: "c1",
+ code: "local",
+ name: "renamed",
+ config: cell("c1", "").config,
+ });
+ expect(onFirst).toHaveBeenCalledOnce();
+ edit((tx) => tx.setOrder(["c3", "c2", "c1"]));
+ expect(onOrder).toHaveBeenCalledOnce();
+ expect(onFirst).toHaveBeenCalledOnce();
+ store.set(source, {
+ ...remote,
+ revision: { ...remote.revision, app_config: { width: "full" } },
+ });
+ expect(onConfig).toHaveBeenCalledOnce();
+ unsubscribe.forEach((fn) => fn());
+ });
+
+ it.each([
+ [
+ "a missing placement anchor",
+ (tx: DocumentEditor) =>
+ tx.createCell({ id: "c3", code: "" }, { after: "missing" }),
+ "Cell missing does not exist",
+ ],
+ [
+ "a deleted placement anchor",
+ (tx: DocumentEditor) => {
+ tx.deleteCell("c2");
+ tx.createCell({ id: "c3", code: "" }, { before: "c2" });
+ },
+ "Cell c2 does not exist",
+ ],
+ [
+ "an exception",
+ () => {
+ throw new Error("failed");
+ },
+ "failed",
+ ],
+ [
+ "a missing cell",
+ (tx: DocumentEditor) => tx.setCode("missing", "code"),
+ "Cell missing does not exist",
+ ],
+ [
+ "a deleted cell",
+ (tx: DocumentEditor) => {
+ tx.deleteCell("c2");
+ tx.setName("c2", "missing");
+ },
+ "Cell c2 does not exist",
+ ],
+ [
+ "a duplicate cell",
+ (tx: DocumentEditor) => tx.createCell({ id: "c1", code: "duplicate" }),
+ "Cell c1 already exists",
+ ],
+ [
+ "an incomplete order",
+ (tx: DocumentEditor) => tx.setOrder(["c1"]),
+ "Cell order must contain every cell exactly once",
+ ],
+ [
+ "a duplicate in the order",
+ (tx: DocumentEditor) => tx.setOrder(["c1", "c1"]),
+ "Cell order must contain every cell exactly once",
+ ],
+ [
+ "an unknown cell in the order",
+ (tx: DocumentEditor) => tx.setOrder(["c1", "missing"]),
+ "Cell order must contain every cell exactly once",
+ ],
+ [
+ "an invalid config",
+ (tx: DocumentEditor) => tx.updateConfig("c2", { column: 0.5 }),
+ "Invalid input",
+ ],
+ ])("rolls back the whole transaction for %s", (_, fail, message) => {
+ const { store, changesAtom, cellAtom, edit } = setup();
+ const onChange = vi.fn();
+ const unsubscribe = store.sub(cellAtom("c1"), onChange);
+ expect(() =>
+ edit((tx) => {
+ tx.setCode("c1", "not committed");
+ fail(tx);
+ }),
+ ).toThrow(message);
+ expect(store.get(changesAtom)).toEqual([]);
+ expect(onChange).not.toHaveBeenCalled();
+ edit((tx) => tx.setCode("c1", "next transaction"));
+ expect(store.get(cellAtom("c1"))?.code).toBe("next transaction");
+ unsubscribe();
+ });
+
+ it("expires the editor after a transaction", () => {
+ const { store, cellAtom, edit } = setup();
+ let saved: DocumentEditor | undefined;
+ edit((tx) => {
+ saved = tx;
+ tx.setCode("c1", "committed");
+ });
+ expect(() => saved?.setCode("c1", "too late")).toThrow("has ended");
+ expect(store.get(cellAtom("c1"))?.code).toBe("committed");
+ });
+
+ it("rejects asynchronous transactions without publishing before or after await", async () => {
+ const { store, changesAtom, edit } = setup();
+ expect(() =>
+ edit(async (tx) => {
+ tx.setCode("c1", "before await");
+ await Promise.resolve();
+ tx.setCode("c1", "after await");
+ }),
+ ).toThrow("must be synchronous");
+ await Promise.resolve();
+ expect(store.get(changesAtom)).toEqual([]);
+ });
+
+ it("rejects nested transactions without overwriting drafts", () => {
+ const { store, changesAtom, edit } = setup();
+ expect(() =>
+ edit((tx) => {
+ tx.setCode("c1", "outer");
+ edit((inner) => inner.setCode("c2", "inner"));
+ }),
+ ).toThrow("cannot be nested");
+ expect(store.get(changesAtom)).toEqual([]);
+ });
+
+ it("does not commit against a source replaced during the callback", () => {
+ const { store, source, changesAtom, edit } = setup();
+ expect(() =>
+ edit((tx) => {
+ tx.setCode("c1", "old notebook");
+ store.set(source, document("n2"));
+ }),
+ ).toThrow("changed during the transaction");
+ expect(store.get(changesAtom)).toEqual([]);
+ store.set(source, document());
+ expect(store.get(changesAtom)).toEqual([]);
+ });
+});
diff --git a/frontend/src/core/document/__tests__/submission.test.ts b/frontend/src/core/document/__tests__/submission.test.ts
new file mode 100644
index 0000000000..65ccfdf0a6
--- /dev/null
+++ b/frontend/src/core/document/__tests__/submission.test.ts
@@ -0,0 +1,334 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { atom, createStore } from "jotai/vanilla";
+import { describe, expect, it, vi } from "vitest";
+import type { Document } from "../../host/resources/document";
+import { createDocumentModel, type DocumentSubmission } from "../model";
+import { cell, document, withCells } from "./fixtures";
+
+function setup() {
+ const store = createStore();
+ const source = atom<Document | null>(document());
+ const model = createDocumentModel(store, source);
+ return {
+ store,
+ source,
+ ...model,
+ submit() {
+ const submission = store.set(model.submitAtom);
+ if (submission === null) {
+ throw new Error("Expected a submission");
+ }
+ return submission;
+ },
+ settle(submission: DocumentSubmission, confirmed: Document) {
+ store.set(model.settleAtom, submission, confirmed.revision);
+ },
+ };
+}
+
+describe("document submissions", () => {
+ it.each(["host source", "replacement code"] as const)(
+ "retains an unsendable draft until it receives %s",
+ (recovery) => {
+ const {
+ store,
+ source,
+ editAtom,
+ changesAtom,
+ submitAtom,
+ submit,
+ settle,
+ } = setup();
+ const hidden = withCells(document(), {
+ c1: cell("c1", "", { code: null }),
+ });
+ store.set(source, hidden);
+ store.set(editAtom, (tx) => {
+ tx.setCode("c2", "other edit");
+ tx.setName("c1", "renamed");
+ });
+ expect(store.get(changesAtom)).toBeNull();
+ expect(store.set(submitAtom)).toBeNull();
+ expect(store.set(submitAtom)).toBeNull();
+
+ const code = recovery === "host source" ? "revealed" : "";
+ if (recovery === "host source") {
+ store.set(source, withCells(hidden, { c1: cell("c1", code) }));
+ } else {
+ store.set(editAtom, (tx) => tx.setCode("c1", code));
+ }
+ const sent = submit();
+ expect(sent.changes).toEqual([
+ {
+ kind: "put_cell",
+ base_etag: "c2-etag",
+ cell: {
+ id: "c2",
+ code: "other edit",
+ name: "_",
+ config: cell("c2", "").config,
+ },
+ },
+ {
+ kind: "put_cell",
+ base_etag: "c1-etag",
+ cell: {
+ id: "c1",
+ code,
+ name: "renamed",
+ config: cell("c1", "").config,
+ },
+ },
+ ]);
+ const accepted = withCells(store.get(source)!, {
+ c1: cell("c1", code, { name: "renamed" }),
+ c2: cell("c2", "other edit"),
+ });
+ settle(sent, accepted);
+ store.set(source, accepted);
+ expect(store.get(changesAtom)).toEqual([]);
+ },
+ );
+
+ it.each(["response", "stream"] as const)(
+ "preserves later typing when the %s arrives first",
+ (first) => {
+ const {
+ store,
+ source,
+ editAtom,
+ cellAtom,
+ changesAtom,
+ submitAtom,
+ submit,
+ settle,
+ } = setup();
+ store.set(editAtom, (tx) => {
+ tx.setCode("c1", "sent");
+ tx.updateConfig("c1", { hide_code: true });
+ });
+ const sent = submit();
+ store.set(editAtom, (tx) => tx.setCode("c1", "still typing"));
+ const confirmed = withCells(document(), {
+ c1: cell("c1", "sent", {
+ etag: "accepted",
+ config: { ...cell("c1", "").config, hide_code: true },
+ }),
+ });
+ const onCell = vi.fn();
+ store.sub(cellAtom("c1"), onCell);
+ const arrivals = {
+ response: () => settle(sent, confirmed),
+ stream: () => store.set(source, confirmed),
+ };
+ arrivals[first]();
+ expect(store.set(submitAtom)).toBeNull();
+ arrivals[first === "response" ? "stream" : "response"]();
+ expect(onCell).not.toHaveBeenCalled();
+ expect(store.get(cellAtom("c1"))?.code).toBe("still typing");
+ expect(store.get(changesAtom)).toEqual([
+ {
+ kind: "put_cell",
+ base_etag: "accepted",
+ cell: {
+ id: "c1",
+ code: "still typing",
+ name: "_",
+ config: confirmed.cells.get("c1")?.config,
+ },
+ },
+ ]);
+ const next = submit();
+ settle(sent, confirmed);
+ expect(store.set(submitAtom)).toBeNull();
+ const updated = withCells(confirmed, {
+ c1: cell("c1", "still typing", {
+ config: confirmed.cells.get("c1")!.config,
+ }),
+ });
+ settle(next, updated);
+ store.set(source, updated);
+ expect(store.get(changesAtom)).toEqual([]);
+ },
+ );
+
+ it.each(["response", "stream"] as const)(
+ "never shows a cancelled creation when the %s arrives first",
+ (first) => {
+ const {
+ store,
+ source,
+ editAtom,
+ cellAtom,
+ orderAtom,
+ changesAtom,
+ submit,
+ settle,
+ } = setup();
+ store.set(editAtom, (tx) => tx.createCell({ id: "c3", code: "new" }));
+ const sent = submit();
+ store.set(editAtom, (tx) => tx.deleteCell("c3"));
+ const onCell = vi.fn();
+ store.sub(cellAtom("c3"), onCell);
+ // An unrelated revision before the creation must not forget the deletion.
+ const intermediate = withCells(document(), { c2: cell("c2", "remote") });
+ store.set(source, intermediate);
+ const confirmed = withCells(intermediate, { c3: cell("c3", "new") });
+ const arrivals = {
+ response: () => settle(sent, confirmed),
+ stream: () => store.set(source, confirmed),
+ };
+ arrivals[first]();
+ arrivals[first === "response" ? "stream" : "response"]();
+ expect(onCell).not.toHaveBeenCalled();
+ expect(store.get(orderAtom)).toEqual(["c1", "c2"]);
+ expect(store.get(changesAtom)).toEqual([
+ { kind: "delete_cell", id: "c3", base_etag: "c3-etag" },
+ ]);
+ const deletion = submit();
+ const removed = withCells(confirmed, { c3: null });
+ store.set(source, removed);
+ settle(deletion, removed);
+ settle(sent, confirmed);
+ expect(store.get(changesAtom)).toEqual([]);
+ },
+ );
+
+ it("waits for the response's later revision and follows subsequent host edits", () => {
+ const { store, source, editAtom, cellAtom, submitAtom, submit, settle } =
+ setup();
+ store.set(editAtom, (tx) => tx.setCode("c1", "sent"));
+ const sent = submit();
+ const edited = withCells(document(), { c1: cell("c1", "sent") });
+ const response = withCells(edited, { c2: cell("c2", "mirrored update") });
+ settle(sent, response);
+ store.set(source, edited);
+ expect(store.set(submitAtom)).toBeNull();
+ const later = withCells(response, {
+ c1: cell("c1", "another client's edit"),
+ });
+ const seen: (string | null | undefined)[] = [];
+ store.sub(cellAtom("c1"), () => seen.push(store.get(cellAtom("c1"))?.code));
+ store.set(source, later);
+ expect(seen).toEqual(["another client's edit"]);
+ expect(store.set(submitAtom)).toBeNull();
+ });
+
+ it.each(["before reset", "during reset", "after snapshot"] as const)(
+ "confirms a submission across reset when its response arrives %s",
+ (arrival) => {
+ const { store, source, editAtom, cellAtom, submit, settle } = setup();
+ store.set(editAtom, (tx) => tx.setCode("c1", "unsaved"));
+ const sent = submit();
+ const old = withCells(document(), { c1: cell("c1", "unsaved") });
+ store.set(editAtom, (tx) => tx.setCode("c1", "newer typing"));
+ if (arrival === "before reset") {
+ settle(sent, old);
+ }
+ store.set(source, null);
+ if (arrival === "during reset") {
+ settle(sent, old);
+ }
+ const fresh = withCells(old, { c2: cell("c2", "unrelated") });
+ store.set(source, fresh);
+ if (arrival === "after snapshot") {
+ settle(sent, old);
+ }
+ expect(store.get(cellAtom("c1"))?.code).toBe("newer typing");
+ const retried = submit();
+ const accepted = withCells(fresh, { c1: cell("c1", "newer typing") });
+ settle(retried, accepted);
+ store.set(source, accepted);
+ store.set(source, withCells(accepted, { c1: cell("c1", "remote") }));
+ expect(store.get(cellAtom("c1"))?.code).toBe("remote");
+ },
+ );
+
+ it("invalidates submissions when switching notebooks, retaining each draft", () => {
+ const { store, source, editAtom, cellAtom, submit, settle } = setup();
+ store.set(editAtom, (tx) => tx.setCode("c1", "first"));
+ const sent = submit();
+ store.set(source, document("n2"));
+ store.set(editAtom, (tx) => tx.setCode("c1", "second"));
+ store.set(source, withCells(document(), { c2: cell("c2", "remote") }));
+ settle(sent, withCells(document(), { c1: cell("c1", "first") }));
+ expect(store.get(cellAtom("c1"))?.code).toBe("first");
+ store.set(source, document("n2"));
+ expect(store.get(cellAtom("c1"))?.code).toBe("second");
+ });
+
+ it("retries a rejected edit with fresh preconditions and ignores its late reply", () => {
+ const { store, source, editAtom, settleAtom, submitAtom, submit, settle } =
+ setup();
+ store.set(editAtom, (tx) => tx.setCode("c1", "local"));
+ const sent = submit();
+ store.set(settleAtom, sent, null);
+ const remote = withCells(document(), {
+ c1: cell("c1", "remote", { name: "renamed", etag: "fresh" }),
+ });
+ store.set(source, remote);
+ const retry = submit();
+ expect(retry.changes).toEqual([
+ {
+ kind: "put_cell",
+ base_etag: "fresh",
+ cell: {
+ id: "c1",
+ code: "local",
+ name: "renamed",
+ config: cell("c1", "").config,
+ },
+ },
+ ]);
+ settle(sent, remote);
+ expect(store.set(submitAtom)).toBeNull();
+ });
+
+ it("does not treat a response for another notebook as acceptance", () => {
+ const { store, editAtom, settleAtom, submitAtom, submit } = setup();
+ store.set(editAtom, (tx) => tx.setCode("c1", "local"));
+ const sent = submit();
+ expect(() => store.set(settleAtom, sent, document("n2").revision)).toThrow(
+ "another notebook",
+ );
+ expect(store.set(submitAtom)).toBeNull();
+ });
+
+ it("releases an unsent reversal without making a request", () => {
+ const { store, source, editAtom, cellAtom, submitAtom } = setup();
+ store.set(editAtom, (tx) => tx.setCode("c1", "local"));
+ store.set(editAtom, (tx) => tx.setCode("c1", "x = 1"));
+ expect(store.set(submitAtom)).toBeNull();
+ store.set(source, withCells(document(), { c1: cell("c1", "remote") }));
+ expect(store.get(cellAtom("c1"))?.code).toBe("remote");
+ });
+
+ it("stops observing and accepting work after disposal", () => {
+ const {
+ store,
+ source,
+ editAtom,
+ orderAtom,
+ submitAtom,
+ submit,
+ settle,
+ dispose,
+ } = setup();
+ store.set(editAtom, (tx) => tx.setCode("c1", "local"));
+ const sent = submit();
+ dispose();
+ const onOrder = vi.fn();
+ store.sub(orderAtom, onOrder);
+ const confirmed = withCells(document(), { c1: cell("c1", "local") });
+ store.set(source, confirmed);
+ settle(sent, confirmed);
+ const edit = vi.fn();
+ store.set(editAtom, edit);
+ dispose();
+ expect(edit).not.toHaveBeenCalled();
+ expect(onOrder).not.toHaveBeenCalled();
+ expect(store.get(orderAtom)).toBeNull();
+ expect(store.set(submitAtom)).toBeNull();
+ });
+});
diff --git a/frontend/src/core/document/draft.ts b/frontend/src/core/document/draft.ts
new file mode 100644
index 0000000000..ae76a4b363
--- /dev/null
+++ b/frontend/src/core/document/draft.ts
@@ -0,0 +1,472 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import type { Document } from "../host/resources/document";
+import * as Protocol from "@marimo-team/client/protocol";
+
+/** The fields a client edits. Null code means the host withheld source. */
+export type EditableCell = Readonly<
+ Pick<Protocol.Cell, "id" | "code" | "name">
+> & {
+ readonly config: Readonly<Protocol.CellConfig>;
+};
+
+type CellWithSource = EditableCell & { readonly code: string };
+
+/** A confirmed document with a draft applied. */
+export interface EditableDocument {
+ readonly order: readonly Protocol.CellId[];
+ readonly cells: ReadonlyMap<Protocol.CellId, EditableCell>;
+}
+
+/** Fields to change on a cell. A field left out keeps its value, including within config. */
+export interface CellEdit {
+ readonly code?: string;
+ readonly name?: string;
+ readonly config?: Partial<Readonly<Protocol.CellConfig>>;
+}
+
+type MutableEdit = { -readonly [K in keyof CellEdit]: CellEdit[K] };
+
+/** Where a created cell goes. With neither, at the end. */
+export interface Placement {
+ readonly after?: Protocol.CellId;
+ readonly before?: Protocol.CellId;
+}
+
+/** What this client wants one cell to become. */
+type CellDraft =
+ | { readonly kind: "edit"; readonly edit: CellEdit }
+ | {
+ readonly kind: "create";
+ readonly cell: CellWithSource;
+ readonly placement: Placement;
+ }
+ | { readonly kind: "delete" };
+
+/**
+ * This client's changes, layered over a confirmed document.
+ *
+ * A draft is a document delta in the terms of the host's edit request:
+ * per-cell puts and deletes, and optionally the order as a whole. The view
+ * a person edits and the request that synchronizes it both derive from it.
+ */
+export interface Draft {
+ readonly cells: ReadonlyMap<Protocol.CellId, CellDraft>;
+ /** The full order to apply, or null to follow the host's. */
+ readonly order: readonly Protocol.CellId[] | null;
+}
+
+export const EMPTY_DRAFT: Draft = { cells: new Map(), order: null };
+
+export function isEmptyDraft(draft: Draft): boolean {
+ return draft.cells.size === 0 && draft.order === null;
+}
+
+// Merging -------------------------------------------------------------------
+
+/** Copy the defined fields of `patch` over `base`. */
+function assignDefined<T extends object>(base: T, patch: Partial<T>): T {
+ const result = { ...base };
+ for (const key in patch) {
+ const value = patch[key];
+ if (value !== undefined) {
+ result[key] = value;
+ }
+ }
+ return result;
+}
+
+/** The defined fields of `to` that differ from `from`. */
+function differingFields<T extends object>(
+ from: T,
+ to: Partial<T>,
+): Partial<T> {
+ const result: Partial<T> = {};
+ for (const key in to) {
+ const value = to[key];
+ if (value !== undefined && value !== from[key]) {
+ result[key] = value;
+ }
+ }
+ return result;
+}
+
+function isEmpty(object: object): boolean {
+ return Object.keys(object).length === 0;
+}
+
+function sameOrder(
+ a: readonly Protocol.CellId[],
+ b: readonly Protocol.CellId[],
+): boolean {
+ return a.length === b.length && a.every((id, index) => id === b[index]);
+}
+
+/** Combine two edits, the later one winning field by field. */
+function mergeEdit(previous: CellEdit, edit: CellEdit): CellEdit {
+ const merged = assignDefined(previous, edit);
+ return edit.config === undefined
+ ? merged
+ : { ...merged, config: assignDefined(previous.config ?? {}, edit.config) };
+}
+
+/** The cell with an edit applied, as a new object with the editable fields. */
+function applyEdit(cell: CellWithSource, edit: CellEdit): CellWithSource;
+function applyEdit(cell: EditableCell, edit: CellEdit): EditableCell;
+function applyEdit(cell: EditableCell, edit: CellEdit): EditableCell {
+ return {
+ id: cell.id,
+ code: edit.code ?? cell.code,
+ name: edit.name ?? cell.name,
+ config:
+ edit.config === undefined
+ ? cell.config
+ : assignDefined(cell.config, edit.config),
+ };
+}
+
+export function sameCell(a: EditableCell, b: EditableCell): boolean {
+ return (
+ a.id === b.id &&
+ a.code === b.code &&
+ a.name === b.name &&
+ isEmpty(differingFields(a.config, b.config))
+ );
+}
+
+/** The edit that turns `from` into `to`. Empty when they are the same. */
+function editBetween(from: CellWithSource, to: CellWithSource): CellEdit {
+ const edit: MutableEdit = {};
+ if (to.code !== from.code) {
+ edit.code = to.code;
+ }
+ if (to.name !== from.name) {
+ edit.name = to.name;
+ }
+ const config = differingFields(from.config, to.config);
+ if (!isEmpty(config)) {
+ edit.config = config;
+ }
+ return edit;
+}
+
+/** The fields of `edit` still waiting after `sent` was accepted. */
+function remainingEdit(edit: CellEdit, sent: CellEdit): CellEdit {
+ const remaining: MutableEdit = {};
+ if (edit.code !== undefined && edit.code !== sent.code) {
+ remaining.code = edit.code;
+ }
+ if (edit.name !== undefined && edit.name !== sent.name) {
+ remaining.name = edit.name;
+ }
+ if (edit.config !== undefined) {
+ const config = differingFields(sent.config ?? {}, edit.config);
+ if (!isEmpty(config)) {
+ remaining.config = config;
+ }
+ }
+ return remaining;
+}
+
+// Transitions ---------------------------------------------------------------
+//
+// Transitions are total. One with no effect returns its input, so a store
+// can skip the write and its notifications.
+
+function withCell(
+ draft: Draft,
+ id: Protocol.CellId,
+ cell: CellDraft | undefined,
+): Draft {
+ const cells = new Map(draft.cells);
+ if (cell === undefined) {
+ cells.delete(id);
+ } else {
+ cells.set(id, cell);
+ }
+ return { ...draft, cells };
+}
+
+/** Place a cell, falling back to the end if its anchor has disappeared. */
+function insertAt(
+ order: readonly Protocol.CellId[],
+ id: Protocol.CellId,
+ placement: Placement,
+): Protocol.CellId[] {
+ const without = order.filter((other) => other !== id);
+ let index = without.length;
+ if (placement.after !== undefined) {
+ const anchor = without.indexOf(placement.after);
+ if (anchor !== -1) {
+ index = anchor + 1;
+ }
+ } else if (placement.before !== undefined) {
+ const anchor = without.indexOf(placement.before);
+ if (anchor !== -1) {
+ index = anchor;
+ }
+ }
+ return [...without.slice(0, index), id, ...without.slice(index)];
+}
+
+/**
+ * Edit a cell's fields.
+ *
+ * An edit to a cell the host has removed is dropped: there is no state to
+ * apply it to. So is an edit to a cell this draft deletes.
+ */
+export function editCell(
+ confirmed: Document,
+ draft: Draft,
+ id: Protocol.CellId,
+ edit: CellEdit,
+): Draft {
+ const current = draft.cells.get(id);
+ if (current?.kind === "delete") {
+ return draft;
+ }
+ if (current?.kind === "create") {
+ const cell = applyEdit(current.cell, edit);
+ return sameCell(cell, current.cell)
+ ? draft
+ : withCell(draft, id, { ...current, cell });
+ }
+ const base = confirmed.cells.get(id);
+ if (base === undefined) {
+ return draft;
+ }
+ const previous = current?.edit ?? {};
+ const next = mergeEdit(previous, edit);
+ return sameCell(applyEdit(base, previous), applyEdit(base, next))
+ ? draft
+ : withCell(draft, id, { kind: "edit", edit: next });
+}
+
+/**
+ * Create a cell with the id the client chose.
+ *
+ * Omitted fields take the protocol's defaults. A draft order, if any, gains
+ * the cell at its placement so that it stays complete.
+ */
+export function createCell(
+ draft: Draft,
+ input: Protocol.CellInput,
+ placement: Placement = {},
+): Draft {
+ const parsed = Protocol.CellInput.parse(input);
+ const cell: CellWithSource = {
+ id: parsed.id,
+ code: parsed.code,
+ name: parsed.name,
+ config: parsed.config ?? Protocol.CellConfigInput.parse({}),
+ };
+ const next = withCell(draft, cell.id, { kind: "create", cell, placement });
+ return draft.order === null
+ ? next
+ : { ...next, order: insertAt(draft.order, cell.id, placement) };
+}
+
+/** Forget an unsent creation; otherwise retain the deletion until confirmed. */
+export function deleteCell(
+ draft: Draft,
+ id: Protocol.CellId,
+ sent: Draft = EMPTY_DRAFT,
+): Draft {
+ const current = draft.cells.get(id);
+ if (current?.kind === "delete") {
+ return draft;
+ }
+ const next = withCell(
+ draft,
+ id,
+ current?.kind === "create" && sent.cells.get(id)?.kind !== "create"
+ ? undefined
+ : { kind: "delete" },
+ );
+ return draft.order === null
+ ? next
+ : { ...next, order: draft.order.filter((other) => other !== id) };
+}
+
+/** Replace the order. Lists each cell of the document once, as `set_order` does. */
+export function setOrder(
+ draft: Draft,
+ order: readonly Protocol.CellId[],
+): Draft {
+ return draft.order !== null && sameOrder(draft.order, order)
+ ? draft
+ : { ...draft, order: [...order] };
+}
+
+/** Drop satisfied deletions, retaining edits to missing cells for recovery. */
+export function prune(
+ confirmed: Document,
+ draft: Draft,
+ sent: Draft = EMPTY_DRAFT,
+): Draft {
+ let cells: Map<Protocol.CellId, CellDraft> | undefined;
+ for (const [id, cell] of draft.cells) {
+ if (
+ cell.kind === "delete" &&
+ !confirmed.cells.has(id) &&
+ sent.cells.get(id)?.kind !== "create"
+ ) {
+ cells ??= new Map(draft.cells);
+ cells.delete(id);
+ }
+ }
+ return cells === undefined ? draft : { ...draft, cells };
+}
+
+/**
+ * Release a draft after the accepted revision is present in the source.
+ *
+ * `sent` is the draft the accepted request was derived from. A field is
+ * released when its value is still the one sent; a created cell becomes an
+ * edit of whatever changed after it was sent. The model enforces the revision
+ * precondition; this pure transition assumes it has already been checked.
+ */
+export function acknowledge(draft: Draft, sent: Draft): Draft {
+ let next = draft;
+ for (const [id, accepted] of sent.cells) {
+ const current = next.cells.get(id);
+ if (current?.kind === "delete" && accepted.kind === "delete") {
+ next = withCell(next, id, undefined);
+ } else if (current?.kind === "create" && accepted.kind === "create") {
+ next = withEdit(next, id, editBetween(accepted.cell, current.cell));
+ } else if (current?.kind === "edit" && accepted.kind === "edit") {
+ next = withEdit(next, id, remainingEdit(current.edit, accepted.edit));
+ }
+ }
+ if (
+ next.order !== null &&
+ sent.order !== null &&
+ sameOrder(next.order, sent.order)
+ ) {
+ next = { ...next, order: null };
+ }
+ return next;
+}
+
+function withEdit(draft: Draft, id: Protocol.CellId, edit: CellEdit): Draft {
+ return withCell(
+ draft,
+ id,
+ isEmpty(edit) ? undefined : { kind: "edit", edit },
+ );
+}
+
+// Projections ---------------------------------------------------------------
+
+/** A create or edit as the edit it makes to an existing cell. */
+function editOf(local: Exclude<CellDraft, { kind: "delete" }>): CellEdit {
+ return local.kind === "edit" ? local.edit : local.cell;
+}
+
+/**
+ * The confirmed document with a draft applied.
+ *
+ * A cell without a draft is the confirmed record itself, so its identity is
+ * stable until the host changes it. Cells the host added since a draft order
+ * was set go at the end; cells it removed leave the order.
+ */
+export function viewDocument(
+ confirmed: Document,
+ draft: Draft,
+): EditableDocument {
+ const cells = new Map<Protocol.CellId, EditableCell>();
+ for (const [id, cell] of confirmed.cells) {
+ const local = draft.cells.get(id);
+ if (local?.kind === "delete") {
+ continue;
+ }
+ cells.set(id, local === undefined ? cell : applyEdit(cell, editOf(local)));
+ }
+ let order: readonly Protocol.CellId[] =
+ draft.order ?? confirmed.revision.order;
+ for (const [id, local] of draft.cells) {
+ if (local.kind === "create" && !confirmed.cells.has(id)) {
+ cells.set(id, local.cell);
+ if (draft.order === null) {
+ order = insertAt(order, id, local.placement);
+ }
+ }
+ }
+ const placed = new Set(order);
+ const unplaced = [...cells.keys()].filter((id) => !placed.has(id));
+ if (unplaced.length > 0 || order.some((id) => !cells.has(id))) {
+ order = [...order.filter((id) => cells.has(id)), ...unplaced];
+ }
+ return {
+ order,
+ cells,
+ };
+}
+
+/**
+ * The edit request that would make the host match the view.
+ *
+ * Preconditions are the confirmed etags. A put with no effect is left out.
+ * Cells come before the order, so one request can create a cell and then
+ * place it. Returns null if a put lacks source or its edited cell was removed,
+ * keeping the draft atomic and retaining local intent for recovery.
+ */
+export function toChanges(
+ confirmed: Document,
+ draft: Draft,
+): Protocol.Change[] | null {
+ const changes: Protocol.Change[] = [];
+ let stagedOrder = confirmed.revision.order;
+ const stagedIds = new Set(stagedOrder);
+ for (const [id, local] of draft.cells) {
+ const base = confirmed.cells.get(id);
+ if (local.kind === "delete") {
+ if (base !== undefined) {
+ changes.push({ kind: "delete_cell", id, base_etag: base.etag });
+ stagedOrder = stagedOrder.filter((other) => other !== id);
+ stagedIds.delete(id);
+ }
+ } else if (local.kind === "create") {
+ const anchor = local.placement.after ?? local.placement.before;
+ const placement =
+ anchor === undefined || stagedIds.has(anchor) ? local.placement : {};
+ changes.push({
+ kind: "put_cell",
+ base_etag: null,
+ cell: local.cell,
+ ...placement,
+ });
+ if (base === undefined) {
+ stagedOrder = insertAt(stagedOrder, id, placement);
+ stagedIds.add(id);
+ }
+ } else if (base !== undefined) {
+ const cell = applyEdit(base, local.edit);
+ if (!sameCell(base, cell)) {
+ const { code } = cell;
+ if (code === null) {
+ return null;
+ }
+ changes.push({
+ kind: "put_cell",
+ base_etag: base.etag,
+ cell: { ...cell, code },
+ });
+ }
+ } else {
+ return null;
+ }
+ }
+ const { order } = viewDocument(confirmed, draft);
+ if (
+ (draft.order !== null && !sameOrder(order, confirmed.revision.order)) ||
+ !sameOrder(order, stagedOrder)
+ ) {
+ changes.push({
+ kind: "set_order",
+ base_etag: confirmed.revision.order_etag,
+ order: [...order],
+ });
+ }
+ return changes;
+}
diff --git a/frontend/src/core/document/model.ts b/frontend/src/core/document/model.ts
new file mode 100644
index 0000000000..204a6357dd
--- /dev/null
+++ b/frontend/src/core/document/model.ts
@@ -0,0 +1,395 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { dequal } from "dequal";
+import {
+ atom,
+ type Atom,
+ type createStore,
+ type WritableAtom,
+} from "jotai/vanilla";
+import { selectAtom } from "jotai/vanilla/utils";
+import type { Document } from "../host/resources/document";
+import * as Protocol from "@marimo-team/client/protocol";
+import {
+ acknowledge,
+ type CellEdit,
+ createCell,
+ deleteCell,
+ type Draft,
+ type EditableCell,
+ type EditableDocument,
+ editCell,
+ EMPTY_DRAFT,
+ isEmptyDraft,
+ type Placement,
+ prune,
+ sameCell,
+ setOrder,
+ toChanges,
+ viewDocument,
+} from "./draft";
+
+/** Operations on a working draft, valid only during the edit callback. */
+export interface DocumentEditor {
+ setCode(id: Protocol.CellId, code: string): void;
+ setName(id: Protocol.CellId, name: string): void;
+ updateConfig(id: Protocol.CellId, patch: Partial<Protocol.CellConfig>): void;
+ createCell(cell: Protocol.CellInput, placement?: Placement): void;
+ deleteCell(id: Protocol.CellId): void;
+ /** A permutation of the cells present at this point in the transaction. */
+ setOrder(order: readonly Protocol.CellId[]): void;
+}
+
+/** Synchronous; a thrown error discards the entire transaction. */
+export type DocumentEdit = (editor: DocumentEditor) => void;
+
+/** A captured edit request. Return this same object when reporting its result. */
+export interface DocumentSubmission {
+ readonly notebookId: Protocol.NotebookId;
+ readonly changes: readonly Protocol.Change[];
+}
+
+type ResponseRevision = Pick<Protocol.Document, "notebook_id" | "version">;
+
+interface PendingSubmission {
+ readonly submission: DocumentSubmission;
+ readonly draft: Draft;
+ readonly responseRevision: ResponseRevision | null;
+}
+
+interface ModelState {
+ readonly confirmed: Document | null;
+ readonly drafts: ReadonlyMap<Protocol.NotebookId, Draft>;
+ readonly pending: PendingSubmission | null;
+}
+
+/**
+ * Local edits over confirmed host state, with one submission in flight.
+ *
+ * A reset retains the submission so its receipt can reconcile a new snapshot.
+ * Switching notebook identity invalidates it, retaining each notebook's draft.
+ */
+export interface DocumentModel {
+ /** Hold onto the selector; its value is stable until the cell changes. */
+ cellAtom(id: Protocol.CellId): Atom<EditableCell | undefined>;
+ readonly orderAtom: Atom<readonly Protocol.CellId[] | null>;
+ readonly appConfigAtom: Atom<Readonly<
+ Protocol.Document["app_config"]
+ > | null>;
+ /** Null when the document or source needed by a put is unavailable. */
+ readonly changesAtom: Atom<readonly Protocol.Change[] | null>;
+ /** Remains pending until both the response and its streamed revision arrive. */
+ readonly pendingAtom: Atom<DocumentSubmission | null>;
+ readonly editAtom: WritableAtom<null, [edit: DocumentEdit], void>;
+ /** Capture a request, or null when unavailable, unchanged, or already sending. */
+ readonly submitAtom: WritableAtom<null, [], DocumentSubmission | null>;
+ /**
+ * Report the response revision, or null for a rejected request.
+ *
+ * Success waits for a complete streamed document at that version or later.
+ * Duplicate replies and replies for another notebook are ignored. Retry an
+ * uncertain request with the same body and idempotency key; do not reject it
+ * or capture a new request until its outcome is known.
+ */
+ readonly settleAtom: WritableAtom<
+ null,
+ [submission: DocumentSubmission, responseRevision: ResponseRevision | null],
+ void
+ >;
+ /** Stop observing the source and invalidate pending work. Safe to repeat. */
+ dispose(): void;
+}
+
+function draftOf(state: ModelState): Draft {
+ return state.confirmed === null
+ ? EMPTY_DRAFT
+ : (state.drafts.get(state.confirmed.revision.notebook_id) ?? EMPTY_DRAFT);
+}
+
+function withDraft(state: ModelState, draft: Draft): ModelState {
+ if (state.confirmed === null || draft === draftOf(state)) {
+ return state;
+ }
+ const drafts = new Map(state.drafts);
+ const notebookId = state.confirmed.revision.notebook_id;
+ if (isEmptyDraft(draft)) {
+ drafts.delete(notebookId);
+ } else {
+ drafts.set(notebookId, draft);
+ }
+ return { ...state, drafts };
+}
+
+/** Publish the confirmed document and any released fields together. */
+function reconcile(state: ModelState): ModelState {
+ const { confirmed, pending } = state;
+ if (confirmed === null) {
+ return state;
+ }
+ let draft = draftOf(state);
+ if (
+ pending !== null &&
+ pending.responseRevision !== null &&
+ confirmed.revision.version >= pending.responseRevision.version
+ ) {
+ draft = acknowledge(draft, pending.draft);
+ state = { ...state, pending: null };
+ }
+ return withDraft(state, prune(confirmed, draft, state.pending?.draft));
+}
+
+/** Create once per source and store; the owner must dispose the model. */
+export function createDocumentModel(
+ store: ReturnType<typeof createStore>,
+ source: Atom<Document | null>,
+): DocumentModel {
+ const stateAtom = atom<ModelState>({
+ confirmed: store.get(source),
+ drafts: new Map(),
+ pending: null,
+ });
+ let disposed = false;
+ const documentAtom = atom((get): EditableDocument | null => {
+ const state = get(stateAtom);
+ return state.confirmed === null
+ ? null
+ : viewDocument(state.confirmed, draftOf(state));
+ });
+ const cellAtom = (id: Protocol.CellId) =>
+ selectAtom(
+ documentAtom,
+ (document) => document?.cells.get(id),
+ (a, b) =>
+ a === b || (a !== undefined && b !== undefined && sameCell(a, b)),
+ );
+ const orderAtom = selectAtom(
+ documentAtom,
+ (document) => document?.order ?? null,
+ dequal,
+ );
+ const appConfigAtom = selectAtom(
+ stateAtom,
+ (state) => state.confirmed?.revision.app_config ?? null,
+ dequal,
+ );
+ const changesAtom = atom((get): readonly Protocol.Change[] | null => {
+ const state = get(stateAtom);
+ return state.confirmed === null
+ ? null
+ : toChanges(state.confirmed, draftOf(state));
+ });
+ const pendingAtom = atom((get) => get(stateAtom).pending?.submission ?? null);
+
+ const unsubscribe = store.sub(source, () => {
+ const confirmed = store.get(source);
+ store.set(stateAtom, (state) =>
+ reconcile({
+ ...state,
+ confirmed,
+ pending:
+ confirmed !== null &&
+ state.pending !== null &&
+ confirmed.revision.notebook_id !== state.pending.submission.notebookId
+ ? null
+ : state.pending,
+ }),
+ );
+ });
+
+ let editing = false;
+ const editAtom = atom(null, (get, set, edit: DocumentEdit) => {
+ if (editing) {
+ throw new Error("Document transactions cannot be nested");
+ }
+ const state = get(stateAtom);
+ if (disposed || state.confirmed === null) {
+ return;
+ }
+ editing = true;
+ try {
+ const draft = editDocument(
+ state.confirmed,
+ draftOf(state),
+ edit,
+ state.pending?.draft,
+ );
+ if (
+ disposed ||
+ get(stateAtom) !== state ||
+ get(source) !== state.confirmed
+ ) {
+ throw new Error("The document changed during the transaction");
+ }
+ set(stateAtom, withDraft(state, draft));
+ } finally {
+ editing = false;
+ }
+ });
+
+ const submitAtom = atom(null, (get, set): DocumentSubmission | null => {
+ const state = get(stateAtom);
+ if (disposed || state.confirmed === null || state.pending !== null) {
+ return null;
+ }
+ const draft = draftOf(state);
+ const changes = toChanges(state.confirmed, draft);
+ if (changes === null) {
+ return null;
+ }
+ if (changes.length === 0) {
+ set(stateAtom, withDraft(state, EMPTY_DRAFT));
+ return null;
+ }
+ const submission = {
+ notebookId: state.confirmed.revision.notebook_id,
+ changes,
+ };
+ set(stateAtom, {
+ ...state,
+ pending: { submission, draft, responseRevision: null },
+ });
+ return submission;
+ });
+
+ const settleAtom = atom(
+ null,
+ (
+ get,
+ set,
+ submission: DocumentSubmission,
+ responseRevision: ResponseRevision | null,
+ ) => {
+ const state = get(stateAtom);
+ if (
+ disposed ||
+ state.pending?.submission !== submission ||
+ state.pending.responseRevision !== null
+ ) {
+ return;
+ }
+ if (
+ responseRevision !== null &&
+ responseRevision.notebook_id !== submission.notebookId
+ ) {
+ throw new Error("Edit response belongs to another notebook");
+ }
+ set(
+ stateAtom,
+ reconcile({
+ ...state,
+ pending:
+ responseRevision === null
+ ? null
+ : { ...state.pending, responseRevision },
+ }),
+ );
+ },
+ );
+
+ return {
+ cellAtom,
+ orderAtom,
+ appConfigAtom,
+ changesAtom,
+ pendingAtom,
+ editAtom,
+ submitAtom,
+ settleAtom,
+ dispose() {
+ if (!disposed) {
+ disposed = true;
+ unsubscribe();
+ store.set(stateAtom, {
+ confirmed: null,
+ drafts: new Map(),
+ pending: null,
+ });
+ }
+ },
+ };
+}
+
+function editDocument(
+ confirmed: Document,
+ draft: Draft,
+ edit: DocumentEdit,
+ sent: Draft = EMPTY_DRAFT,
+): Draft {
+ let next = draft;
+ let active = true;
+
+ function assertActive() {
+ if (!active) {
+ throw new Error("The document transaction has ended");
+ }
+ }
+
+ function hasCell(id: Protocol.CellId): boolean {
+ const local = next.cells.get(id);
+ return (
+ local?.kind === "create" ||
+ (local?.kind !== "delete" && confirmed.cells.has(id))
+ );
+ }
+
+ function requireCell(id: Protocol.CellId) {
+ assertActive();
+ if (!hasCell(id)) {
+ throw new Error(`Cell ${id} does not exist`);
+ }
+ }
+
+ function updateCell(id: Protocol.CellId, patch: CellEdit) {
+ requireCell(id);
+ next = editCell(confirmed, next, id, patch);
+ }
+
+ const editor: DocumentEditor = {
+ setCode: (id, code) => updateCell(id, { code }),
+ setName: (id, name) => updateCell(id, { name }),
+ updateConfig: (id, patch) =>
+ updateCell(id, { config: Protocol.CellConfig.partial().parse(patch) }),
+ createCell: (cell, placement = {}) => {
+ assertActive();
+ if (confirmed.cells.has(cell.id) || hasCell(cell.id)) {
+ throw new Error(`Cell ${cell.id} already exists`);
+ }
+ if (placement.after !== undefined && placement.before !== undefined) {
+ throw new Error("Specify either before or after for cell placement");
+ }
+ const anchor = placement.after ?? placement.before;
+ if (anchor !== undefined) {
+ requireCell(anchor);
+ }
+ next = createCell(next, cell, { ...placement });
+ },
+ deleteCell: (id) => {
+ requireCell(id);
+ next = deleteCell(next, id, sent);
+ },
+ setOrder: (order) => {
+ assertActive();
+ const { cells } = viewDocument(confirmed, next);
+ if (
+ order.length !== cells.size ||
+ new Set(order).size !== cells.size ||
+ order.some((id) => !cells.has(id))
+ ) {
+ throw new Error("Cell order must contain every cell exactly once");
+ }
+ next = setOrder(next, order);
+ },
+ };
+
+ try {
+ const result: unknown = edit(editor);
+ if (result instanceof Promise) {
+ // Observe a rejected async callback without publishing its partial draft.
+ result.catch(() => undefined);
+ throw new Error("Document edit callbacks must be synchronous");
+ }
+ return next;
+ } finally {
+ active = false;
+ }
+}