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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
Test document synchronization through notebook scenarios (#11462)
Trevor Manz587b557f82fc
diff --git a/frontend/src/core/document/__tests__/lifecycle-scenarios.test.ts b/frontend/src/core/document/__tests__/lifecycle-scenarios.test.tsnew file mode 100644index 0000000000..2500e098b2--- /dev/null+++ b/frontend/src/core/document/__tests__/lifecycle-scenarios.test.ts@@ -0,0 +1,61 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { vi } from "vitest";+import { test } from "./scenario-fixture";++test("closing a session before the debounce prevents submission", async ({+ expect,+ session: { user, notebook, controller },+}) => {+ user.changeCode("c3", "local");+ const reason = new Error("Editing session ended");+ controller.abort(reason);+ await vi.advanceTimersByTimeAsync(1000);+ expect(notebook.edit).not.toHaveBeenCalled();+ expect(vi.getTimerCount()).toBe(0);+ await expect(user.sync()).rejects.toBe(reason);+});++test("closing a session before a queued flush starts prevents submission", async ({+ expect,+ session: { user, notebook, controller },+}) => {+ user.changeCode("c3", "local");+ const flushed = user.sync();+ const reason = new Error("Editing session ended");+ controller.abort(reason);+ await expect(flushed).rejects.toBe(reason);+ expect(notebook.edit).not.toHaveBeenCalled();+ expect(vi.getTimerCount()).toBe(0);+});++test.for(["request", "confirmation", "retry"] as const)(+ "closing a session during %s stops synchronization",+ async (phase, { expect, session: { user, host, notebook, controller } }) => {+ user.changeCode("c3", "local");+ const flushed = user.sync();+ const request = await host.nextRequest();+ if (phase === "confirmation") {+ request.process();+ request.deliverResponse();+ } else if (phase === "retry") {+ request.loseResponse();+ }+ await vi.advanceTimersByTimeAsync(0);+ const reason = new Error("Editing session ended");+ controller.abort(reason);+ await expect(flushed).rejects.toBe(reason);+ if (phase === "request") {+ expect(request.signal.aborted).toBe(true);+ }++ host.changeCell("c1", { code: "later" });+ host.deliverSnapshot();+ user.changeCode("c3", "after closing");+ await vi.advanceTimersByTimeAsync(1000);+ expect(notebook.edit).toHaveBeenCalledOnce();+ expect(vi.getTimerCount()).toBe(0);+ await expect(user.sync()).rejects.toBe(reason);+ await expect(user.retry()).rejects.toBe(reason);+ },+);diff --git a/frontend/src/core/document/__tests__/model.test.ts b/frontend/src/core/document/__tests__/model.test.tsindex b49d143031..5e5e02bb28 100644--- a/frontend/src/core/document/__tests__/model.test.ts+++ b/frontend/src/core/document/__tests__/model.test.ts@@ -101,69 +101,6 @@ describe("document synchronization", () => {expect(vi.getTimerCount()).toBe(0);});- 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("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);-- 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" } },- ]);-- 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("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 accepted = withCells(document(), { c1: cell("c1", "local") });- replies[3].resolve(response(accepted));- store.set(source, accepted);- await expect(retried).resolves.toEqual(accepted.revision);- });-it("fails without repeating a request when the response names another notebook", async () => {const { sent, replies, edit, model, state } = setup();edit("local");@@ -176,257 +113,6 @@ describe("document synchronization", () => {expect(state()).toMatchObject({ status: "error" });});- 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" },- });- edit("newer");- const accepted = withCells(document(), {- c1: cell("c1", "sent", { etag: "accepted" }),- });- 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" },- });- 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.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" }),- });- 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");- });-- 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" }),- });- 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,- });- 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" },- });- 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("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 },- },- });- 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("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("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("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.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,@@ -458,17 +144,6 @@ describe("document synchronization", () => {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");diff --git a/frontend/src/core/document/__tests__/protocol-fixtures.ts b/frontend/src/core/document/__tests__/protocol-fixtures.tsnew file mode 100644index 0000000000..22fbc0b800--- /dev/null+++ b/frontend/src/core/document/__tests__/protocol-fixtures.ts@@ -0,0 +1,38 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { readFileSync } from "node:fs";+import NodeUrl from "node:url";+import type * as Protocol from "@marimo-team/client/protocol";+import { invariant } from "@/utils/invariant";+import { fixtureEvents } from "../../host/__tests__/fixtures";+import type { Document } from "../../host/resources/document";++export function protocolFixture(name: string): unknown {+ return JSON.parse(+ readFileSync(+ new NodeUrl.URL(+ `../../../../../protocols/host/fixtures/${name}`,+ import.meta.url,+ ),+ "utf8",+ ),+ );+}++export function initialDocument(): Document {+ const cells = new Map<Protocol.CellId, Protocol.Cell>();+ let revision: Protocol.Document | undefined;+ for (const event of fixtureEvents("notebook-events.sse")) {+ if (event.event === "ready") {+ break;+ }+ if (event.event === "cell") {+ cells.set(event.data.cell.id, event.data.cell);+ }+ if (event.event === "document") {+ revision = event.data.document;+ }+ }+ invariant(revision !== undefined, "Fixture has no document");+ return { revision, cells };+}diff --git a/frontend/src/core/document/__tests__/recovery-scenarios.test.ts b/frontend/src/core/document/__tests__/recovery-scenarios.test.tsnew file mode 100644index 0000000000..849f372c7d--- /dev/null+++ b/frontend/src/core/document/__tests__/recovery-scenarios.test.ts@@ -0,0 +1,230 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { vi } from "vitest";+import { test } from "./scenario-fixture";++test.for(["response", "document"] as const)(+ "keeps a conflicting batch intact and retries explicitly with %s first",+ async (first, { expect, session: { user, host, notebook } }) => {+ // The first change is valid; the second conflicts. Neither may commit.+ user.changeCells({+ c1: { code: "other local edit" },+ c3: { code: "local" },+ });+ const synced = user.sync();+ const request = await host.nextRequest();+ host.changeCell("c3", { code: "remote", name: "remote name" });+ const remote = host.document();+ expect(user.cell("c3")?.code).toBe("local");+ request.process();+ expect(host.document()).toEqual(remote);+ user.changeCode("c3", "updated local");++ if (first === "document") {+ host.deliverDocument();+ }+ request.deliverResponse();+ await expect(synced).rejects.toThrow("conflict");+ expect(user.status()).toMatchObject({ status: "error", retryable: true });+ if (first === "response") {+ host.deliverDocument();+ }+ await vi.advanceTimersByTimeAsync(2000);+ expect(notebook.edit).toHaveBeenCalledOnce();+ expect(user.cell("c3")?.code).toBe("updated local");+ expect(user.cell("c1")?.code).toBe("other local edit");++ const retried = user.retry();+ const retry = await host.nextRequest();+ expect(retry.idempotencyKey).not.toBe(request.idempotencyKey);+ retry.process();+ retry.deliverResponse();+ host.deliverDocument();+ await expect(retried).resolves.toEqual(host.document().revision);+ expect(host.document().cells.get("c1")?.code).toBe("other local edit");+ expect(host.document().cells.get("c3")).toMatchObject({+ code: "updated local",+ name: "remote name",+ });+ expect(user.cell("c3")).toMatchObject({+ code: "updated local",+ name: "remote name",+ });+ expect(user.status()).toEqual({ status: "idle" });+ },+);++test("waits for the conflicting revision before allowing a retry", async ({+ expect,+ session: { user, host, notebook },+}) => {+ user.changeCode("c3", "local");+ const synced = user.sync();+ const request = await host.nextRequest();+ host.changeCell("c3", { code: "remote" });+ request.process();+ request.deliverResponse();+ await expect(synced).rejects.toThrow("conflict");+ await expect(user.retry()).rejects.toThrow("Wait for the host");+ expect(notebook.edit).toHaveBeenCalledOnce();+ expect(user.cell("c3")?.code).toBe("local");++ host.deliverDocument();+ const retried = user.retry();+ const retry = await host.nextRequest();+ retry.process();+ retry.deliverResponse();+ host.deliverDocument();+ await expect(retried).resolves.toEqual(host.document().revision);+ expect(host.document().cells.get("c3")?.code).toBe("local");+ expect(user.status()).toEqual({ status: "idle" });+});++test("replays a lost response without committing twice or losing newer typing", async ({+ expect,+ session: { user, host },+}) => {+ user.changeCode("c3", "sent");+ const flushed = user.sync();+ const request = await host.nextRequest();+ request.process();+ const committed = host.document();+ host.deliverDocument();+ user.changeCode("c3", "newer");+ request.loseResponse();++ await vi.advanceTimersByTimeAsync(500);+ const retry = await host.nextRequest();+ expect(retry.idempotencyKey).toBe(request.idempotencyKey);+ expect(retry.changes).toEqual(request.changes);+ retry.process();+ expect(host.document()).toEqual(committed);+ retry.deliverResponse();++ const next = await host.nextRequest();+ expect(next.idempotencyKey).not.toBe(request.idempotencyKey);+ next.process();+ next.deliverResponse();+ host.deliverDocument();+ await expect(flushed).resolves.toEqual(host.document().revision);+ expect(host.document().revision.version).toBe(committed.revision.version + 1);+ expect(host.document().cells.get("c3")?.code).toBe("newer");+ expect(user.cell("c3")?.code).toBe("newer");+});++test("ignores a timed-out attempt that completes after its retry", async ({+ expect,+ session: { user, host, notebook },+}) => {+ user.changeCode("c3", "local");+ const flushed = user.sync();+ const first = await host.nextRequest();+ await vi.advanceTimersByTimeAsync(10_500);+ const retry = await host.nextRequest();+ expect(first.signal.aborted).toBe(true);+ expect(retry.idempotencyKey).toBe(first.idempotencyKey);+ retry.process();+ const committed = host.document();+ retry.deliverResponse();+ host.deliverDocument();+ await expect(flushed).resolves.toEqual(committed.revision);+ first.process();+ first.deliverResponse();+ await vi.advanceTimersByTimeAsync(0);+ expect(host.document()).toEqual(committed);+ expect(user.cell("c3")?.code).toBe("local");+ expect(notebook.edit).toHaveBeenCalledTimes(2);+});++test("a manual retry reuses the committed edit after automatic retries give up", async ({+ expect,+ session: { user, host, notebook },+}) => {+ user.changeCode("c3", "sent");+ const synced = user.sync();+ const request = await host.nextRequest();+ request.process();+ const committed = host.document();+ request.loseResponse();+ for (const delay of [500, 1000]) {+ await vi.advanceTimersByTimeAsync(delay);+ const retry = await host.nextRequest();+ retry.process();+ retry.loseResponse();+ }+ await expect(synced).rejects.toThrow("Connection lost");+ expect(user.status()).toMatchObject({ status: "error", retryable: true });+ expect(notebook.edit).toHaveBeenCalledTimes(3);+ expect(host.document()).toEqual(committed);++ const retried = user.retry();+ const retry = await host.nextRequest();+ expect(retry.idempotencyKey).toBe(request.idempotencyKey);+ expect(retry.changes).toEqual(request.changes);+ retry.process();+ retry.deliverResponse();+ host.deliverDocument();+ await expect(retried).resolves.toEqual(committed.revision);+ expect(host.document()).toEqual(committed);+ expect(user.status()).toEqual({ status: "idle" });+ expect(notebook.edit).toHaveBeenCalledTimes(4);+});++test("refuses a manual retry after the safe retry window while retaining the draft", async ({+ expect,+ session: { user, host, notebook },+}) => {+ user.changeCode("c3", "sent");+ const synced = user.sync();+ const request = await host.nextRequest();+ request.process();+ const committed = host.document();+ request.loseResponse();+ for (const delay of [500, 1000]) {+ await vi.advanceTimersByTimeAsync(delay);+ const retry = await host.nextRequest();+ retry.process();+ retry.loseResponse();+ }+ await expect(synced).rejects.toThrow("Connection lost");+ expect(user.status()).toMatchObject({ status: "error", retryable: true });++ await vi.advanceTimersByTimeAsync(60_000);+ await expect(user.retry()).rejects.toThrow("retry window expired");+ expect(user.status()).toMatchObject({ status: "error", retryable: false });+ expect(notebook.edit).toHaveBeenCalledTimes(3);+ expect(host.document()).toEqual(committed);+ expect(user.cell("c3")?.code).toBe("sent");+});++test("keeps the whole draft when another writer deletes an edited cell", async ({+ expect,+ session: { user, host, notebook },+}) => {+ user.changeCode("c3", "keep this");+ const synced = user.sync();+ const request = await host.nextRequest();+ host.deleteCell("c3");+ request.process();+ request.deliverResponse();+ host.deliverDocument();+ await expect(synced).rejects.toThrow("conflict");++ user.changeCode("c1", "other edit");+ await expect(user.retry()).rejects.toThrow("unavailable");+ await vi.advanceTimersByTimeAsync(1000);+ expect(notebook.edit).toHaveBeenCalledOnce();+ expect(host.document().cells.get("c1")?.code).toBe("import marimo as mo");++ host.createCell({ id: "c3", code: "restored" });+ host.deliverDocument();+ expect(user.cell("c3")?.code).toBe("keep this");+ const retried = user.retry();+ const retry = await host.nextRequest();+ retry.process();+ retry.deliverResponse();+ host.deliverDocument();+ await expect(retried).resolves.toEqual(host.document().revision);+ expect(host.document().cells.get("c3")?.code).toBe("keep this");+ expect(host.document().cells.get("c1")?.code).toBe("other edit");+});diff --git a/frontend/src/core/document/__tests__/scenario-fixture.ts b/frontend/src/core/document/__tests__/scenario-fixture.tsnew file mode 100644index 0000000000..2ece5a7ca4--- /dev/null+++ b/frontend/src/core/document/__tests__/scenario-fixture.ts@@ -0,0 +1,42 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { createStore } from "jotai/vanilla";+import { test as baseTest, vi } from "vitest";+import type { Document } from "../../host/resources/document";+import { createDocumentModel } from "../model";+import { initialDocument } from "./protocol-fixtures";+import { createTestNotebook } from "./test-notebook";+import { createUser } from "./user";++function createSession(initial: Document, controller: AbortController) {+ const store = createStore();+ const { notebook, control } = createTestNotebook(store, initial);+ const model = createDocumentModel({+ store,+ notebook,+ signal: controller.signal,+ });+ return {+ user: createUser(store, model),+ host: control,+ notebook,+ controller,+ };+}++export const test = baseTest.extend<{+ initial: Document;+ session: ReturnType<typeof createSession>;+}>({+ initial: initialDocument(),+ session: async ({ initial }, provide) => {+ vi.useFakeTimers({ now: 0 });+ const controller = new AbortController();+ try {+ await provide(createSession(initial, controller));+ } finally {+ controller.abort();+ vi.useRealTimers();+ }+ },+});diff --git a/frontend/src/core/document/__tests__/scenarios.test.ts b/frontend/src/core/document/__tests__/scenarios.test.tsnew file mode 100644index 0000000000..13a4184c18--- /dev/null+++ b/frontend/src/core/document/__tests__/scenarios.test.ts@@ -0,0 +1,205 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { vi } from "vitest";+import { test } from "./scenario-fixture";++test("waits for a pause in typing before sending the latest edit", async ({+ expect,+ session: { user, host, notebook },+}) => {+ user.changeCode("c3", "first");+ await vi.advanceTimersByTimeAsync(300);+ user.changeCode("c3", "latest");+ await vi.advanceTimersByTimeAsync(399);+ expect(notebook.edit).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1);+ expect(notebook.edit).toHaveBeenCalledOnce();+ const request = await host.nextRequest();+ request.process();+ request.deliverResponse();+ host.deliverDocument();+ await expect(user.sync()).resolves.toEqual(host.document().revision);+ expect(host.document().cells.get("c3")?.code).toBe("latest");+});++test.for(["response", "document"] as const)(+ "preserves newer typing when the %s arrives first",+ async (first, { expect, session: { user, host, notebook } }) => {+ user.changeCells({ c3: { code: "sent", config: { hide_code: true } } });+ const flushed = user.sync();+ const finished = vi.fn();+ void flushed.then(finished, () => undefined);+ const request = await host.nextRequest();+ request.process();+ user.changeCode("c3", "still typing");++ const deliver = {+ response: () => request.deliverResponse(),+ document: () => host.deliverDocument(),+ };+ deliver[first]();+ await vi.advanceTimersByTimeAsync(0);+ expect(finished).not.toHaveBeenCalled();+ expect(notebook.edit).toHaveBeenCalledOnce();+ expect(user.cell("c3")?.code).toBe("still typing");++ deliver[first === "response" ? "document" : "response"]();+ await vi.advanceTimersByTimeAsync(0);+ expect(user.cell("c3")?.code).toBe("still typing");+ const next = await host.nextRequest();+ next.process();+ next.deliverResponse();+ host.deliverDocument();+ await expect(flushed).resolves.toEqual(host.document().revision);+ const expected = {+ id: "c3",+ code: "still typing",+ name: "_",+ config: {+ column: null,+ disabled: false,+ hide_code: true,+ expand_output: false,+ },+ };+ expect(user.cell("c3")).toEqual(expected);+ expect(host.document().cells.get("c3")).toMatchObject(expected);+ expect(user.status()).toEqual({ status: "idle" });++ host.changeCell("c3", {+ code: "another writer",+ config: { hide_code: false },+ });+ host.deliverDocument();+ expect(user.cell("c3")?.code).toBe("another writer");+ expect(user.cell("c3")?.config.hide_code).toBe(false);+ },+);++test("uses a newer confirmed document for edits that have not been sent", async ({+ expect,+ session: { user, host },+}) => {+ user.changeCode("c3", "local");+ host.changeCell("c3", { name: "remote name" });+ host.deliverDocument();+ const flushed = user.sync();+ const request = await host.nextRequest();+ request.process();+ request.deliverResponse();+ host.deliverDocument();+ await expect(flushed).resolves.toEqual(host.document().revision);+ expect(host.document().cells.get("c3")).toMatchObject({+ code: "local",+ name: "remote name",+ });+});++test.for(["before reset", "during reset", "after snapshot"] as const)(+ "recovers across reset when the response arrives %s",+ async (arrival, { expect, session: { user, host } }) => {+ user.changeCode("c3", "sent");+ const flushed = user.sync();+ const request = await host.nextRequest();+ request.process();+ user.changeCode("c3", "newer typing");+ if (arrival === "before reset") {+ request.deliverResponse();+ await vi.advanceTimersByTimeAsync(0);+ }+ host.reset();+ if (arrival === "during reset") {+ request.deliverResponse();+ await vi.advanceTimersByTimeAsync(0);+ }+ host.changeCell("c1", { code: "unrelated edit" });+ host.deliverSnapshot();+ if (arrival === "after snapshot") {+ await vi.advanceTimersByTimeAsync(0);+ request.deliverResponse();+ }+ expect(user.cell("c3")?.code).toBe("newer typing");+ const next = await host.nextRequest();+ next.process();+ next.deliverResponse();+ host.deliverDocument();+ await expect(flushed).resolves.toEqual(host.document().revision);+ expect(host.document().cells.get("c3")?.code).toBe("newer typing");+ expect(user.cell("c1")?.code).toBe("unrelated edit");+ expect(user.status()).toEqual({ status: "idle" });++ host.changeCell("c3", { code: "another writer" });+ host.deliverDocument();+ expect(user.cell("c3")?.code).toBe("another writer");+ },+);++test.for(["response", "document"] as const)(+ "does not resurrect a cancelled creation when the %s arrives first",+ async (first, { expect, session: { user, host } }) => {+ user.createCell({ id: "new", code: "new cell" });+ const flushed = user.sync();+ const creation = await host.nextRequest();+ user.deleteCell("new");+ host.changeCell("c1", { code: "unrelated edit" });+ host.deliverDocument();+ creation.process();+ const deliver = {+ response: () => creation.deliverResponse(),+ document: () => host.deliverDocument(),+ };+ deliver[first]();+ await vi.advanceTimersByTimeAsync(0);+ expect(user.cell("new")).toBeUndefined();+ expect(user.order()).toEqual(["c1", "c3", "k7f2"]);+ deliver[first === "response" ? "document" : "response"]();+ const deletion = await host.nextRequest();+ deletion.process();+ deletion.deliverResponse();+ host.deliverDocument();+ await expect(flushed).resolves.toEqual(host.document().revision);+ expect(host.document().cells.has("new")).toBe(false);+ expect(user.cell("new")).toBeUndefined();+ },+);++test("releases an edit undone before sending and follows subsequent host changes", async ({+ expect,+ session: { user, host, notebook },+}) => {+ user.changeCode("c3", "temporary");+ user.changeCode("c3", "x = 21");+ expect(user.status()).toEqual({ status: "idle" });+ await expect(user.sync()).resolves.toEqual(host.document().revision);++ host.changeCell("c3", { code: "another writer" });+ host.deliverDocument();+ expect(user.cell("c3")?.code).toBe("another writer");+ await vi.advanceTimersByTimeAsync(1000);+ expect(notebook.edit).not.toHaveBeenCalled();+});++test("flushes edits made while an earlier flush is finishing", async ({+ expect,+ session: { user, host, notebook },+}) => {+ const original = host.document().revision;+ const first = user.sync();+ // Let the first flush drain without awaiting its returned promise.+ await Promise.resolve();+ user.changeCode("c3", "new code");+ const second = user.sync();+ const settled = vi.fn();+ void second.then(settled, settled);++ await vi.advanceTimersByTimeAsync(0);+ expect(notebook.edit).toHaveBeenCalledOnce();+ expect(settled).not.toHaveBeenCalled();+ const request = await host.nextRequest();+ request.process();+ expect(host.document().cells.get("c3")?.code).toBe("new code");+ request.deliverResponse();+ host.deliverDocument();+ await expect(second).resolves.toEqual(host.document().revision);+ await expect(first).resolves.toEqual(original);+});diff --git a/frontend/src/core/document/__tests__/submission.test.ts b/frontend/src/core/document/__tests__/submission.test.tsindex dfd6a3aaec..bee525661a 100644--- a/frontend/src/core/document/__tests__/submission.test.ts+++ b/frontend/src/core/document/__tests__/submission.test.ts@@ -25,7 +25,6 @@ function setup() {store,source,...model,- abort: () => controller.abort(),submit() {const submission = store.set(model.submitAtom);if (submission === null) {@@ -104,106 +103,39 @@ describe("document submissions", () => {);it.each(["response", "stream"] as const)(- "preserves later typing when the %s arrives first",+ "does not notify cell subscribers when the %s acknowledges a superseded draft",(first) => {- const {- store,- source,- editAtom,- cellAtom,- changesAtom,- submitAtom,- submit,- settle,- } = setup();+ const { store, source, editAtom, cellAtom, submit, settle } = setup();store.set(editAtom, (tx) => {tx.setCode("c1", "sent");- tx.updateConfig("c1", { hide_code: true });+ tx.createCell({ id: "c3", code: "new" });});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 },- }),+ store.set(editAtom, (tx) => {+ tx.setCode("c1", "still typing");+ tx.deleteCell("c3");});- 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,- }),+ const onCode = vi.fn();+ const onCreation = vi.fn();+ const unsubscribeCode = store.sub(cellAtom("c1"), onCode);+ const unsubscribeCreation = store.sub(cellAtom("c3"), onCreation);+ const confirmed = withCells(document(), {+ c1: cell("c1", "sent", { etag: "accepted", version: 2 }),+ c3: cell("c3", "new"),});- 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([]);+ try {+ arrivals[first]();+ arrivals[first === "response" ? "stream" : "response"]();+ expect(onCode).not.toHaveBeenCalled();+ expect(onCreation).not.toHaveBeenCalled();+ } finally {+ unsubscribeCode();+ unsubscribeCreation();+ }},);@@ -227,36 +159,6 @@ describe("document submissions", () => {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"));@@ -296,51 +198,4 @@ describe("document submissions", () => {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,- abort,- } = setup();- store.set(editAtom, (tx) => tx.setCode("c1", "local"));- const sent = submit();- abort();- 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);- abort();- 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/__tests__/test-host.test.ts b/frontend/src/core/document/__tests__/test-host.test.tsnew file mode 100644index 0000000000..bdb0f474de--- /dev/null+++ b/frontend/src/core/document/__tests__/test-host.test.ts@@ -0,0 +1,92 @@+/* Copyright 2026 Marimo. All rights reserved. */++import * as Protocol from "@marimo-team/client/protocol";+import { afterEach, expect, it, vi } from "vitest";+import { initialDocument, protocolFixture } from "./protocol-fixtures";+import { createTestHost } from "./test-host";++afterEach(() => vi.useRealTimers());++it("matches the portable host examples for accepted and conflicting edits", () => {+ const host = createTestHost(initialDocument());+ const accepted = host.process({+ notebookId: "n1",+ idempotencyKey: "accepted",+ changes: Protocol.EditRequest.parse(protocolFixture("edit.json")).changes,+ });+ const expected = Protocol.EditResponse.parse(+ protocolFixture("edit-response.json"),+ );+ expect(accepted.result).toEqual({ ok: true, status: 200, data: expected });+ expect(accepted.update).toEqual(host.document());++ const rejected = host.process({+ notebookId: "n1",+ idempotencyKey: "rejected",+ changes: Protocol.EditRequest.parse(+ protocolFixture("edit-conflict-request.json"),+ ).changes,+ });+ const problem = Protocol.Problem.parse(+ protocolFixture("problems/edit-conflict.json"),+ );+ expect(rejected).toEqual({+ result: {+ ok: false,+ status: 409,+ problem: { ...problem, detail: expect.any(String) },+ },+ });+ expect(host.document().revision).toEqual(expected.document);+});++it("rejects an entire batch when a later precondition is stale", () => {+ const initial = initialDocument();+ const host = createTestHost(initial);+ const result = host.apply([+ { kind: "put_cell", base_etag: null, cell: { id: "created", code: "new" } },+ { kind: "delete_cell", id: "c3", base_etag: "stale" },+ ]);+ expect(result).toMatchObject({+ result: { ok: false, status: 409, problem: { edit: { change: 1 } } },+ });+ expect(host.document()).toEqual(initial);+ expect(result.update).toBeUndefined();+});++it("keeps successful and rejected receipts tied to their original payload and revision", () => {+ vi.useFakeTimers({ now: 0 });+ const host = createTestHost(initialDocument());+ const request = {+ notebookId: "n1",+ idempotencyKey: "original",+ changes: Protocol.EditRequest.parse(protocolFixture("edit.json")).changes,+ };+ const accepted = host.process(request);+ const stale = {+ notebookId: "n1",+ idempotencyKey: "stale",+ changes: Protocol.EditRequest.parse(+ protocolFixture("edit-conflict-request.json"),+ ).changes,+ };+ const rejected = host.process(stale);+ host.apply([+ { kind: "put_cell", base_etag: "*", cell: { id: "c3", code: "later" } },+ ]);+ const latest = host.document();+ expect(host.process(request)).toEqual({ result: accepted.result });+ expect(host.process(stale)).toEqual({ result: rejected.result });+ expect(host.process({ ...request, changes: [] }).result).toMatchObject({+ ok: false,+ status: 409,+ });+ expect(host.document()).toEqual(latest);++ vi.advanceTimersByTime(300_000);+ expect(host.process(request).result).toMatchObject({+ ok: false,+ status: 409,+ });+ expect(host.document()).toEqual(latest);+});diff --git a/frontend/src/core/document/__tests__/test-host.ts b/frontend/src/core/document/__tests__/test-host.tsnew file mode 100644index 0000000000..ca49e24100--- /dev/null+++ b/frontend/src/core/document/__tests__/test-host.ts@@ -0,0 +1,247 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { createHash } from "node:crypto";+import type { Result } from "@marimo-team/client";+import * as Protocol from "@marimo-team/client/protocol";+import type { Document } from "../../host/resources/document";++export interface EditRequest {+ readonly notebookId: Protocol.NotebookId;+ readonly changes: readonly Protocol.Change[];+ readonly idempotencyKey: string;+}++interface Outcome {+ readonly result: Result<Protocol.EditResponseOutput>;+ /** Only a new commit produces a stream update; replaying a receipt does not. */+ readonly update?: Document;+}++const hash = (text: string) =>+ createHash("sha256").update(text).digest("hex").slice(0, 16);++function record(+ input: Protocol.CellInput,+ notebookId: Protocol.NotebookId,+ version: number,+): Protocol.Cell {+ const cell = Protocol.CellInput.parse(input);+ const config = Protocol.CellConfigInput.parse(cell.config ?? {});+ const code = cell.code.replace(/\r\n?/g, "\n");+ const codeHash = hash(code);+ return {+ id: cell.id,+ notebook_id: notebookId,+ name: cell.name,+ code,+ config,+ code_hash: codeHash,+ etag: hash(+ [+ codeHash,+ cell.name,+ ...[+ config.column,+ config.disabled,+ config.hide_code,+ config.expand_output,+ ].map((value) => JSON.stringify(value)),+ ].join("\n"),+ ),+ version,+ };+}++function rejected(+ status: number,+ kind: string,+ detail: string,+ edit?: Protocol.Problem["edit"],+): Outcome {+ return {+ result: {+ ok: false,+ status,+ problem: {+ type: `tag:marimo.io,2026:host/${kind}`,+ title: kind === "conflict" ? "Conflict" : "Invalid request",+ detail,+ status,+ ...(edit === undefined ? {} : { edit }),+ },+ },+ };+}++/** An independent implementation of the document edit protocol, without client draft logic. */+export function createTestHost(initial: Document) {+ let current = initial;+ const receipts = new Map<+ string,+ {+ fingerprint: string;+ result: Result<Protocol.EditResponseOutput>;+ expiresAt: number;+ }+ >();++ function apply(changes: readonly Protocol.Change[]): Outcome {+ const cells = new Map(current.cells);+ let order = [...current.revision.order];+ const touched = new Set<Protocol.CellId>();+ const version = current.revision.version + 1;+ const matches = (id: Protocol.CellId, etag: string) =>+ etag === "*" || current.cells.get(id)?.etag === etag;+ const conflict = (change: number, id?: Protocol.CellId) =>+ rejected(409, "conflict", `Edit conflict at change ${change}`, {+ change,+ cell: id === undefined ? null : (current.cells.get(id) ?? null),+ document: current.revision,+ });++ for (const [index, change] of changes.entries()) {+ switch (change.kind) {+ case "put_cell": {+ const { id } = change.cell;+ if (change.base_etag === null) {+ if (current.cells.has(id) || cells.has(id)) {+ return conflict(index, id);+ }+ if (change.after !== undefined && change.before !== undefined) {+ return rejected(+ 400,+ "invalid-request",+ "A cell cannot name both before and after",+ );+ }+ const anchor = change.after ?? change.before;+ if (anchor !== undefined && !order.includes(anchor)) {+ return rejected(+ 400,+ "invalid-request",+ "The placement anchor does not exist",+ );+ }+ const position =+ anchor === undefined+ ? order.length+ : order.indexOf(anchor) + (change.after === undefined ? 0 : 1);+ order.splice(position, 0, id);+ } else if (!cells.has(id) || !matches(id, change.base_etag)) {+ return conflict(index, id);+ }+ cells.set(+ id,+ record(change.cell, current.revision.notebook_id, version),+ );+ touched.add(id);+ break;+ }+ case "delete_cell":+ if (!cells.has(change.id) || !matches(change.id, change.base_etag)) {+ return conflict(index, change.id);+ }+ cells.delete(change.id);+ order = order.filter((id) => id !== change.id);+ touched.add(change.id);+ break;+ case "set_order":+ if (+ change.base_etag !== "*" &&+ change.base_etag !== current.revision.order_etag+ ) {+ return conflict(index);+ }+ if (+ change.order.length !== cells.size ||+ new Set(change.order).size !== cells.size ||+ change.order.some((id) => !cells.has(id))+ ) {+ return rejected(+ 400,+ "invalid-request",+ "Order must name every cell exactly once",+ );+ }+ order = [...change.order];+ break;+ }+ }++ for (const [id, cell] of cells) {+ const previous = current.cells.get(id);+ if (previous?.etag === cell.etag) {+ cells.set(id, previous);+ }+ }+ const orderEtag = hash(JSON.stringify(order));+ const etag = hash(+ [+ orderEtag,+ current.revision.app_config_etag,+ ...order.map((id) => cells.get(id)!.etag),+ ].join("\n"),+ );+ const changed = etag !== current.revision.etag;+ if (changed) {+ current = {+ revision: {+ ...current.revision,+ order,+ order_etag: orderEtag,+ etag,+ version,+ },+ cells,+ };+ }+ const versions: Protocol.EditResponseOutput["cells"] = {};+ for (const id of touched) {+ const cell = current.cells.get(id);+ versions[id] =+ cell === undefined+ ? null+ : {+ etag: cell.etag,+ code_hash: cell.code_hash,+ version: cell.version,+ };+ }+ return {+ result: {+ ok: true,+ status: 200,+ data: { document: current.revision, cells: versions },+ },+ ...(changed ? { update: current } : {}),+ };+ }++ return {+ document: () => current,+ apply,+ process(request: EditRequest): Outcome {+ const fingerprint = JSON.stringify([request.notebookId, request.changes]);+ const receipt = receipts.get(request.idempotencyKey);+ if (receipt !== undefined && Date.now() < receipt.expiresAt) {+ return receipt.fingerprint === fingerprint+ ? { result: receipt.result }+ : rejected(+ 409,+ "conflict",+ "Idempotency key was used for another request",+ );+ }+ const outcome =+ request.notebookId === current.revision.notebook_id+ ? apply(request.changes)+ : rejected(404, "not-found", "Notebook does not exist");+ receipts.set(request.idempotencyKey, {+ fingerprint,+ result: outcome.result,+ expiresAt: Date.now() + 300_000,+ });+ return outcome;+ },+ };+}diff --git a/frontend/src/core/document/__tests__/test-notebook.ts b/frontend/src/core/document/__tests__/test-notebook.tsnew file mode 100644index 0000000000..65600dc951--- /dev/null+++ b/frontend/src/core/document/__tests__/test-notebook.ts@@ -0,0 +1,139 @@+/* Copyright 2026 Marimo. All rights reserved. */++import type { Result } from "@marimo-team/client";+import type * as Protocol from "@marimo-team/client/protocol";+import { atom, type createStore } from "jotai/vanilla";+import { vi } from "vitest";+import { Deferred } from "@/utils/Deferred";+import { invariant } from "@/utils/invariant";+import type { Document } from "../../host/resources/document";+import type { DocumentHost } from "../model";+import { createTestHost, type EditRequest } from "./test-host";++export interface PendingRequest extends EditRequest {+ readonly signal: AbortSignal;+ process(): void;+ deliverResponse(): void;+ loseResponse(): void;+}++export function createTestNotebook(+ store: ReturnType<typeof createStore>,+ initial: Document,+) {+ const host = createTestHost(initial);+ const source = atom<Document | null>(initial);+ const requests: PendingRequest[] = [];+ const waiting: Deferred<PendingRequest>[] = [];+ const documents: Document[] = [];+ function apply(changes: readonly Protocol.Change[]) {+ const { result, update } = host.apply(changes);+ invariant(result.ok, "Another writer's edit was rejected");+ if (update !== undefined) {+ documents.push(update);+ }+ }+ const edit = vi.fn<DocumentHost["edit"]>((notebookId, changes, options) => {+ options.signal.throwIfAborted();+ const reply = new Deferred<Result<Protocol.EditResponseOutput>>();+ let outcome: Result<Protocol.EditResponseOutput> | undefined;+ const abort = () => reply.reject(options.signal.reason);+ const finish = () => options.signal.removeEventListener("abort", abort);+ options.signal.addEventListener("abort", abort, { once: true });+ void reply.promise.then(finish, finish);+ const request: PendingRequest = {+ notebookId,+ changes: structuredClone(changes),+ idempotencyKey: options.idempotencyKey,+ signal: options.signal,+ process() {+ invariant(outcome === undefined, "Request was already processed");+ // Cancellation of the client's wait does not roll back a server commit.+ const processed = host.process(request);+ outcome = processed.result;+ if (processed.update !== undefined) {+ documents.push(processed.update);+ }+ },+ deliverResponse() {+ invariant(+ outcome !== undefined,+ "Process the request before delivering its response",+ );+ reply.resolve(outcome);+ },+ loseResponse() {+ reply.reject(new Error("Connection lost"));+ },+ };+ const next = waiting.shift();+ if (next === undefined) {+ requests.push(request);+ } else {+ next.resolve(request);+ }+ return reply.promise;+ });+ const notebook = { documentAtom: source, edit } satisfies DocumentHost;+ return {+ notebook,+ control: {+ document: host.document,+ nextRequest(): Promise<PendingRequest> {+ const next = requests.shift();+ if (next !== undefined) {+ return Promise.resolve(next);+ }+ const deferred = new Deferred<PendingRequest>();+ waiting.push(deferred);+ return deferred.promise;+ },+ changeCell(+ id: Protocol.CellId,+ patch: Partial<Omit<Protocol.CellInput, "id">>,+ ) {+ const cell = host.document().cells.get(id);+ invariant(+ cell !== undefined && cell.code !== null,+ `No host source for cell ${id}`,+ );+ apply([+ {+ kind: "put_cell",+ base_etag: cell.etag,+ cell: {+ ...cell,+ code: cell.code,+ ...patch,+ config: { ...cell.config, ...patch.config },+ },+ },+ ]);+ },+ createCell(cell: Protocol.CellInput) {+ apply([{ kind: "put_cell", base_etag: null, cell }]);+ },+ deleteCell(id: Protocol.CellId) {+ const cell = host.document().cells.get(id);+ invariant(cell !== undefined, `No host cell ${id}`);+ apply([{ kind: "delete_cell", id, base_etag: cell.etag }]);+ },+ deliverDocument() {+ const next = documents.shift();+ invariant(+ next !== undefined,+ "No document update is waiting for delivery",+ );+ store.set(source, next);+ },+ reset() {+ documents.length = 0;+ store.set(source, null);+ },+ deliverSnapshot() {+ documents.length = 0;+ store.set(source, host.document());+ },+ },+ };+}diff --git a/frontend/src/core/document/__tests__/user.ts b/frontend/src/core/document/__tests__/user.tsnew file mode 100644index 0000000000..91d6279aa0--- /dev/null+++ b/frontend/src/core/document/__tests__/user.ts@@ -0,0 +1,61 @@+/* Copyright 2026 Marimo. All rights reserved. */++import type * as Protocol from "@marimo-team/client/protocol";+import type { createStore } from "jotai/vanilla";+import type { DocumentModel } from "../model";++/** Translate user actions and observations without keeping any expected state. */+export function createUser(+ store: ReturnType<typeof createStore>,+ model: DocumentModel,+) {+ function observe(promise: Promise<Protocol.Document>) {+ // A failed assertion may end a scenario before it awaits sync; teardown+ // should not obscure that failure with an unhandled abort rejection.+ void promise.catch(() => undefined);+ return promise;+ }+ return {+ changeCode(id: Protocol.CellId, code: string) {+ store.set(model.editAtom, (tx) => tx.setCode(id, code));+ },+ changeCells(+ changes: Record<Protocol.CellId, Partial<Omit<Protocol.CellInput, "id">>>,+ ) {+ store.set(model.editAtom, (tx) => {+ for (const [id, patch] of Object.entries(changes)) {+ if (patch.code !== undefined) {+ tx.setCode(id, patch.code);+ }+ if (patch.name !== undefined) {+ tx.setName(id, patch.name);+ }+ if (patch.config !== undefined) {+ tx.updateConfig(id, patch.config);+ }+ }+ });+ },+ createCell(cell: Protocol.CellInput) {+ store.set(model.editAtom, (tx) => tx.createCell(cell));+ },+ deleteCell(id: Protocol.CellId) {+ store.set(model.editAtom, (tx) => tx.deleteCell(id));+ },+ cell(id: Protocol.CellId) {+ const cell = store.get(model.cellAtom(id));+ return cell === undefined+ ? undefined+ : {+ id: cell.id,+ code: cell.code,+ name: cell.name,+ config: cell.config,+ };+ },+ order: () => store.get(model.orderAtom),+ status: () => store.get(model.syncStateAtom),+ sync: () => observe(model.flush()),+ retry: () => observe(model.retry()),+ };+}