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.

Send document edits through the confirming backend (#11511)

Trevor Manz7b6ff9f2d95e
diff --git a/frontend/src/core/document/__tests__/codemirror.test.ts b/frontend/src/core/document/__tests__/codemirror.test.ts
index 12b418c36e..8fa9cc6453 100644
--- a/frontend/src/core/document/__tests__/codemirror.test.ts
+++ b/frontend/src/core/document/__tests__/codemirror.test.ts
@@ -24,6 +24,7 @@ import { SCHEMA_CACHE } from "../../codemirror/language/languages/sql/completion
import type { Document } from "../../host/resources/document";
import { cellCodeBinding } from "../codemirror";
import { createDocumentModel } from "../model";
+import { fakeBackend } from "../../host/__tests__/fixtures";
import { cell, document, withCells } from "./fixtures";
const views: EditorView[] = [];
@@ -87,7 +88,8 @@ function setup({
lifetimes.push(controller);
const model = createDocumentModel({
store,
- notebook: { documentAtom: source, edit: () => new Promise(() => {}) },
+ documentAtom: source,
+ backendAtom: atom(fakeBackend({ edit: () => new Promise(() => {}) })),
signal: controller.signal,
});
const editor = (text = doc) => {
diff --git a/frontend/src/core/document/__tests__/hooks.test.tsx b/frontend/src/core/document/__tests__/hooks.test.tsx
index d61ae784eb..339fa8cbfe 100644
--- a/frontend/src/core/document/__tests__/hooks.test.tsx
+++ b/frontend/src/core/document/__tests__/hooks.test.tsx
@@ -15,11 +15,10 @@ import {
useCellOrder,
useDocumentEdit,
useDocumentSync,
- type DocumentHost,
} from "..";
import { cell, CONFIG, document, withCells } from "./fixtures";
+import { type FakeEdit, fakeBackend } from "../../host/__tests__/fixtures";
-type HostEdit = DocumentHost["edit"];
const lifetimes: AbortController[] = [];
afterEach(() => {
@@ -28,7 +27,7 @@ afterEach(() => {
function setup(
initial: Document | null = document(),
- edit: HostEdit = () => new Promise(() => {}),
+ edit: FakeEdit = () => new Promise(() => {}),
) {
const store = createStore();
const source = atom(initial);
@@ -38,7 +37,8 @@ function setup(
lifetimes.push(controller);
const model = createDocumentModel({
store,
- notebook: { documentAtom: source, edit },
+ documentAtom: source,
+ backendAtom: atom(fakeBackend({ edit })),
signal: controller.signal,
});
const wrapper = ({ children }: PropsWithChildren) => (
@@ -53,14 +53,14 @@ describe("document hooks", () => {
it("flushes edits through the model and aborts work when the session ends", async () => {
const accepted = withCells(document(), { c1: cell("c1", "local") });
const edit = vi
- .fn<HostEdit>()
+ .fn<FakeEdit>()
.mockResolvedValueOnce({
ok: true,
status: 200,
data: { document: accepted.revision, cells: {} },
})
.mockImplementation(
- () => new Deferred<Awaited<ReturnType<HostEdit>>>().promise,
+ () => new Deferred<Awaited<ReturnType<FakeEdit>>>().promise,
);
const { store, source, wrapper, controller } = setup(document(), edit);
const { result, unmount } = renderHook(
@@ -98,7 +98,7 @@ describe("document hooks", () => {
await rejected;
});
expect(edit).toHaveBeenCalledTimes(2);
- expect(edit.mock.calls[1][2].signal.aborted).toBe(true);
+ expect(edit.mock.calls[1][2]?.signal?.aborted).toBe(true);
});
it("publishes compound edits atomically without changing host records", () => {
diff --git a/frontend/src/core/document/__tests__/model.test.ts b/frontend/src/core/document/__tests__/model.test.ts
index 0d18e187f3..54a68fe918 100644
--- a/frontend/src/core/document/__tests__/model.test.ts
+++ b/frontend/src/core/document/__tests__/model.test.ts
@@ -5,8 +5,10 @@ import type * as Protocol from "@marimo-team/client/protocol";
import { atom, createStore } from "jotai/vanilla";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { Deferred } from "@/utils/Deferred";
+import type { NotebookBackend } from "../../host/backend";
import type { Document } from "../../host/resources/document";
-import { createDocumentModel, type DocumentHost } from "../model";
+import { createDocumentModel } from "../model";
+import { type FakeEdit, fakeBackend } from "../../host/__tests__/fixtures";
import { cell, document, withCells } from "./fixtures";
function response(confirmed: Document): Result<Protocol.EditResponseOutput> {
@@ -30,11 +32,11 @@ async function expectAbort(promise: Promise<unknown>, reason: Error) {
interface SentEdit {
notebookId: Protocol.NotebookId;
changes: readonly Protocol.Change[];
- idempotencyKey: string;
- signal: AbortSignal;
+ idempotencyKey?: string;
+ signal?: AbortSignal;
}
-function setup() {
+function setup({ connected = true } = {}) {
const store = createStore();
const source = atom<Document | null>(document());
const unmounted = vi.fn();
@@ -45,21 +47,24 @@ function setup() {
replies.push(reply);
return reply.promise;
});
- const host: DocumentHost = {
- documentAtom: source,
+ const backend = fakeBackend({
edit: (notebookId, changes, options) =>
sent({ notebookId, changes, ...options }),
- };
+ });
+ const backendAtom = atom<NotebookBackend | null>(connected ? backend : null);
const controller = new AbortController();
lifetimes.push(controller);
const model = createDocumentModel({
store,
- notebook: host,
+ documentAtom: source,
+ backendAtom,
signal: controller.signal,
});
return {
store,
source,
+ backend,
+ backendAtom,
model,
sent,
replies,
@@ -88,11 +93,12 @@ describe("document synchronization", () => {
const controller = new AbortController();
const reason = new Error("Session ended");
controller.abort(reason);
- const edit = vi.fn<DocumentHost["edit"]>();
+ const edit = vi.fn<FakeEdit>();
expect(() =>
createDocumentModel({
store,
- notebook: { documentAtom: source, edit },
+ documentAtom: source,
+ backendAtom: atom(fakeBackend({ edit })),
signal: controller.signal,
}),
).toThrow(reason);
@@ -152,7 +158,34 @@ describe("document synchronization", () => {
await vi.advanceTimersByTimeAsync(0);
store.set(source, document("n2"));
await rejected;
- expect(sent.mock.calls[0][0].signal.aborted).toBe(true);
+ expect(sent.mock.calls[0][0].signal?.aborted).toBe(true);
expect(status()).toMatchObject({ status: "error", retryable: false });
});
+
+ it("aborts an in-flight edit when the backend changes and never sends it to the new one", async () => {
+ const { store, backendAtom, sent, edit, model } = setup();
+ edit("local");
+ const rejected = expectFailure(model.flush(), "notebook changed");
+ await vi.advanceTimersByTimeAsync(0);
+ const other = vi.fn<FakeEdit>();
+ store.set(backendAtom, fakeBackend({ edit: other }));
+ await rejected;
+ expect(sent).toHaveBeenCalledOnce();
+ expect(sent.mock.calls[0][0].signal?.aborted).toBe(true);
+ expect(other).not.toHaveBeenCalled();
+ });
+
+ it("keeps edits as drafts until a backend is connected", async () => {
+ const { store, backend, backendAtom, sent, edit, status, value } = setup({
+ connected: false,
+ });
+ edit("local");
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(status()).toEqual({ status: "unavailable" });
+ expect(value()?.code).toBe("local");
+
+ store.set(backendAtom, backend);
+ await vi.advanceTimersByTimeAsync(400);
+ expect(sent).toHaveBeenCalledOnce();
+ });
});
diff --git a/frontend/src/core/document/__tests__/scenario-fixture.ts b/frontend/src/core/document/__tests__/scenario-fixture.ts
index 2ece5a7ca4..ac4d6602ac 100644
--- a/frontend/src/core/document/__tests__/scenario-fixture.ts
+++ b/frontend/src/core/document/__tests__/scenario-fixture.ts
@@ -13,7 +13,8 @@ function createSession(initial: Document, controller: AbortController) {
const { notebook, control } = createTestNotebook(store, initial);
const model = createDocumentModel({
store,
- notebook,
+ documentAtom: notebook.documentAtom,
+ backendAtom: notebook.backendAtom,
signal: controller.signal,
});
return {
diff --git a/frontend/src/core/document/__tests__/test-notebook.ts b/frontend/src/core/document/__tests__/test-notebook.ts
index 65600dc951..c9829ef65f 100644
--- a/frontend/src/core/document/__tests__/test-notebook.ts
+++ b/frontend/src/core/document/__tests__/test-notebook.ts
@@ -6,8 +6,8 @@ import { atom, type createStore } from "jotai/vanilla";
import { vi } from "vitest";
import { Deferred } from "@/utils/Deferred";
import { invariant } from "@/utils/invariant";
+import { type FakeEdit, fakeBackend } from "../../host/__tests__/fixtures";
import type { Document } from "../../host/resources/document";
-import type { DocumentHost } from "../model";
import { createTestHost, type EditRequest } from "./test-host";
export interface PendingRequest extends EditRequest {
@@ -33,19 +33,25 @@ export function createTestNotebook(
documents.push(update);
}
}
- const edit = vi.fn<DocumentHost["edit"]>((notebookId, changes, options) => {
- options.signal.throwIfAborted();
+ const edit = vi.fn<FakeEdit>((notebookId, changes, options) => {
+ const signal = options?.signal;
+ const idempotencyKey = options?.idempotencyKey;
+ invariant(
+ signal !== undefined && idempotencyKey !== undefined,
+ "The test host answers edits that carry a key and a signal",
+ );
+ 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 });
+ const abort = () => reply.reject(signal.reason);
+ const finish = () => signal.removeEventListener("abort", abort);
+ 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,
+ idempotencyKey,
+ signal,
process() {
invariant(outcome === undefined, "Request was already processed");
// Cancellation of the client's wait does not roll back a server commit.
@@ -74,7 +80,11 @@ export function createTestNotebook(
}
return reply.promise;
});
- const notebook = { documentAtom: source, edit } satisfies DocumentHost;
+ const notebook = {
+ documentAtom: source,
+ backendAtom: atom(fakeBackend({ edit })),
+ edit,
+ };
return {
notebook,
control: {
diff --git a/frontend/src/core/document/index.ts b/frontend/src/core/document/index.ts
index b2f2f35808..d2be31de57 100644
--- a/frontend/src/core/document/index.ts
+++ b/frontend/src/core/document/index.ts
@@ -14,7 +14,6 @@ export { createDocumentModel } from "./model";
export type {
DocumentEdit,
DocumentEditor,
- DocumentHost,
DocumentModel,
DocumentSyncStatus,
EditableCell,
diff --git a/frontend/src/core/document/model.ts b/frontend/src/core/document/model.ts
index e418033ca8..70b0199d14 100644
--- a/frontend/src/core/document/model.ts
+++ b/frontend/src/core/document/model.ts
@@ -2,16 +2,14 @@
import type * as Protocol from "@marimo-team/client/protocol";
import type { Atom, createStore } from "jotai/vanilla";
+import type { NotebookBackend } from "../host/backend";
+import type { Document } from "../host/resources/document";
import { createDocumentState, type DocumentState } from "./state";
-import {
- createDocumentSync,
- type DocumentHost,
- type DocumentSyncStatus,
-} from "./sync";
+import { createDocumentSync, type DocumentSyncStatus } from "./sync";
export type { DocumentEdit, DocumentEditor } from "./state";
export type { EditableCell, EditableDocument } from "./draft";
-export type { DocumentHost, DocumentSyncStatus } from "./sync";
+export type { DocumentSyncStatus } from "./sync";
/** The editable document and its synchronization with the host. */
export interface DocumentModel extends Pick<
@@ -28,20 +26,26 @@ export interface DocumentModel extends Pick<
/** Create once per editing session; abort to stop editing and synchronization together. */
export function createDocumentModel({
store,
- notebook,
+ documentAtom,
+ backendAtom,
signal,
}: {
store: ReturnType<typeof createStore>;
- notebook: DocumentHost;
+ /** The document the host last confirmed. */
+ documentAtom: Atom<Document | null>;
+ /** The backend that confirmed it, whose commands reach its host. */
+ backendAtom: Atom<NotebookBackend | null>;
signal: AbortSignal;
}): DocumentModel {
signal.throwIfAborted();
- const state = createDocumentState({
+ const state = createDocumentState({ store, source: documentAtom, signal });
+ const sync = createDocumentSync({
store,
- source: notebook.documentAtom,
+ documentAtom,
+ backendAtom,
+ state,
signal,
});
- const sync = createDocumentSync({ store, notebook, state, signal });
return {
documentAtom: state.documentAtom,
editAtom: state.editAtom,
diff --git a/frontend/src/core/document/sync.ts b/frontend/src/core/document/sync.ts
index 6a0f9dde74..3bf516879c 100644
--- a/frontend/src/core/document/sync.ts
+++ b/frontend/src/core/document/sync.ts
@@ -2,13 +2,11 @@
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 Atom, atom, type createStore } from "jotai/vanilla";
+import type { NotebookBackend } from "../host/backend";
+import type { Document } from "../host/resources/document";
import type { DocumentState, DocumentSubmission } from "./state";
-/** The notebook state and operation needed by document editing. */
-export type DocumentHost = Pick<NotebookClient, "documentAtom" | "edit">;
-
export type DocumentSyncStatus =
| {
readonly status:
@@ -27,6 +25,8 @@ export type DocumentSyncStatus =
interface Submission {
readonly submission: DocumentSubmission;
+ /** The backend that confirmed the submission's base. */
+ readonly backend: NotebookBackend;
readonly idempotencyKey: string;
readonly startedAt: number;
readonly controller: AbortController;
@@ -74,20 +74,22 @@ function delay(ms: number, signal: AbortSignal): Promise<void> {
/** Own submission scheduling; follow the existing source without opening a stream. */
export function createDocumentSync({
store,
- notebook,
+ documentAtom: source,
+ backendAtom,
state,
signal,
}: {
store: ReturnType<typeof createStore>;
- notebook: DocumentHost;
+ documentAtom: Atom<Document | null>;
+ backendAtom: Atom<NotebookBackend | null>;
state: DocumentState;
signal: AbortSignal;
}) {
signal.throwIfAborted();
- const source = notebook.documentAtom;
const statusAtom = atom<DocumentSyncStatus>({ status: "idle" });
const observed = atom((get) => ({
document: get(source),
+ backend: get(backendAtom),
pending: get(state.pendingAtom),
changes: get(state.changesAtom),
}));
@@ -117,8 +119,9 @@ export function createDocumentSync({
const current = store.get(source);
if (
active &&
- current &&
- current.revision.notebook_id !== active.submission.notebookId
+ (store.get(backendAtom) !== active.backend ||
+ (current &&
+ current.revision.notebook_id !== active.submission.notebookId))
) {
active.controller.abort(
new Error("The notebook changed during synchronization"),
@@ -129,7 +132,7 @@ export function createDocumentSync({
}
clearTimer();
const changes = store.get(state.changesAtom);
- if (changes === null) {
+ if (changes === null || store.get(backendAtom) === null) {
store.set(statusAtom, { status: "unavailable" });
} else if (changes.length === 0) {
// Release unsent reversals instead of keeping an invisible override.
@@ -170,14 +173,12 @@ export function createDocumentSync({
signal.throwIfAborted();
request.controller.signal.throwIfAborted();
result = await abortable(
- notebook.edit(
- request.submission.notebookId,
- request.submission.changes,
- {
+ request.backend
+ .notebook(request.submission.notebookId)
+ .edit(request.submission.changes, {
idempotencyKey: request.idempotencyKey,
signal: controller.signal,
- },
- ),
+ }),
controller.signal,
);
} catch (error) {
@@ -248,7 +249,12 @@ export function createDocumentSync({
throw new Error("The notebook changed during synchronization");
}
if (active === null) {
- if (current === null || store.get(state.changesAtom) === null) {
+ const backend = store.get(backendAtom);
+ if (
+ current === null ||
+ backend === null ||
+ store.get(state.changesAtom) === null
+ ) {
throw unavailable();
}
const submission = store.set(state.submitAtom);
@@ -257,6 +263,7 @@ export function createDocumentSync({
}
active = {
submission,
+ backend,
idempotencyKey: idempotencyKey(),
startedAt: Date.now(),
controller: new AbortController(),
diff --git a/frontend/src/core/host/__tests__/notebook-client.test.ts b/frontend/src/core/host/__tests__/notebook-client.test.ts
index d9ce5441f7..c54c2977f3 100644
--- a/frontend/src/core/host/__tests__/notebook-client.test.ts
+++ b/frontend/src/core/host/__tests__/notebook-client.test.ts
@@ -8,12 +8,7 @@ import { Deferred } from "@/utils/Deferred";
import { ConnectionState } from "../../websocket/types";
import type { ConnectionStatus } from "../connection";
import { createNotebookClient } from "../notebook-client";
-import {
- type FakeEdit,
- fakeBackend,
- fixtureEvents,
- fixtureMessages,
-} from "./fixtures";
+import { fakeBackend, fixtureEvents, fixtureMessages } from "./fixtures";
/** One connection the fake transport opened. */
interface Attempt {
@@ -27,7 +22,7 @@ interface Attempt {
stop(status?: ConnectionStatus): void;
}
-function setup(edit = vi.fn<FakeEdit>()) {
+function setup() {
const attempts: Attempt[] = [];
const transport: NotebookTransport = ({ cursor, signal }, handlers) =>
new Promise((resolve, reject) => {
@@ -45,7 +40,7 @@ function setup(edit = vi.fn<FakeEdit>()) {
const onNotification = vi.fn();
const checkHealth = vi.fn(async () => true);
const store = createStore();
- const backend = fakeBackend({ transport, edit, checkHealth });
+ const backend = fakeBackend({ transport, checkHealth });
const client = createNotebookClient(store);
/** Follow the backend until `signal` aborts. */
const connect = (signal: AbortSignal) => {
@@ -121,60 +116,22 @@ describe("NotebookClient lifetime", () => {
});
});
- it("keeps an edit's target and request identity across a stream reset", async () => {
- const edit = vi.fn<FakeEdit>().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();
+ it("exposes the backend it follows until that connection ends", async () => {
+ const { backend, client, opened, store } = setup();
+ expect(store.get(client.backendAtom)).toBeNull();
+ const disconnect = client.connect(backend, { onNotification: vi.fn() });
+ expect(store.get(client.backendAtom)).toBe(backend);
+ const { receive, drop } = 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);
- });
+ drop();
+ expect(store.get(client.backendAtom)).toBe(backend);
- it("rejects aborted edits and reports edits before connecting", 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);
+ const other = fakeBackend();
+ onTestFinished(client.connect(other, { onNotification: vi.fn() }));
+ expect(store.get(client.backendAtom)).toBe(other);
+ disconnect();
+ expect(store.get(client.backendAtom)).toBe(other);
});
it("exposes identity and capabilities only after the notebook is ready", async () => {
diff --git a/frontend/src/core/host/__tests__/wasm.test.ts b/frontend/src/core/host/__tests__/wasm.test.ts
index 43c619a933..2b9554335f 100644
--- a/frontend/src/core/host/__tests__/wasm.test.ts
+++ b/frontend/src/core/host/__tests__/wasm.test.ts
@@ -99,6 +99,14 @@ describe("WASM notebook backend", () => {
).rejects.toBeInstanceOf(StreamStopped);
});
+ it("refuses commands for any notebook but the worker's", () => {
+ const { bridge } = worker();
+ expect(() => createWasmNotebookBackend(bridge).notebook("n2")).toThrow(
+ "serves notebook n1, not n2",
+ );
+ expect(bridge.call).not.toHaveBeenCalled();
+ });
+
it("sends edits as calls with the retry key and validates replies", async () => {
const { bridge, reply } = worker();
const backend = createWasmNotebookBackend(bridge);
diff --git a/frontend/src/core/host/notebook-client.ts b/frontend/src/core/host/notebook-client.ts
index 30b7ff2894..7adcef8436 100644
--- a/frontend/src/core/host/notebook-client.ts
+++ b/frontend/src/core/host/notebook-client.ts
@@ -5,16 +5,9 @@ import {
createNotebookReducer,
type NotebookEvent,
NotebookEvents,
- type Result,
StreamStopped,
} from "@marimo-team/client";
-import type {
- Attachment,
- Change,
- EditResponseOutput,
- NotebookId,
- NotebookOutput,
-} from "@marimo-team/client/protocol";
+import type { Attachment, NotebookOutput } from "@marimo-team/client/protocol";
import { type Atom, atom, type createStore } from "jotai/vanilla";
import { z } from "zod";
import type { NotebookBackend } from "./backend";
@@ -48,12 +41,13 @@ 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>>;
+ /**
+ * The backend this client follows, or null while not connected.
+ *
+ * Its commands reach the host that confirmed `documentAtom`. A temporary
+ * disconnection keeps it. Connecting again or disconnecting replaces it.
+ */
+ readonly backendAtom: Atom<NotebookBackend | null>;
/** Live attachments, empty until the stream is ready or while disconnected. */
readonly attachmentsAtom: Atom<readonly Attachment[]>;
/**
@@ -133,7 +127,7 @@ export function createNotebookClient(
? get(streamAtom).resources.attachments
: attachments.initial,
);
- let backend: NotebookBackend | undefined;
+ const backendAtom = atom<NotebookBackend | null>(null);
/** The connection this client follows. Connecting again ends it. */
let current: { end(): void; reconnect(): Promise<void> } | undefined;
@@ -152,25 +146,7 @@ export function createNotebookClient(
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 (backend === 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 backend.notebook(notebookId).edit(changes, options);
- },
+ backendAtom,
attachmentsAtom,
connect,
reconnect: async () => current?.reconnect(),
@@ -184,7 +160,7 @@ export function createNotebookClient(
const lifetime = new AbortController();
const { signal } = lifetime;
const checkHealth = connected.checkHealth ?? (async () => true);
- backend = connected;
+ store.set(backendAtom, connected);
const { transport } = connected;
let events: NotebookEvents<(typeof TYPES)[number]> | undefined;
let checkingHealth = false;
@@ -294,7 +270,7 @@ export function createNotebookClient(
lifetime.abort();
if (current === connection) {
current = undefined;
- backend = undefined;
+ store.set(backendAtom, null);
}
clear({ state: ConnectionState.NOT_STARTED });
},
diff --git a/frontend/src/core/host/wasm.ts b/frontend/src/core/host/wasm.ts
index 5458321c4e..4b42abede4 100644
--- a/frontend/src/core/host/wasm.ts
+++ b/frontend/src/core/host/wasm.ts
@@ -88,6 +88,13 @@ export function createWasmNotebookBackend(
signal.removeEventListener("abort", abort);
}
},
- notebook: () => client,
+ notebook: (id) => {
+ if (id !== bridge.notebookId) {
+ throw new Error(
+ `The worker serves notebook ${bridge.notebookId}, not ${id}`,
+ );
+ }
+ return client;
+ },
};
}