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.

Own document drafts and synchronization in one model (#11445)

Trevor Manz7d394c4d8acd
diff --git a/frontend/src/core/document/__tests__/model.test.ts b/frontend/src/core/document/__tests__/model.test.ts
index 5eeaec276c..b49d143031 100644
--- a/frontend/src/core/document/__tests__/model.test.ts
+++ b/frontend/src/core/document/__tests__/model.test.ts
@@ -1,434 +1,483 @@
/* Copyright 2026 Marimo. All rights reserved. */
+import type { Result } from "@marimo-team/client";
+import type * as Protocol from "@marimo-team/client/protocol";
import { atom, createStore } from "jotai/vanilla";
-import { describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { Deferred } from "@/utils/Deferred";
import type { Document } from "../../host/resources/document";
-import {
- createDocumentModel,
- type DocumentEdit,
- type DocumentEditor,
-} from "../model";
+import { createDocumentModel, type DocumentHost } from "../model";
import { cell, document, withCells } from "./fixtures";
-function setup(initial: Document | null = document()) {
+function response(confirmed: Document): Result<Protocol.EditResponseOutput> {
+ return {
+ ok: true,
+ status: 200,
+ data: { document: confirmed.revision, cells: {} },
+ };
+}
+
+// Observe rejections before advancing timers to avoid unhandled promises.
+async function expectFailure(promise: Promise<unknown>, message: string) {
+ await expect(promise).rejects.toThrow(message);
+}
+
+async function expectAbort(promise: Promise<unknown>, reason: Error) {
+ await expect(promise).rejects.toBe(reason);
+}
+
+/** An edit the host received, with its notebook and options. */
+interface SentEdit {
+ notebookId: Protocol.NotebookId;
+ changes: readonly Protocol.Change[];
+ idempotencyKey: string;
+ signal: AbortSignal;
+}
+
+function setup() {
const store = createStore();
- const source = atom(initial);
- const model = createDocumentModel(store, source);
+ const source = atom<Document | null>(document());
+ const unmounted = vi.fn();
+ source.onMount = () => unmounted;
+ const replies: Deferred<Result<Protocol.EditResponseOutput>>[] = [];
+ const sent = vi.fn((_edit: SentEdit) => {
+ const reply = new Deferred<Result<Protocol.EditResponseOutput>>();
+ replies.push(reply);
+ return reply.promise;
+ });
+ const host: DocumentHost = {
+ documentAtom: source,
+ edit: (notebookId, changes, options) =>
+ sent({ notebookId, changes, ...options }),
+ };
+ const controller = new AbortController();
+ lifetimes.push(controller);
+ const model = createDocumentModel({
+ store,
+ notebook: host,
+ signal: controller.signal,
+ });
return {
store,
source,
- ...model,
- edit: (callback: DocumentEdit) => store.set(model.editAtom, callback),
+ model,
+ sent,
+ replies,
+ controller,
+ unmounted,
+ edit: (code: string) =>
+ store.set(model.editAtom, (tx) => tx.setCode("c1", code)),
+ state: () => store.get(model.syncStateAtom),
+ value: () => store.get(model.cellAtom("c1")),
};
}
-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();
+const lifetimes: AbortController[] = [];
+beforeEach(() => vi.useFakeTimers());
+afterEach(() => {
+ lifetimes.splice(0).forEach((controller) => controller.abort());
+ vi.useRealTimers();
+});
- store.set(
- source,
- withCells(hidden, {
- c1: cell("c1", "updated source", { etag: "latest" }),
+describe("document synchronization", () => {
+ it("rejects an aborted lifetime before subscribing or sending", () => {
+ const store = createStore();
+ const source = atom<Document | null>(document());
+ const mounted = vi.fn();
+ source.onMount = mounted;
+ const controller = new AbortController();
+ const reason = new Error("Session ended");
+ controller.abort(reason);
+ const edit = vi.fn<DocumentHost["edit"]>();
+ expect(() =>
+ createDocumentModel({
+ store,
+ notebook: { documentAtom: source, edit },
+ signal: controller.signal,
}),
- );
- expect(store.get(changesAtom)).toEqual([
- {
- kind: "put_cell",
- base_etag: "latest",
- cell: {
- id: "c1",
- code: "updated source",
- name: "local name",
- config: cell("c1", "").config,
- },
- },
- ]);
+ ).toThrow(reason);
+ expect(mounted).not.toHaveBeenCalled();
+ expect(edit).not.toHaveBeenCalled();
+ expect(vi.getTimerCount()).toBe(0);
});
- 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("releases unsent reversals and flushes an unchanged document without a request", async () => {
+ const { store, source, sent, edit, model, state, value } = setup();
+ edit("temporary");
+ edit("x = 1");
+ expect(state()).toEqual({ status: "idle" });
+ const remote = withCells(document(), { c1: cell("c1", "remote") });
+ store.set(source, remote);
+ expect(value()?.code).toBe("remote");
+ await expect(model.flush()).resolves.toEqual(remote.revision);
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(sent).not.toHaveBeenCalled();
});
- 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("flushes edits made after an earlier drain finishes but before its promise settles", async () => {
+ const { store, source, sent, replies, edit, model } = setup();
+ const first = model.flush();
+ await Promise.resolve();
+ edit("new code");
+ const second = model.flush();
+ const settled = vi.fn();
+ void second.then(settled, settled);
- 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"] },
+ await vi.advanceTimersByTimeAsync(0);
+ expect(sent).toHaveBeenCalledOnce();
+ expect(settled).not.toHaveBeenCalled();
+ expect(sent.mock.calls[0][0].changes).toMatchObject([
+ { cell: { id: "c1", code: "new code" } },
]);
- });
- 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");
+ const accepted = withCells(document(), {
+ c1: cell("c1", "new code", { etag: "accepted", version: 2 }),
+ });
+ replies[0].resolve(response(accepted));
+ store.set(source, accepted);
+ await expect(second).resolves.toEqual(accepted.revision);
+ await expect(first).resolves.toEqual(document().revision);
});
- 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");
+ it("manually retries an uncertain request with its original identity", async () => {
+ const { store, source, sent, replies, edit, model } = setup();
+ edit("local");
+ const flushed = model.flush();
+ expect(model.flush()).toBe(flushed);
+ const rejected = expectFailure(flushed, "offline");
+ await vi.advanceTimersByTimeAsync(0);
+ replies[0].reject(new Error("offline"));
+ await vi.advanceTimersByTimeAsync(500);
+ replies[1].reject(new Error("offline"));
+ await vi.advanceTimersByTimeAsync(1000);
+ replies[2].reject(new Error("offline"));
+ await rejected;
+ const retried = model.retry();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(sent.mock.calls[3][0]).toMatchObject({
+ idempotencyKey: sent.mock.calls[0][0].idempotencyKey,
+ changes: sent.mock.calls[0][0].changes,
});
- 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,
- },
- },
- ]);
+ const accepted = withCells(document(), { c1: cell("c1", "local") });
+ replies[3].resolve(response(accepted));
+ store.set(source, accepted);
+ await expect(retried).resolves.toEqual(accepted.revision);
});
- 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("fails without repeating a request when the response names another notebook", async () => {
+ const { sent, replies, edit, model, state } = setup();
+ edit("local");
+ const rejected = expectFailure(model.flush(), "another notebook");
+ await vi.advanceTimersByTimeAsync(0);
+ replies[0].resolve(response(document("n2")));
+ await rejected;
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(sent).toHaveBeenCalledOnce();
+ expect(state()).toMatchObject({ status: "error" });
});
- 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();
+ it("debounces typing and waits for streamed confirmation before sending newer edits", async () => {
+ const { store, source, sent, replies, edit, model, state, value } = setup();
+ edit("first");
+ await vi.advanceTimersByTimeAsync(300);
+ edit("sent");
+ await vi.advanceTimersByTimeAsync(399);
+ expect(sent).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1);
+ expect(sent).toHaveBeenCalledOnce();
+ expect(sent.mock.calls[0][0].changes[0]).toMatchObject({
+ cell: { code: "sent" },
});
- 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();
+ edit("newer");
+ const accepted = withCells(document(), {
+ c1: cell("c1", "sent", { etag: "accepted" }),
});
- 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 });
+ replies[0].resolve(response(accepted));
+ await vi.advanceTimersByTimeAsync(0);
+ expect(state()).toEqual({ status: "confirming" });
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(sent).toHaveBeenCalledOnce();
+ store.set(source, accepted);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(sent).toHaveBeenCalledTimes(2);
+ expect(sent.mock.calls[1][0].changes[0]).toMatchObject({
+ base_etag: "accepted",
+ cell: { code: "newer" },
});
- 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();
+ const latest = withCells(accepted, { c1: cell("c1", "newer") });
+ const flushed = model.flush();
+ replies[1].resolve(response(latest));
+ store.set(source, latest);
+ await expect(flushed).resolves.toEqual(latest.revision);
+ expect(state()).toEqual({ status: "idle" });
+ expect(value()?.code).toBe("newer");
});
- 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" });
+ it.each(["response", "snapshot"] as const)(
+ "confirms a reset when %s arrives first without opening a stream",
+ async (first) => {
+ const { store, source, sent, replies, edit, model } = setup();
+ edit("sent");
+ const flushed = model.flush();
+ await vi.advanceTimersByTimeAsync(0);
+ store.set(source, null);
+ const accepted = withCells(document(), { c1: cell("c1", "sent") });
+ const later = withCells(accepted, { c2: cell("c2", "remote") });
+ if (first === "response") {
+ replies[0].resolve(response(accepted));
+ } else {
+ store.set(source, later);
+ }
+ await vi.advanceTimersByTimeAsync(0);
+ expect(store.get(model.syncStateAtom)).toEqual({
+ status: first === "response" ? "confirming" : "sending",
+ });
+ if (first === "response") {
+ store.set(source, later);
+ } else {
+ replies[0].resolve(response(accepted));
+ }
+ await expect(flushed).resolves.toEqual(later.revision);
+ expect(sent).toHaveBeenCalledOnce();
+ expect(store.get(model.syncStateAtom)).toEqual({ status: "idle" });
+ },
+ );
+
+ it("retries a lost response with the captured body and key, preserving subsequent typing", async () => {
+ const { store, source, sent, replies, edit, model, value } = setup();
+ edit("sent");
+ const flushed = model.flush();
+ await vi.advanceTimersByTimeAsync(0);
+ const accepted = withCells(document(), {
+ c1: cell("c1", "sent", { etag: "accepted" }),
});
- 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),
- ];
+ store.set(source, accepted);
+ edit("newer");
+ replies[0].reject(new Error("response lost"));
+ await vi.advanceTimersByTimeAsync(500);
+ expect(sent).toHaveBeenCalledTimes(2);
+ const original = sent.mock.calls[0][0];
+ const retry = sent.mock.calls[1][0];
+ expect(retry.idempotencyKey).toBe(original.idempotencyKey);
+ expect(retry.changes).toBe(original.changes);
+ replies[1].resolve(response(accepted));
+ await vi.advanceTimersByTimeAsync(0);
+ expect(sent).toHaveBeenCalledTimes(3);
+ expect(sent.mock.calls[2][0].idempotencyKey).not.toBe(
+ original.idempotencyKey,
+ );
+ const latest = withCells(accepted, { c1: cell("c1", "newer") });
+ store.set(source, latest);
+ replies[2].resolve(response(latest));
+ await expect(flushed).resolves.toEqual(latest.revision);
+ expect(value()?.code).toBe("newer");
+ });
- edit((tx) => tx.setCode("c2", "other local"));
- const remote = withCells(initial, {
- c1: cell("c1", "remote", { version: 2, etag: "new-etag" }),
+ it("exposes conflicts and only retries explicitly against a fresh confirmed revision", async () => {
+ const { store, source, sent, replies, edit, model, state, value } = setup();
+ edit("local");
+ const flushed = model.flush();
+ const rejected = expectFailure(flushed, "conflict");
+ await vi.advanceTimersByTimeAsync(0);
+ const remote = withCells(document(), {
+ c1: cell("c1", "remote", { etag: "remote" }),
});
- store.set(source, {
- ...remote,
- revision: {
- ...remote.revision,
- order: [...initial.revision.order],
- app_config: { ...initial.revision.app_config },
+ const problem: Protocol.Problem = {
+ type: "tag:marimo.io,2026:host/conflict",
+ title: "conflict",
+ status: 409,
+ edit: {
+ change: 0,
+ cell: remote.cells.get("c1")!,
+ document: remote.revision,
},
+ };
+ replies[0].resolve({ ok: false, status: 409, problem });
+ await rejected;
+ expect(state()).toMatchObject({
+ status: "error",
+ problem,
+ retryable: true,
});
- 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,
+ await expect(model.retry()).rejects.toThrow("Wait for the host");
+ edit("updated local");
+ store.set(source, remote);
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(sent).toHaveBeenCalledOnce();
+ expect(value()?.code).toBe("updated local");
+ const retry = model.retry();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(sent.mock.calls[1][0].changes[0]).toMatchObject({
+ base_etag: "remote",
+ cell: { code: "updated local" },
});
- 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());
+ const accepted = withCells(remote, { c1: cell("c1", "updated local") });
+ replies[1].resolve(response(accepted));
+ store.set(source, accepted);
+ await expect(retry).resolves.toEqual(accepted.revision);
});
- 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");
+ it("retains a draft after remote deletion and never sends the other edits alone", async () => {
+ const { store, source, model, sent, replies, edit } = setup();
+ edit("keep this");
+ const flushed = model.flush();
+ const rejected = expectFailure(flushed, "removed");
+ await vi.advanceTimersByTimeAsync(0);
+ const removed = withCells(document(), { c1: null });
+ store.set(source, removed);
+ replies[0].resolve({
+ ok: false,
+ status: 409,
+ problem: {
+ type: "tag:marimo.io,2026:host/conflict",
+ title: "removed",
+ status: 409,
+ edit: { change: 0, cell: null, document: removed.revision },
},
- "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();
+ });
+ await rejected;
+ store.set(model.editAtom, (tx) => tx.setCode("c2", "other edit"));
+ await expect(model.retry()).rejects.toThrow("unavailable");
+ expect(sent).toHaveBeenCalledOnce();
+ store.set(source, withCells(removed, { c1: cell("c1", "restored") }));
+ expect(store.get(model.cellAtom("c1"))?.code).toBe("keep this");
});
- 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("bounds retries and never replays an uncertain write after receipt expiry", async () => {
+ const { sent, replies, edit, model, state } = setup();
+ edit("local");
+ const flushed = model.flush();
+ const rejected = expectFailure(flushed, "offline");
+ await vi.advanceTimersByTimeAsync(0);
+ replies[0].reject(new Error("offline"));
+ await vi.advanceTimersByTimeAsync(500);
+ replies[1].reject(new Error("offline"));
+ await vi.advanceTimersByTimeAsync(1000);
+ replies[2].reject(new Error("offline"));
+ await rejected;
+ expect(state()).toMatchObject({ status: "error", retryable: true });
+ await vi.advanceTimersByTimeAsync(60_000);
+ await expect(model.retry()).rejects.toThrow("retry window expired");
+ expect(sent).toHaveBeenCalledTimes(3);
+ expect(state()).toMatchObject({ status: "error", retryable: false });
});
- 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("times out a hung attempt, aborts it, and retries the same request", async () => {
+ const { store, source, sent, replies, edit, model } = setup();
+ edit("local");
+ const flushed = model.flush();
+ await vi.advanceTimersByTimeAsync(10_500);
+ expect(sent).toHaveBeenCalledTimes(2);
+ expect(sent.mock.calls[0][0].signal.aborted).toBe(true);
+ expect(sent.mock.calls[1][0].idempotencyKey).toBe(
+ sent.mock.calls[0][0].idempotencyKey,
+ );
+ const accepted = withCells(document(), { c1: cell("c1", "local") });
+ replies[1].resolve(response(accepted));
+ store.set(source, accepted);
+ await expect(flushed).resolves.toEqual(accepted.revision);
});
- 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("aborts before the debounce without sending any edits", async () => {
+ const { sent, edit, model, controller } = setup();
+ edit("local");
+ controller.abort();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(sent).not.toHaveBeenCalled();
+ expect(vi.getTimerCount()).toBe(0);
+ await expect(model.flush()).rejects.toThrow("aborted");
});
- 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([]);
+ it.each(["request", "confirmation", "retry"] as const)(
+ "aborts during %s without leaving work or subscriptions",
+ async (phase) => {
+ const {
+ store,
+ source,
+ sent,
+ replies,
+ edit,
+ model,
+ controller,
+ unmounted,
+ } = setup();
+ edit("local");
+ const flushed = model.flush();
+ const reason = new Error("Editing session ended");
+ const rejected = expectAbort(flushed, reason);
+ await vi.advanceTimersByTimeAsync(0);
+ if (phase === "confirmation") {
+ replies[0].resolve(
+ response(withCells(document(), { c1: cell("c1", "local") })),
+ );
+ }
+ if (phase === "retry") {
+ replies[0].reject(new Error("offline"));
+ }
+ await vi.advanceTimersByTimeAsync(0);
+ controller.abort(reason);
+ await rejected;
+ expect(unmounted).toHaveBeenCalledOnce();
+ expect(sent).toHaveBeenCalledOnce();
+ store.set(source, withCells(document(), { c1: cell("c1", "later") }));
+ edit("after disposal");
+ expect(vi.getTimerCount()).toBe(0);
+ await expect(model.flush()).rejects.toBe(reason);
+ await expect(model.retry()).rejects.toBe(reason);
+ },
+ );
+
+ it("ignores a late response and source update after its lifetime ends", async () => {
+ const {
+ store,
+ source,
+ model,
+ replies,
+ sent,
+ edit,
+ controller,
+ unmounted,
+ value,
+ } = setup();
+ edit("local");
+ const reason = new Error("Editing session ended");
+ const rejected = expectAbort(model.flush(), reason);
+ await vi.advanceTimersByTimeAsync(0);
+ controller.abort(reason);
+ await rejected;
+ const accepted = withCells(document(), { c1: cell("c1", "local") });
+ replies[0].resolve(response(accepted));
+ store.set(source, accepted);
+ const staleEdit = vi.fn();
+ store.set(model.editAtom, staleEdit);
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(unmounted).toHaveBeenCalledOnce();
+ expect(staleEdit).not.toHaveBeenCalled();
+ expect(value()).toBeUndefined();
+ expect(sent).toHaveBeenCalledOnce();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it("rejects a queued flush when aborted before submission", async () => {
+ const { model, edit, sent, controller } = setup();
+ edit("local");
+ const reason = new Error("Editing session ended");
+ const rejected = expectAbort(model.flush(), reason);
+ controller.abort(reason);
+ await rejected;
+ expect(sent).not.toHaveBeenCalled();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it("aborts an in-flight edit when notebook identity changes", async () => {
+ const { store, source, sent, edit, model, state } = setup();
+ edit("local");
+ const flushed = model.flush();
+ const rejected = expectFailure(flushed, "notebook changed");
+ await vi.advanceTimersByTimeAsync(0);
+ store.set(source, document("n2"));
+ await rejected;
+ expect(sent.mock.calls[0][0].signal.aborted).toBe(true);
+ expect(state()).toMatchObject({ status: "error", retryable: false });
});
});
diff --git a/frontend/src/core/document/__tests__/state.test.ts b/frontend/src/core/document/__tests__/state.test.ts
new file mode 100644
index 0000000000..152dc80056
--- /dev/null
+++ b/frontend/src/core/document/__tests__/state.test.ts
@@ -0,0 +1,446 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { atom, createStore } from "jotai/vanilla";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { Document } from "../../host/resources/document";
+import {
+ createDocumentState,
+ type DocumentEdit,
+ type DocumentEditor,
+} from "../state";
+import { cell, document, withCells } from "./fixtures";
+
+const lifetimes: AbortController[] = [];
+afterEach(() =>
+ lifetimes.splice(0).forEach((controller) => controller.abort()),
+);
+
+function setup(initial: Document | null = document()) {
+ const store = createStore();
+ const source = atom(initial);
+ const controller = new AbortController();
+ lifetimes.push(controller);
+ const model = createDocumentState({
+ store,
+ source,
+ signal: controller.signal,
+ });
+ return {
+ store,
+ source,
+ ...model,
+ abort: () => controller.abort(),
+ 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
index 65ccfdf0a6..dfd6a3aaec 100644
--- a/frontend/src/core/document/__tests__/submission.test.ts
+++ b/frontend/src/core/document/__tests__/submission.test.ts
@@ -1,19 +1,31 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { atom, createStore } from "jotai/vanilla";
-import { describe, expect, it, vi } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import type { Document } from "../../host/resources/document";
-import { createDocumentModel, type DocumentSubmission } from "../model";
+import { createDocumentState, type DocumentSubmission } from "../state";
import { cell, document, withCells } from "./fixtures";
+const lifetimes: AbortController[] = [];
+afterEach(() =>
+ lifetimes.splice(0).forEach((controller) => controller.abort()),
+);
+
function setup() {
const store = createStore();
const source = atom<Document | null>(document());
- const model = createDocumentModel(store, source);
+ const controller = new AbortController();
+ lifetimes.push(controller);
+ const model = createDocumentState({
+ store,
+ source,
+ signal: controller.signal,
+ });
return {
store,
source,
...model,
+ abort: () => controller.abort(),
submit() {
const submission = store.set(model.submitAtom);
if (submission === null) {
@@ -313,11 +325,11 @@ describe("document submissions", () => {
submitAtom,
submit,
settle,
- dispose,
+ abort,
} = setup();
store.set(editAtom, (tx) => tx.setCode("c1", "local"));
const sent = submit();
- dispose();
+ abort();
const onOrder = vi.fn();
store.sub(orderAtom, onOrder);
const confirmed = withCells(document(), { c1: cell("c1", "local") });
@@ -325,7 +337,7 @@ describe("document submissions", () => {
settle(sent, confirmed);
const edit = vi.fn();
store.set(editAtom, edit);
- dispose();
+ abort();
expect(edit).not.toHaveBeenCalled();
expect(onOrder).not.toHaveBeenCalled();
expect(store.get(orderAtom)).toBeNull();
diff --git a/frontend/src/core/document/index.ts b/frontend/src/core/document/index.ts
new file mode 100644
index 0000000000..4b779f498c
--- /dev/null
+++ b/frontend/src/core/document/index.ts
@@ -0,0 +1,10 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+export { createDocumentModel } from "./model";
+export type {
+ DocumentEdit,
+ DocumentEditor,
+ DocumentHost,
+ DocumentModel,
+ DocumentSyncState,
+} from "./model";
diff --git a/frontend/src/core/document/model.ts b/frontend/src/core/document/model.ts
index 204a6357dd..050ad79c36 100644
--- a/frontend/src/core/document/model.ts
+++ b/frontend/src/core/document/model.ts
@@ -1,395 +1,53 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import { dequal } from "dequal";
+import type * as Protocol from "@marimo-team/client/protocol";
+import type { Atom, createStore } from "jotai/vanilla";
+import { createDocumentState, type DocumentState } from "./state";
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,
+ createDocumentSync,
+ type DocumentHost,
+ type DocumentSyncState,
+} from "./sync";
+
+export type { DocumentEdit, DocumentEditor } from "./state";
+export type { DocumentHost, DocumentSyncState } from "./sync";
+
+/** The editable document and its synchronization with the host. */
+export interface DocumentModel extends Pick<
+ DocumentState,
+ "cellAtom" | "orderAtom" | "appConfigAtom" | "editAtom"
+> {
+ readonly syncStateAtom: Atom<DocumentSyncState>;
+ /** Drain local edits and return the confirmed revision. */
+ flush(): Promise<Protocol.Document>;
+ /** Retry a rejection against fresh state, or repeat an uncertain request exactly. */
+ retry(): Promise<Protocol.Document>;
+}
+
+/** Create once per editing session; abort to stop editing and synchronization together. */
+export function createDocumentModel({
+ store,
+ notebook,
+ signal,
+}: {
+ store: ReturnType<typeof createStore>;
+ notebook: DocumentHost;
+ signal: AbortSignal;
+}): DocumentModel {
+ signal.throwIfAborted();
+ const state = createDocumentState({
+ store,
+ source: notebook.documentAtom,
+ signal,
});
- 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 },
- }),
- );
- },
- );
-
+ const sync = createDocumentSync({ store, notebook, state, signal });
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,
- });
- }
- },
+ cellAtom: state.cellAtom,
+ orderAtom: state.orderAtom,
+ appConfigAtom: state.appConfigAtom,
+ editAtom: state.editAtom,
+ syncStateAtom: sync.stateAtom,
+ flush: sync.flush,
+ retry: sync.retry,
};
}
-
-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;
- }
-}
diff --git a/frontend/src/core/document/state.ts b/frontend/src/core/document/state.ts
new file mode 100644
index 0000000000..a621e8c5c6
--- /dev/null
+++ b/frontend/src/core/document/state.ts
@@ -0,0 +1,401 @@
+/* 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 DocumentState {
+ /** 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
+ >;
+}
+
+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));
+}
+
+/** Internal draft and submission state for one editing lifetime. */
+export function createDocumentState({
+ store,
+ source,
+ signal,
+}: {
+ store: ReturnType<typeof createStore>;
+ source: Atom<Document | null>;
+ signal: AbortSignal;
+}): DocumentState {
+ signal.throwIfAborted();
+ const stateAtom = atom<ModelState>({
+ confirmed: store.get(source),
+ drafts: new Map(),
+ pending: null,
+ });
+ 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 (signal.aborted || state.confirmed === null) {
+ return;
+ }
+ editing = true;
+ try {
+ const draft = editDocument(
+ state.confirmed,
+ draftOf(state),
+ edit,
+ state.pending?.draft,
+ );
+ if (
+ signal.aborted ||
+ 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 (signal.aborted || 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 (
+ signal.aborted ||
+ 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 },
+ }),
+ );
+ },
+ );
+
+ function stop() {
+ unsubscribe();
+ signal.removeEventListener("abort", stop);
+ store.set(stateAtom, {
+ confirmed: null,
+ drafts: new Map(),
+ pending: null,
+ });
+ }
+ signal.addEventListener("abort", stop, { once: true });
+ if (signal.aborted) {
+ stop();
+ }
+
+ return {
+ cellAtom,
+ orderAtom,
+ appConfigAtom,
+ changesAtom,
+ pendingAtom,
+ editAtom,
+ submitAtom,
+ settleAtom,
+ };
+}
+
+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;
+ }
+}
diff --git a/frontend/src/core/document/sync.ts b/frontend/src/core/document/sync.ts
new file mode 100644
index 0000000000..371af8e9d9
--- /dev/null
+++ b/frontend/src/core/document/sync.ts
@@ -0,0 +1,359 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { idempotencyKey, type Result } from "@marimo-team/client";
+import type * as Protocol from "@marimo-team/client/protocol";
+import { atom, type createStore } from "jotai/vanilla";
+import type { NotebookClient } from "../host/notebook-client";
+import type { DocumentState, DocumentSubmission } from "./state";
+
+/** The notebook state and operation needed by document editing. */
+export type DocumentHost = Pick<NotebookClient, "documentAtom" | "edit">;
+
+export type DocumentSyncState =
+ | {
+ readonly status:
+ | "idle"
+ | "pending"
+ | "sending"
+ | "confirming"
+ | "unavailable";
+ }
+ | {
+ readonly status: "error";
+ readonly error: Error;
+ readonly problem?: Protocol.Problem;
+ readonly retryable: boolean;
+ };
+
+interface Submission {
+ readonly edit: DocumentSubmission;
+ readonly idempotencyKey: string;
+ readonly startedAt: number;
+ readonly controller: AbortController;
+ response?: Protocol.Document;
+ problem?: Protocol.Problem;
+}
+
+// The marimo host retains receipts for five minutes. Stop well before that,
+// including after sleep, rather than replaying an uncertain write as a new one.
+const RETRY_WINDOW_MS = 60_000;
+const REQUEST_TIMEOUT_MS = 10_000;
+const MAX_ATTEMPTS = 3;
+const DEBOUNCE_MS = 400;
+
+function abortable<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
+ return new Promise((resolve, reject) => {
+ const abort = () => reject(signal.reason);
+ signal.addEventListener("abort", abort, { once: true });
+ promise
+ .then(resolve, reject)
+ .finally(() => signal.removeEventListener("abort", abort));
+ if (signal.aborted) {
+ abort();
+ }
+ });
+}
+
+function delay(ms: number, signal: AbortSignal): Promise<void> {
+ return new Promise((resolve, reject) => {
+ const abort = () => {
+ clearTimeout(timer);
+ reject(signal.reason);
+ };
+ const timer = setTimeout(() => {
+ signal.removeEventListener("abort", abort);
+ resolve();
+ }, ms);
+ signal.addEventListener("abort", abort, { once: true });
+ if (signal.aborted) {
+ abort();
+ }
+ });
+}
+
+/** Own submission scheduling; follow the existing source without opening a stream. */
+export function createDocumentSync({
+ store,
+ notebook,
+ state,
+ signal,
+}: {
+ store: ReturnType<typeof createStore>;
+ notebook: DocumentHost;
+ state: DocumentState;
+ signal: AbortSignal;
+}) {
+ signal.throwIfAborted();
+ const source = notebook.documentAtom;
+ const stateAtom = atom<DocumentSyncState>({ status: "idle" });
+ const observed = atom((get) => ({
+ document: get(source),
+ pending: get(state.pendingAtom),
+ changes: get(state.changesAtom),
+ }));
+ let active: Submission | null = null;
+ let running: Promise<Protocol.Document> | null = null;
+ let failure: Extract<DocumentSyncState, { status: "error" }> | null = null;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let refreshing = false;
+
+ function clearTimer() {
+ clearTimeout(timer);
+ timer = undefined;
+ }
+
+ function unavailable() {
+ return new Error(
+ "The document or source required by an edit is unavailable",
+ );
+ }
+
+ function refresh() {
+ if (signal.aborted || refreshing) {
+ return;
+ }
+ refreshing = true;
+ try {
+ const current = store.get(source);
+ if (
+ active &&
+ current &&
+ current.revision.notebook_id !== active.edit.notebookId
+ ) {
+ active.controller.abort(
+ new Error("The notebook changed during synchronization"),
+ );
+ }
+ if (running || failure) {
+ return;
+ }
+ clearTimer();
+ const changes = store.get(state.changesAtom);
+ if (changes === null) {
+ store.set(stateAtom, { status: "unavailable" });
+ } else if (changes.length === 0) {
+ // Release unsent reversals instead of keeping an invisible override.
+ store.set(state.submitAtom);
+ store.set(stateAtom, { status: "idle" });
+ } else {
+ store.set(stateAtom, { status: "pending" });
+ timer = setTimeout(() => {
+ void flush().catch(() => undefined);
+ }, DEBOUNCE_MS);
+ }
+ } finally {
+ refreshing = false;
+ }
+ }
+
+ async function send(request: Submission) {
+ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
+ signal.throwIfAborted();
+ request.controller.signal.throwIfAborted();
+ if (Date.now() - request.startedAt >= RETRY_WINDOW_MS) {
+ throw new Error(
+ "The edit's retry window expired; its outcome is unknown",
+ );
+ }
+ store.set(stateAtom, { status: "sending" });
+ const controller = new AbortController();
+ const abort = () => controller.abort(request.controller.signal.reason);
+ request.controller.signal.addEventListener("abort", abort, {
+ once: true,
+ });
+ const timeout = setTimeout(
+ () => controller.abort(new Error("The edit request timed out")),
+ REQUEST_TIMEOUT_MS,
+ );
+ let result: Result<Protocol.EditResponseOutput> | undefined;
+ try {
+ signal.throwIfAborted();
+ request.controller.signal.throwIfAborted();
+ result = await abortable(
+ notebook.edit(request.edit.notebookId, request.edit.changes, {
+ idempotencyKey: request.idempotencyKey,
+ signal: controller.signal,
+ }),
+ controller.signal,
+ );
+ } catch (error) {
+ // The host may or may not have applied it. Repeat it with the same key.
+ if (request.controller.signal.aborted || attempt === MAX_ATTEMPTS - 1) {
+ throw error;
+ }
+ } finally {
+ clearTimeout(timeout);
+ request.controller.signal.removeEventListener("abort", abort);
+ }
+ signal.throwIfAborted();
+ request.controller.signal.throwIfAborted();
+ if (result === undefined) {
+ await delay(500 * 2 ** attempt, request.controller.signal);
+ continue;
+ }
+ // The host answered, so repeating the request returns the same answer.
+ if (!result.ok) {
+ request.problem = result.problem;
+ throw new Error(result.problem.detail ?? result.problem.title, {
+ cause: result.problem,
+ });
+ }
+ if (result.data.document.notebook_id !== request.edit.notebookId) {
+ throw new Error("Edit response belongs to another notebook");
+ }
+ request.response = result.data.document;
+ store.set(state.settleAtom, request.edit, request.response);
+ return;
+ }
+ }
+
+ function confirm(request: Submission): Promise<void> {
+ store.set(stateAtom, { status: "confirming" });
+ return new Promise((resolve, reject) => {
+ const check = () => {
+ if (signal.aborted || request.controller.signal.aborted) {
+ cleanup();
+ reject(
+ signal.aborted ? signal.reason : request.controller.signal.reason,
+ );
+ } else if (store.get(state.pendingAtom) !== request.edit) {
+ cleanup();
+ resolve();
+ }
+ };
+ const unsubscribe = store.sub(observed, check);
+ const cleanup = () => {
+ unsubscribe();
+ request.controller.signal.removeEventListener("abort", check);
+ };
+ request.controller.signal.addEventListener("abort", check, {
+ once: true,
+ });
+ check();
+ });
+ }
+
+ async function drain(
+ notebookId: Protocol.NotebookId,
+ ): Promise<Protocol.Document> {
+ try {
+ while (true) {
+ signal.throwIfAborted();
+ const current = store.get(source);
+ if (current && current.revision.notebook_id !== notebookId) {
+ throw new Error("The notebook changed during synchronization");
+ }
+ if (active === null) {
+ if (current === null || store.get(state.changesAtom) === null) {
+ throw unavailable();
+ }
+ const edit = store.set(state.submitAtom);
+ if (edit === null) {
+ return current.revision;
+ }
+ active = {
+ edit,
+ idempotencyKey: idempotencyKey(),
+ startedAt: Date.now(),
+ controller: new AbortController(),
+ };
+ }
+ if (!active.response) {
+ await send(active);
+ }
+ await confirm(active);
+ active = null;
+ }
+ } catch (cause: unknown) {
+ signal.throwIfAborted();
+ const error =
+ cause instanceof Error
+ ? cause
+ : new Error("Document synchronization failed", { cause });
+ failure = {
+ status: "error",
+ error,
+ problem: active?.problem,
+ retryable:
+ !signal.aborted &&
+ !active?.controller.signal.aborted &&
+ (active === null ||
+ active.problem !== undefined ||
+ Date.now() - active.startedAt < RETRY_WINDOW_MS),
+ };
+ if (!signal.aborted) {
+ store.set(stateAtom, failure);
+ }
+ throw error;
+ } finally {
+ // Stop accepting joiners in the same turn that the drain finishes.
+ running = null;
+ refresh();
+ }
+ }
+
+ /** Drain edits and return the revision to use as the subsequent command's precondition. */
+ function flush(): Promise<Protocol.Document> {
+ clearTimer();
+ if (signal.aborted) {
+ return Promise.reject(signal.reason);
+ }
+ if (failure) {
+ return Promise.reject(failure.error);
+ }
+ if (running) {
+ return running;
+ }
+ const notebookId =
+ active?.edit.notebookId ?? store.get(source)?.revision.notebook_id;
+ if (notebookId === undefined) {
+ return Promise.reject(unavailable());
+ }
+ running = Promise.resolve().then(() => drain(notebookId));
+ return running;
+ }
+
+ /** Explicitly retry a rejection against fresh state, or repeat an uncertain request exactly. */
+ function retry(): Promise<Protocol.Document> {
+ if (signal.aborted) {
+ return Promise.reject(signal.reason);
+ }
+ if (!failure) {
+ return flush();
+ }
+ if (!failure.retryable) {
+ return Promise.reject(failure.error);
+ }
+ if (active?.problem) {
+ const current = store.get(source);
+ const rejectedAt = active.problem.edit?.document.version;
+ if (
+ !current ||
+ current.revision.notebook_id !== active.edit.notebookId ||
+ (rejectedAt !== undefined && current.revision.version < rejectedAt)
+ ) {
+ return Promise.reject(
+ new Error("Wait for the host's current document before retrying"),
+ );
+ }
+ store.set(state.settleAtom, active.edit, null);
+ active = null;
+ }
+ failure = null;
+ return flush();
+ }
+
+ const unsubscribe = store.sub(observed, refresh);
+ function stop() {
+ clearTimer();
+ unsubscribe();
+ signal.removeEventListener("abort", stop);
+ active?.controller.abort(signal.reason);
+ }
+ signal.addEventListener("abort", stop, { once: true });
+ if (signal.aborted) {
+ stop();
+ }
+ refresh();
+ return { stateAtom, flush, retry };
+}
diff --git a/frontend/src/core/host/__tests__/notebook-client.test.ts b/frontend/src/core/host/__tests__/notebook-client.test.ts
index d226ba5cb4..a41a14dfe8 100644
--- a/frontend/src/core/host/__tests__/notebook-client.test.ts
+++ b/frontend/src/core/host/__tests__/notebook-client.test.ts
@@ -7,7 +7,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { Deferred } from "@/utils/Deferred";
import { ConnectionState } from "../../websocket/types";
import type { ConnectionStatus } from "../connection";
-import { createNotebookClient } from "../notebook-client";
+import { createNotebookClient, type NotebookClient } from "../notebook-client";
import { fixtureEvents, fixtureMessages } from "./fixtures";
/** One connection the fake transport opened. */
@@ -22,7 +22,7 @@ interface Attempt {
stop(status?: ConnectionStatus): void;
}
-function setup() {
+function setup(edit?: NotebookClient["edit"]) {
const attempts: Attempt[] = [];
const transport: NotebookTransport = ({ cursor, signal }, handlers) =>
new Promise((resolve, reject) => {
@@ -40,7 +40,7 @@ function setup() {
const onNotification = vi.fn();
const checkHealth = vi.fn(async () => true);
const store = createStore();
- const controller = createNotebookClient(store);
+ const controller = createNotebookClient(store, { edit });
const client = controller.client;
const connect = (signal: AbortSignal) =>
controller.connect({
@@ -98,6 +98,62 @@ const notebook = {
};
describe("NotebookClient lifetime", () => {
+ it("keeps an edit's target and request identity across a stream reset", async () => {
+ const edit = vi.fn<NotebookClient["edit"]>().mockResolvedValue({
+ ok: false,
+ status: 409,
+ problem: { type: "conflict", title: "conflict", status: 409 },
+ });
+ const { connect, opened, client } = setup(edit);
+ connect(lifetime().signal);
+ const { receive } = await opened();
+ fixtureMessages("notebook-events.sse").forEach(receive);
+ const options = { idempotencyKey: "edit-1", signal: lifetime().signal };
+ await client.edit("n1", [], options);
+ receive({ event: "reset", data: {} });
+ await client.edit("n1", [], options);
+ expect(edit.mock.calls).toEqual([
+ ["n1", [], options],
+ ["n1", [], options],
+ ]);
+
+ receive({
+ event: "notebook",
+ data: { notebook: { ...notebook, id: "n2" } },
+ });
+ await expect(client.edit("n1", [], options)).rejects.toThrow(
+ "notebook changed",
+ );
+ expect(edit).toHaveBeenCalledTimes(2);
+ });
+
+ it("rejects aborted edits and reports a missing edit adapter", async () => {
+ const { client } = setup();
+ const controller = lifetime();
+ await expect(
+ client.edit("n1", [], {
+ idempotencyKey: "edit-1",
+ signal: controller.signal,
+ }),
+ ).resolves.toEqual({
+ ok: false,
+ status: 501,
+ problem: {
+ type: "tag:marimo.io,2026:host/unsupported-operation",
+ title: "Document editing is unavailable on this connection",
+ status: 501,
+ },
+ });
+ const reason = new Error("Session ended");
+ controller.abort(reason);
+ await expect(
+ client.edit("n1", [], {
+ idempotencyKey: "edit-1",
+ signal: controller.signal,
+ }),
+ ).rejects.toBe(reason);
+ });
+
it("exposes identity and capabilities only after the notebook is ready", async () => {
const { connect, opened, client, store } = setup();
connect(lifetime().signal);
diff --git a/frontend/src/core/host/notebook-client.ts b/frontend/src/core/host/notebook-client.ts
index 70e63d49de..061b7cd1c9 100644
--- a/frontend/src/core/host/notebook-client.ts
+++ b/frontend/src/core/host/notebook-client.ts
@@ -6,9 +6,16 @@ import {
type NotebookEvent,
NotebookEvents,
type NotebookTransport,
+ type Result,
StreamStopped,
} from "@marimo-team/client";
-import type { Attachment, NotebookOutput } from "@marimo-team/client/protocol";
+import type {
+ Attachment,
+ Change,
+ EditResponseOutput,
+ NotebookId,
+ NotebookOutput,
+} from "@marimo-team/client/protocol";
import { type Atom, atom, type createStore } from "jotai/vanilla";
import { z } from "zod";
import {
@@ -41,6 +48,12 @@ export interface NotebookClient {
* retains the last document. Partial updates are not exposed.
*/
readonly documentAtom: Atom<Document | null>;
+ /** Apply an edit to the notebook captured by the caller, even across a reset. */
+ edit(
+ notebookId: NotebookId,
+ changes: readonly Change[],
+ options: { readonly idempotencyKey: string; readonly signal: AbortSignal },
+ ): Promise<Result<EditResponseOutput>>;
/** Live attachments, empty until the stream is ready or while disconnected. */
readonly attachmentsAtom: Atom<readonly Attachment[]>;
/** Attempt to restore a closed connection after checking host health. */
@@ -90,8 +103,14 @@ function statusAfter(error: unknown): ConnectionStatus {
return disconnected;
}
-/** Create a client without opening a connection. */
-export function createNotebookClient(store: ReturnType<typeof createStore>) {
+/**
+ * Create a client without opening a connection.
+ * The session supplies edits authenticated for the same host as its stream.
+ */
+export function createNotebookClient(
+ store: ReturnType<typeof createStore>,
+ { edit }: { edit?: NotebookClient["edit"] } = {},
+) {
// `useNotebookSession` copies this into the editor's shared `connectionAtom`,
// which gates features until MO-8051 derives availability separately.
const connectionAtom = atom<ConnectionStatus>({
@@ -122,6 +141,25 @@ export function createNotebookClient(store: ReturnType<typeof createStore>) {
connectionAtom,
notebookAtom,
documentAtom,
+ edit: async (notebookId, changes, options) => {
+ options.signal.throwIfAborted();
+ const currentId = store.get(streamAtom).notebookId;
+ if (currentId !== null && currentId !== notebookId) {
+ throw new Error("The notebook changed before the edit was sent");
+ }
+ if (edit === undefined) {
+ return {
+ ok: false,
+ status: 501,
+ problem: {
+ type: "tag:marimo.io,2026:host/unsupported-operation",
+ title: "Document editing is unavailable on this connection",
+ status: 501,
+ },
+ };
+ }
+ return edit(notebookId, changes, options);
+ },
attachmentsAtom,
reconnect: async () => reconnect?.(),
};
diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts
index 2d72f0b0e1..5c891b0976 100644
--- a/packages/client/src/index.ts
+++ b/packages/client/src/index.ts
@@ -17,7 +17,7 @@ export {
type NotebookEventsOptions,
type NotebookEvent,
} from "./notebook/events.ts";
-export type { Result } from "./request.ts";
+export { idempotencyKey, type Result } from "./request.ts";
export {
type Frame,
type Transport,
diff --git a/packages/client/src/request.ts b/packages/client/src/request.ts
index a9ab818049..4efa7da1b0 100644
--- a/packages/client/src/request.ts
+++ b/packages/client/src/request.ts
@@ -110,10 +110,12 @@ interface Call<Id extends RequestOperationId> {
/**
* A random key for a request that changes state.
*
- * `crypto.randomUUID` exists only in secure contexts, such as pages served
- * over HTTPS or from localhost. A host on a local network is often neither.
+ * Send it again with a retry whose outcome is unknown, so the host applies the
+ * request once. `crypto.randomUUID` exists only in secure contexts, such as
+ * pages served over HTTPS or from localhost. A host on a local network is
+ * often neither.
*/
-function idempotencyKey(): string {
+export function idempotencyKey(): string {
if (typeof globalThis.crypto.randomUUID === "function") {
return globalThis.crypto.randomUUID();
}