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.

Serve notebook edits in the WASM worker (#11488)

Trevor Manz356a2664a9fe
diff --git a/frontend/src/core/host/__tests__/wasm.test.ts b/frontend/src/core/host/__tests__/wasm.test.ts
new file mode 100644
index 0000000000..2bbbcb0455
--- /dev/null
+++ b/frontend/src/core/host/__tests__/wasm.test.ts
@@ -0,0 +1,152 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { NotebookEvents, StreamStopped } from "@marimo-team/client";
+import { afterEach, assert, describe, expect, it, vi } from "vitest";
+import { Deferred } from "@/utils/Deferred";
+import { createWasmNotebookBackend, type WasmNotebookBridge } from "../wasm";
+import { fixtureEvents } from "./fixtures";
+
+const streams: NotebookEvents[] = [];
+afterEach(async () => {
+ for (const stream of streams.splice(0)) {
+ stream.close();
+ await stream.closed.catch(() => undefined);
+ }
+});
+
+function worker() {
+ const frames = fixtureEvents("notebook-events.sse");
+ const document = frames.find((event) => event.event === "document")?.data
+ .document;
+ assert(document);
+ const listeners = new Set<(event: unknown) => void>();
+ const reply = { ok: true, status: 200, data: { document, cells: {} } };
+ const wire = { status: 200, body: reply.data };
+ const bridge = {
+ notebookId: "n1",
+ subscribe: vi.fn(
+ async (_cursor: string | null, emit: (event: unknown) => void) => {
+ listeners.add(emit);
+ frames.forEach(emit);
+ return () => {
+ listeners.delete(emit);
+ };
+ },
+ ),
+ call: vi.fn<WasmNotebookBridge["call"]>().mockResolvedValue(wire),
+ };
+ return { bridge, listeners, reply, wire };
+}
+
+async function follow(bridge: WasmNotebookBridge) {
+ const stream = new NotebookEvents(
+ createWasmNotebookBackend(bridge).transport,
+ );
+ streams.push(stream);
+ const ready = new Deferred<void>();
+ stream.subscribe((event) => {
+ if (event.event === "ready") {
+ ready.resolve();
+ }
+ }, ready.reject);
+ await ready.promise;
+ return stream;
+}
+
+describe("WASM notebook backend", () => {
+ it("follows independent readers and releases each subscription on close", async () => {
+ const { bridge, listeners } = worker();
+ const first = await follow(bridge);
+ const second = await follow(bridge);
+ expect(listeners.size).toBe(2);
+ expect(second.status).toBe("connected");
+ first.close();
+ await first.closed;
+ expect(listeners.size).toBe(1);
+ second.close();
+ await second.closed;
+ expect(listeners.size).toBe(0);
+ });
+
+ it("closes during startup and releases the late subscription", async () => {
+ const { bridge } = worker();
+ const pending = new Deferred<() => void>();
+ bridge.subscribe.mockReturnValue(pending.promise);
+ const controller = new AbortController();
+ const done = createWasmNotebookBackend(bridge).transport(
+ { cursor: "previous-4", signal: controller.signal },
+ { open: vi.fn(), message: vi.fn() },
+ );
+ expect(bridge.subscribe).toHaveBeenCalledWith(
+ "previous-4",
+ expect.any(Function),
+ );
+ controller.abort();
+ await done;
+ const close = vi.fn();
+ pending.resolve(close);
+ await vi.waitFor(() => expect(close).toHaveBeenCalledOnce());
+ });
+
+ it("stops on worker initialization failure", async () => {
+ const { bridge } = worker();
+ bridge.subscribe.mockRejectedValue(new Error("Initialization failed"));
+ await expect(
+ createWasmNotebookBackend(bridge).transport(
+ { cursor: null, signal: new AbortController().signal },
+ { open: vi.fn(), message: vi.fn() },
+ ),
+ ).rejects.toBeInstanceOf(StreamStopped);
+ });
+
+ it("sends edits as calls with the retry key and validates replies", async () => {
+ const { bridge, reply } = worker();
+ const backend = createWasmNotebookBackend(bridge);
+ expect(await backend.client.edit([], { idempotencyKey: "edit-7" })).toEqual(
+ reply,
+ );
+ expect(bridge.call).toHaveBeenCalledWith({
+ operation: "notebook.edit",
+ params: { notebook_id: "n1" },
+ headers: { "idempotency-key": "edit-7" },
+ body: { changes: [] },
+ });
+ const problem = {
+ type: "tag:marimo.io,2026:host/forbidden",
+ title: "Forbidden",
+ status: 403,
+ };
+ bridge.call.mockResolvedValue({ status: 403, body: problem });
+ expect(await backend.client.edit([])).toEqual({
+ ok: false,
+ status: 403,
+ problem,
+ });
+ bridge.call.mockResolvedValue({ status: 200, body: {} });
+ await expect(backend.client.edit([])).rejects.toThrow(/Invalid input/);
+ });
+
+ it("cancels waiting for an accepted edit and permits retry with the same key", async () => {
+ const { bridge, reply, wire } = worker();
+ const pending = new Deferred<unknown>();
+ bridge.call.mockReturnValue(pending.promise);
+ const backend = createWasmNotebookBackend(bridge);
+ const controller = new AbortController();
+ const editing = backend.client.edit([], {
+ signal: controller.signal,
+ idempotencyKey: "edit-8",
+ });
+ await vi.waitFor(() => expect(bridge.call).toHaveBeenCalledOnce());
+ controller.abort();
+ await expect(editing).rejects.toBe(controller.signal.reason);
+ pending.resolve(wire);
+ expect(await backend.client.edit([], { idempotencyKey: "edit-8" })).toEqual(
+ reply,
+ );
+ expect(bridge.call.mock.calls[0]).toEqual(bridge.call.mock.calls[1]);
+ await expect(
+ backend.client.edit([], { signal: controller.signal }),
+ ).rejects.toBe(controller.signal.reason);
+ expect(bridge.call).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/frontend/src/core/host/wasm.ts b/frontend/src/core/host/wasm.ts
new file mode 100644
index 0000000000..2e5bda6d59
--- /dev/null
+++ b/frontend/src/core/host/wasm.ts
@@ -0,0 +1,92 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import {
+ NotebookClient,
+ StreamStopped,
+ type unstable_NotebookCall,
+} from "@marimo-team/client";
+import type { NotebookBackend } from "./backend";
+
+/** The worker owns the notebook; this interface only carries commands and events. */
+export interface WasmNotebookBridge {
+ readonly notebookId: string;
+ subscribe(
+ cursor: string | null,
+ emit: (event: unknown) => void,
+ ): Promise<() => void>;
+ /** Deliver a call to the worker and resolve with its status and body. */
+ call(call: unstable_NotebookCall): Promise<unknown>;
+}
+
+/** Stop waiting on cancellation; a command already sent may still commit. */
+function abortable<T>(
+ send: () => Promise<T>,
+ signal?: AbortSignal,
+): Promise<T> {
+ if (!signal) {
+ return send();
+ }
+ signal.throwIfAborted();
+ return new Promise((resolve, reject) => {
+ const abort = () => reject(signal.reason);
+ signal.addEventListener("abort", abort, { once: true });
+ send()
+ .then(resolve, reject)
+ .finally(() => signal.removeEventListener("abort", abort));
+ });
+}
+
+export function createWasmNotebookBackend(
+ bridge: WasmNotebookBridge,
+): NotebookBackend {
+ return {
+ transport: async ({ cursor, signal }, { open, message }) => {
+ if (signal.aborted) {
+ return;
+ }
+ let unsubscribe: (() => void) | undefined;
+ let finish!: () => void;
+ const closed = new Promise<void>((resolve) => {
+ finish = resolve;
+ });
+ const abort = () => {
+ unsubscribe?.();
+ finish();
+ };
+ signal.addEventListener("abort", abort, { once: true });
+ try {
+ open();
+ // Keep the pending subscription so a close during startup still releases it.
+ await abortable(
+ () =>
+ bridge
+ .subscribe(cursor, (event) => {
+ if (!signal.aborted) {
+ message(event);
+ }
+ })
+ .then((close) => {
+ unsubscribe = close;
+ if (signal.aborted) {
+ close();
+ }
+ }),
+ signal,
+ );
+ await closed;
+ } catch (error) {
+ if (!signal.aborted) {
+ unsubscribe?.();
+ throw new StreamStopped("Could not follow the WASM notebook", {
+ cause: error,
+ });
+ }
+ } finally {
+ signal.removeEventListener("abort", abort);
+ }
+ },
+ client: NotebookClient.unstable_over((call) => bridge.call(call), {
+ notebookId: bridge.notebookId,
+ }),
+ };
+}
diff --git a/frontend/src/core/wasm/bridge.ts b/frontend/src/core/wasm/bridge.ts
index 30e1e9b668..9f07fd52f9 100644
--- a/frontend/src/core/wasm/bridge.ts
+++ b/frontend/src/core/wasm/bridge.ts
@@ -11,6 +11,7 @@ import { reloadSafe } from "@/utils/reload-safe";
import { generateUUID } from "@/utils/uuid";
import { createModuleWorker } from "@/utils/worker";
import { notebookIsRunningAtom } from "../cells/cells";
+import { createWasmNotebookBackend } from "../host/wasm";
import type { ClientCommand } from "../kernel/messages";
import { getInitialAppMode } from "../mode";
import { API } from "../network/api";
@@ -67,6 +68,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
private rpc!: ReturnType<typeof getWorkerRPC<WorkerSchema>>;
private saveRpc: SaveWorker | undefined;
private pendingSessionSave: Promise<unknown> = Promise.resolve();
+ private notebookConsumers = new Map<string, (event: unknown) => void>();
private interruptBuffer?: Uint8Array;
private messageConsumer:
| ((message: MessageEvent<string>) => void)
@@ -117,6 +119,10 @@ export class PyodideBridge implements RunRequests, EditRequests {
this.rpc = getWorkerRPC<WorkerSchema>(worker);
this.rpc.send.bootstrap(runtimeConfig);
+ this.rpc.addMessageListener("notebookEvent", ({ id, event }) => {
+ this.notebookConsumers.get(id)?.(JSON.parse(event));
+ });
+
// Listeners
this.rpc.addMessageListener("ready", () => {
this.startSession();
@@ -213,6 +219,36 @@ export class PyodideBridge implements RunRequests, EditRequests {
this.rpc.proxy.send.consumerReady({});
}
+ public async createNotebookBackend() {
+ await this.initialized.promise;
+ const { id } = await this.rpc.proxy.request.notebookInfo();
+ return createWasmNotebookBackend({
+ notebookId: id,
+ subscribe: async (cursor, emit) => {
+ await this.initialized.promise;
+ const id = generateUUID();
+ this.notebookConsumers.set(id, emit);
+ const close = () => {
+ this.notebookConsumers.delete(id);
+ void this.rpc.proxy.request
+ .notebookUnsubscribe(id)
+ .catch(Logger.error);
+ };
+ try {
+ await this.rpc.proxy.request.notebookSubscribe({ id, cursor });
+ return close;
+ } catch (error) {
+ close();
+ throw error;
+ }
+ },
+ call: async (call) => {
+ await this.initialized.promise;
+ return this.rpc.proxy.request.notebookCall(call);
+ },
+ });
+ }
+
public sendRename: EditRequests["sendRename"] = async ({ filename }) => {
if (filename === null) {
return null;
diff --git a/frontend/src/core/wasm/worker/bootstrap.ts b/frontend/src/core/wasm/worker/bootstrap.ts
index 1cc9707338..448a8424aa 100644
--- a/frontend/src/core/wasm/worker/bootstrap.ts
+++ b/frontend/src/core/wasm/worker/bootstrap.ts
@@ -198,6 +198,7 @@ export class DefaultWasmController implements WasmController {
if task is not None:
await asyncio.gather(task, return_exceptions=True)
if bridge is not None:
+ bridge.close()
bridge.session = None
task = None
kernel_task = None
diff --git a/frontend/src/core/wasm/worker/types.ts b/frontend/src/core/wasm/worker/types.ts
index 1e36394698..4a260bc516 100644
--- a/frontend/src/core/wasm/worker/types.ts
+++ b/frontend/src/core/wasm/worker/types.ts
@@ -121,4 +121,15 @@ export type SerializedBridge = {
: RawBridge[P];
} & {
save(payload: string): Promise<void>;
+ notebook: {
+ readonly id: string;
+ subscribe(
+ id: string,
+ cursor: string | null,
+ emit: (event: string) => void,
+ ): Promise<void>;
+ unsubscribe(id: string): void;
+ call(call: string): Promise<string>;
+ destroy(): void;
+ };
};
diff --git a/frontend/src/core/wasm/worker/worker.ts b/frontend/src/core/wasm/worker/worker.ts
index 3c24800310..257a5f5310 100644
--- a/frontend/src/core/wasm/worker/worker.ts
+++ b/frontend/src/core/wasm/worker/worker.ts
@@ -1,5 +1,6 @@
/* Copyright 2026 Marimo. All rights reserved. */
+import type { unstable_NotebookCall } from "@marimo-team/client";
import type { PyodideInterface } from "pyodide";
import {
createRPC,
@@ -81,7 +82,53 @@ const bridgeReady = new Deferred<SerializedBridge>();
let started = false;
// Handle RPC requests
+const notebookSubscriptions = new Map<string, Promise<void>>();
+async function getNotebook() {
+ const bridge = await bridgeReady.promise;
+ return bridge.notebook;
+}
+
const requestHandler = createRPCRequestHandler({
+ notebookInfo: async () => {
+ const notebook = await getNotebook();
+ try {
+ return { id: notebook.id };
+ } finally {
+ notebook.destroy();
+ }
+ },
+ notebookSubscribe: (request: { id: string; cursor: string | null }) => {
+ const subscribing = (async () => {
+ const notebook = await getNotebook();
+ try {
+ await notebook.subscribe(request.id, request.cursor, (event) => {
+ rpc.send.notebookEvent({ id: request.id, event });
+ });
+ } finally {
+ notebook.destroy();
+ }
+ })();
+ notebookSubscriptions.set(request.id, subscribing);
+ return subscribing.finally(() => notebookSubscriptions.delete(request.id));
+ },
+ notebookUnsubscribe: async (id: string) => {
+ // An RPC timeout can close a reader while its subscription is still opening.
+ await notebookSubscriptions.get(id)?.catch(() => undefined);
+ const notebook = await getNotebook();
+ try {
+ notebook.unsubscribe(id);
+ } finally {
+ notebook.destroy();
+ }
+ },
+ notebookCall: async (call: unstable_NotebookCall): Promise<unknown> => {
+ const notebook = await getNotebook();
+ try {
+ return JSON.parse(await notebook.call(JSON.stringify(call)));
+ } finally {
+ notebook.destroy();
+ }
+ },
/**
* Start the session
*/
@@ -335,6 +382,7 @@ const requestHandler = createRPCRequestHandler({
export type WorkerSchema = RPCSchema<
{
messages: {
+ notebookEvent: { id: string; event: string };
// Emitted when the worker is ready
ready: {};
// Emitted when the kernel sends a message
diff --git a/marimo/_pyodide/bootstrap.py b/marimo/_pyodide/bootstrap.py
index 5b01e9ad1c..00c9c74051 100644
--- a/marimo/_pyodide/bootstrap.py
+++ b/marimo/_pyodide/bootstrap.py
@@ -51,6 +51,7 @@ def instantiate(
"""
app = session.app_manager.app
+ session.instantiated = True
execution_requests = tuple(
ExecuteCellCommand(
cell_id=cell_data.cell_id,
diff --git a/marimo/_pyodide/notebook.py b/marimo/_pyodide/notebook.py
new file mode 100644
index 0000000000..4d5ac83a7e
--- /dev/null
+++ b/marimo/_pyodide/notebook.py
@@ -0,0 +1,207 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""The worker's host document, commands, and event subscriptions."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+import msgspec
+
+from marimo._core import protocol
+from marimo._core.calls import OperationCall, dispatch
+from marimo._core.document import Document
+from marimo._core.executions import Executions
+from marimo._core.host import Host
+from marimo._core.ids import mint
+from marimo._core.notebook import Notebook
+from marimo._core.operations import Mutations, problem
+from marimo._messaging.notification import (
+ NotebookDocumentTransactionNotification,
+)
+from marimo._messaging.serde import serialize_kernel_message
+from marimo._server.host import document as documents
+from marimo._server.host.events import serialize_event
+from marimo._session.model import SessionMode
+
+if TYPE_CHECKING:
+ from collections.abc import Callable, Mapping, Sequence
+
+ from marimo._core.stream import Sink
+ from marimo._pyodide.pyodide_session import PyodideSession
+
+
+class _DocumentRuntime:
+ """Runtime operations are not exposed by the worker host yet."""
+
+ def start(self, runtime_id: protocol.RuntimeId) -> None:
+ raise NotImplementedError("Worker runtime operations are not exposed")
+
+ def stop(self, runtime_id: protocol.RuntimeId) -> None:
+ raise NotImplementedError("Worker runtime operations are not exposed")
+
+ def run(self, run_id: protocol.RunId, code: str) -> None:
+ raise NotImplementedError("Worker runtime operations are not exposed")
+
+ def run_cells(
+ self,
+ run_id: protocol.RunId,
+ document: Document,
+ cell_ids: Sequence[protocol.CellId],
+ ) -> None:
+ raise NotImplementedError("Worker runtime operations are not exposed")
+
+ def interrupt(self, run_id: protocol.RunId) -> None:
+ raise NotImplementedError("Worker runtime operations are not exposed")
+
+ def forget(self, run_id: protocol.RunId) -> None:
+ pass
+
+
+class PyodideNotebook:
+ """One session's notebook, independent of the worker RPC and React."""
+
+ def __init__(self, session: PyodideSession) -> None:
+ self._session = session
+ self._subscriptions: dict[str, Callable[[], None]] = {}
+ self._closed = False
+ self.host = Host(operations=("notebook.edit",))
+ project_id = mint(protocol.ProjectId, "p")
+ self.id = mint(protocol.NotebookId, "n")
+ self.host.update_project(
+ protocol.Project(
+ id=project_id,
+ name="WASM",
+ root=None,
+ operations=(),
+ status="indexed",
+ message=None,
+ )
+ )
+ filename = session.app_manager.filename
+ self.host.add_notebook(
+ protocol.Notebook(
+ id=self.id,
+ project_id=project_id,
+ name=Path(filename).name if filename else "Untitled",
+ path=None,
+ updated_at=None,
+ operations=("notebook.edit",)
+ if session.mode is SessionMode.EDIT
+ else (),
+ ),
+ self._initialize,
+ )
+
+ self.mutations = Mutations(self.host)
+
+ def _initialize(self, record: protocol.Notebook, sink: Sink) -> Notebook:
+ cells, config = documents.from_file_manager(self._session.app_manager)
+ document = Document(cells, config)
+ return Notebook(
+ record.id,
+ document,
+ Executions(),
+ _DocumentRuntime(),
+ sink,
+ saved_etag=document.etag,
+ )
+
+ def refresh(self, *, saved: bool = False) -> None:
+ """Observe writes through the existing session while it still owns saves."""
+ if self._closed:
+ return
+ notebook = self.host.peek_notebook(self.id)
+ if notebook is not None:
+ cells, config = documents.from_file_manager(
+ self._session.app_manager
+ )
+ notebook.replace(cells, config, saved=saved)
+
+ async def subscribe(
+ self,
+ subscription_id: str,
+ cursor: str | None,
+ emit: Callable[[str], None],
+ ) -> None:
+ if self._closed:
+ raise RuntimeError("The notebook is closed")
+ await self.host.notebook(self.id)
+ if self._closed:
+ raise RuntimeError("The notebook is closed")
+ self.refresh()
+ self.unsubscribe(subscription_id)
+ # Snapshot and subscription are established in the same event-loop turn.
+ initial = self.host.events(cursor, notebook_id=self.id)
+ self._subscriptions[subscription_id] = self.host.subscribe(
+ lambda event: emit(serialize_event(event)),
+ notebook_id=self.id,
+ )
+ try:
+ for event in initial:
+ emit(serialize_event(event))
+ except BaseException:
+ self.unsubscribe(subscription_id)
+ raise
+
+ def unsubscribe(self, subscription_id: str) -> None:
+ unsubscribe = self._subscriptions.pop(subscription_id, None)
+ if unsubscribe is not None:
+ unsubscribe()
+
+ async def call(self, raw: str) -> str:
+ """Serve an operation call and reply with its status and body."""
+ self.mutations.expire()
+ body: msgspec.Struct | None
+ try:
+ call = msgspec.json.decode(raw, type=OperationCall)
+ except msgspec.DecodeError as e:
+ failure = problem(400, "invalid-request", str(e))
+ status, body = failure.status, failure
+ else:
+ status, body = await dispatch(self.mutations, self, call)
+ return msgspec.json.encode({"status": status, "body": body}).decode()
+
+ async def edit(
+ self,
+ notebook_id: str,
+ changes: Sequence[protocol.Change],
+ *,
+ request_id: str,
+ ) -> protocol.EditResponse:
+ notebook = await self.host.notebook(notebook_id)
+ self.refresh()
+ result = notebook.edit(changes, request_id=request_id)
+ transaction, update = documents.apply_to_document(
+ self._session.app_manager.app.cell_manager.document,
+ notebook.document,
+ )
+ if transaction is not None:
+ self._session._on_message(
+ serialize_kernel_message(
+ NotebookDocumentTransactionNotification(
+ transaction=transaction
+ )
+ )
+ )
+ # Before instantiation the kernel receives the latest app cells.
+ if update is not None and self._session.instantiated:
+ self._session.put_control_request(update)
+ return result
+
+ async def save(
+ self,
+ notebook_id: str,
+ *,
+ if_match: Sequence[str] | None,
+ decisions: Mapping[str, str],
+ request_id: str,
+ ) -> protocol.EditResponse:
+ raise NotImplementedError("Worker saves are not exposed yet")
+
+ def close(self) -> None:
+ self._closed = True
+ for subscription_id in list(self._subscriptions):
+ self.unsubscribe(subscription_id)
+ self.mutations.replies.clear()
+ self.host.remove_notebook(self.id)
diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.py
index 6149de6d84..15b9c79ddd 100644
--- a/marimo/_pyodide/pyodide_session.py
+++ b/marimo/_pyodide/pyodide_session.py
@@ -88,6 +88,7 @@ if TYPE_CHECKING:
from marimo._ast.cell import CellConfig
from marimo._messaging.types import KernelMessage
+ from marimo._pyodide.notebook import PyodideNotebook
from marimo._runtime.context.types import RuntimeContext
from marimo._session.notebook.file_manager import AppFileManager
from marimo._types.ids import CellId_t
@@ -140,6 +141,7 @@ class PyodideSession:
self._queue_manager = AsyncQueueManager()
self.session_consumer = on_write
self.session_view = SessionView()
+ self.instantiated = False
self._initial_user_config = user_config
self._enqueue_control_request = make_control_enqueuer(
self._queue_manager.control_queue,
@@ -245,6 +247,19 @@ class PyodideBridge:
):
self.session = session
self.file_system = OSFileSystem()
+ self._notebook: PyodideNotebook | None = None
+
+ @property
+ def notebook(self) -> PyodideNotebook:
+ if self._notebook is None:
+ from marimo._pyodide.notebook import PyodideNotebook
+
+ self._notebook = PyodideNotebook(self.session)
+ return self._notebook
+
+ def close(self) -> None:
+ if self._notebook is not None:
+ self._notebook.close()
def put_control_request(self, request: str) -> None:
parsed = parse_command(request)
@@ -281,10 +296,14 @@ class PyodideBridge:
def save(self, request: str) -> None:
parsed = self._parse(request, SaveNotebookRequest)
self.session.app_manager.save(parsed)
+ if self._notebook is not None:
+ self._notebook.refresh(saved=True)
def save_app_config(self, request: str) -> None:
parsed = self._parse(request, SaveAppConfigurationRequest)
self.session.app_manager.save_app_config(parsed.config)
+ if self._notebook is not None:
+ self._notebook.refresh(saved=True)
def save_user_config(self, request: str) -> None:
parsed = self._parse(request, SaveUserConfigurationRequest)
diff --git a/marimo/_server/host/document.py b/marimo/_server/host/document.py
index c4ea4b4c24..205c9d36a3 100644
--- a/marimo/_server/host/document.py
+++ b/marimo/_server/host/document.py
@@ -44,6 +44,7 @@ if TYPE_CHECKING:
from collections.abc import Iterable
from marimo._core.document import Document
+ from marimo._messaging.notebook import NotebookDocument
from marimo._session.notebook import AppFileManager
from marimo._session.session import Session
@@ -122,7 +123,21 @@ def apply_to_session(session: Session, document: Document) -> None:
deletes or disables is gone before any run the deletion causes. The
app config is the session's own and is left alone.
"""
- current = session.document
+ transaction, command = apply_to_document(session.document, document)
+ if transaction is None:
+ return
+ session.notify(
+ NotebookDocumentTransactionNotification(transaction=transaction),
+ from_consumer_id=None,
+ )
+ if command is not None:
+ session.put_control_request(command, from_consumer_id=None)
+
+
+def apply_to_document(
+ current: NotebookDocument, document: Document
+) -> tuple[Transaction | None, EditCellsCommand | None]:
+ """Apply host cells to the editor document and return the kernel update."""
changes: list[DocumentChange] = []
codes: dict[CellId_t, str] = {}
configs: dict[CellId_t, dict[str, Any]] = {}
@@ -169,14 +184,11 @@ def apply_to_session(session: Session, document: Document) -> None:
if current.cell_ids != order:
changes.append(ReorderCells(cell_ids=tuple(order)))
if not changes:
- return
+ return None, None
applied = current.apply(Transaction(changes=tuple(changes), source="host"))
- session.notify(
- NotebookDocumentTransactionNotification(transaction=applied),
- from_consumer_id=None,
+ command = (
+ EditCellsCommand(codes=codes, configs=configs, delete_ids=deleted)
+ if codes or configs or deleted
+ else None
)
- if codes or configs or deleted:
- session.put_control_request(
- EditCellsCommand(codes=codes, configs=configs, delete_ids=deleted),
- from_consumer_id=None,
- )
+ return applied, command
diff --git a/packages/client/src/__tests__/notebook-client.test.ts b/packages/client/src/__tests__/notebook-client.test.ts
index 660fe124d9..c9f0ad0af4 100644
--- a/packages/client/src/__tests__/notebook-client.test.ts
+++ b/packages/client/src/__tests__/notebook-client.test.ts
@@ -4,7 +4,10 @@ import NodeFs from "node:fs";
import NodeUrl from "node:url";
import { afterEach, describe, expect, expectTypeOf, it, vi } from "vitest";
import { z } from "zod";
-import { NotebookClient } from "../notebook/client.ts";
+import {
+ NotebookClient,
+ type unstable_NotebookCall,
+} from "../notebook/client.ts";
import type { OperationsBelow } from "../request.ts";
import type * as Protocol from "../protocol.ts";
@@ -200,3 +203,107 @@ describe("NotebookClient", () => {
} as const).toExtend<Record<NotebookOperationId, keyof NotebookClient>>();
});
});
+
+/** A notebook client whose calls `reply` answers. */
+function over(reply: (call: unstable_NotebookCall) => unknown) {
+ const send = vi.fn(async (call: unstable_NotebookCall) => reply(call));
+ const notebook = NotebookClient.unstable_over(send, { notebookId: "n1" });
+ return { notebook, send };
+}
+
+describe("NotebookClient.unstable_over", () => {
+ it("sends each method as its call", async () => {
+ const response = readFixture("edit-response.json");
+ const { notebook, send } = over(() => ({ status: 200, body: response }));
+ const { changes } = readFixture("edit.json") as Protocol.EditRequest;
+
+ expect(await notebook.edit(changes)).toEqual({
+ ok: true,
+ status: 200,
+ data: response,
+ });
+ expect(send).toHaveBeenLastCalledWith({
+ operation: "notebook.edit",
+ params: { notebook_id: "n1" },
+ headers: { "idempotency-key": expect.stringMatching(/^[\da-f-]{36}$/) },
+ body: { changes },
+ });
+
+ await notebook.save({
+ ifMatch: "etag-1",
+ decisions: { environment: "keep" },
+ idempotencyKey: "retry-1",
+ });
+ expect(send).toHaveBeenLastCalledWith({
+ operation: "notebook.save",
+ params: { notebook_id: "n1" },
+ headers: { "idempotency-key": "retry-1", "if-match": "etag-1" },
+ body: { decisions: { environment: "keep" } },
+ });
+ });
+
+ it("names every path parameter and returns problems as values", async () => {
+ const problem = {
+ type: "tag:marimo.io,2026:host/not-found",
+ title: "Not found",
+ status: 404,
+ };
+ const { notebook, send } = over(() => ({ status: 404, body: problem }));
+ expect(await notebook.interrupt("r1", { idempotencyKey: "k" })).toEqual({
+ ok: false,
+ status: 404,
+ problem,
+ });
+ expect(send).toHaveBeenCalledWith({
+ operation: "runtime.interrupt",
+ params: { notebook_id: "n1", run_id: "r1" },
+ headers: { "idempotency-key": "k" },
+ body: undefined,
+ });
+ });
+
+ it("throws on replies the protocol does not describe", async () => {
+ await expect(over(() => ({})).notebook.open()).rejects.toBeInstanceOf(
+ z.ZodError,
+ );
+ await expect(
+ over(() => ({ status: 200, body: { unexpected: true } })).notebook.open(),
+ ).rejects.toBeInstanceOf(z.ZodError);
+ });
+
+ it("stops waiting on abort without sending again", async () => {
+ let answer!: (reply: unknown) => void;
+ const { notebook, send } = over(
+ () => new Promise((resolve) => (answer = resolve)),
+ );
+ const controller = new AbortController();
+ const editing = notebook.edit([], { signal: controller.signal });
+ controller.abort();
+ await expect(editing).rejects.toBe(controller.signal.reason);
+ answer({ status: 200, body: readFixture("edit-response.json") });
+ await expect(notebook.edit([], { signal: controller.signal })).rejects.toBe(
+ controller.signal.reason,
+ );
+ expect(send).toHaveBeenCalledOnce();
+ });
+
+ it("types each call from the operations table", () => {
+ expectTypeOf<unstable_NotebookCall["operation"]>().toEqualTypeOf<
+ OperationsBelow<"/notebooks/{notebook_id}">
+ >();
+ expectTypeOf<
+ unstable_NotebookCall<"runtime.interrupt">["params"]
+ >().toEqualTypeOf<{
+ readonly notebook_id: string;
+ readonly run_id: string;
+ }>();
+ expectTypeOf<unstable_NotebookCall<"notebook.save">["headers"]>().toExtend<{
+ readonly "idempotency-key": string;
+ readonly "if-match"?: string;
+ }>();
+ expectTypeOf<
+ unstable_NotebookCall<"runtime.stop">["body"]
+ >().toEqualTypeOf<undefined>();
+ expectTypeOf(over(() => ({})).notebook).not.toHaveProperty("url");
+ });
+});
diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts
index 5c891b0976..901ac17d0b 100644
--- a/packages/client/src/index.ts
+++ b/packages/client/src/index.ts
@@ -11,6 +11,7 @@ export type { CatalogKind, NotebookKind } from "./kinds.ts";
export {
NotebookClient,
type NotebookClientOptions,
+ type unstable_NotebookCall,
} from "./notebook/client.ts";
export {
NotebookEvents,
diff --git a/packages/client/src/notebook/client.ts b/packages/client/src/notebook/client.ts
index effd80f4f1..6f8c20ba2f 100644
--- a/packages/client/src/notebook/client.ts
+++ b/packages/client/src/notebook/client.ts
@@ -4,8 +4,10 @@ import type * as Protocol from "../protocol.ts";
import type { NotebookKind } from "../kinds.ts";
import {
below,
+ type CallTarget,
type ClientOptions,
type MutationOptions,
+ type OperationCall,
type OperationsBelow,
request,
type Result,
@@ -30,46 +32,26 @@ interface SaveOptions extends DecisionOptions {
type Scope = "/notebooks/{notebook_id}";
+type NotebookOperationId = OperationsBelow<Scope>;
+
/**
- * A client for one notebook.
+ * A notebook operation as one message, the parts of its request without a URL.
*
- * Requests go to URLs below the notebook's URL and keep its query string.
+ * `unstable_NotebookCall` is any notebook operation, and
+ * `unstable_NotebookCall<"notebook.edit">` is one. Header names are lowercase.
+ *
+ * @experimental The shape may change while transports other than HTTP settle.
*/
-export class NotebookClient {
- readonly #url: URL;
- readonly #target: Target<Scope>;
-
- public constructor(url: string | URL, init: NotebookClientOptions = {}) {
- this.#url = new URL(url);
- this.#target = {
- url: this.#url,
- prefix: "/notebooks/{notebook_id}",
- client: init,
- };
- }
+export type unstable_NotebookCall<
+ Id extends NotebookOperationId = NotebookOperationId,
+> = OperationCall<Id>;
- /**
- * The notebook's URL, such as `…/api/marimo/v1/notebooks/n1`.
- *
- * Each read returns a copy, so changing it does not redirect requests.
- */
- public get url(): URL {
- return new URL(this.#url);
- }
+/** The notebook's operations, sent to whichever target the client was given. */
+class NotebookOperations {
+ readonly #target: Target<Scope> | CallTarget<Scope>;
- /**
- * Follow the notebook's stream.
- *
- * The stream is served below the notebook's URL over server-sent events,
- * and shares this client's options.
- */
- public events<const K extends string = NotebookKind>(
- options: Omit<NotebookEventsOptions<K>, keyof ClientOptions> = {},
- ): NotebookEvents<K> {
- return new NotebookEvents<K>(below(this.#url, "/events"), {
- ...this.#target.client,
- ...options,
- });
+ public constructor(target: Target<Scope> | CallTarget<Scope>) {
+ this.#target = target;
}
/** Rename or move the notebook. */
@@ -164,3 +146,69 @@ export class NotebookClient {
return request(this.#target, id, call);
}
}
+
+/**
+ * A client for one notebook.
+ *
+ * Requests go to URLs below the notebook's URL and keep its query string.
+ */
+export class NotebookClient extends NotebookOperations {
+ readonly #url: URL;
+ readonly #options: NotebookClientOptions;
+
+ public constructor(url: string | URL, init: NotebookClientOptions = {}) {
+ const notebook = new URL(url);
+ super({ url: notebook, prefix: "/notebooks/{notebook_id}", client: init });
+ this.#url = notebook;
+ this.#options = init;
+ }
+
+ /**
+ * A client whose requests go to `send` as calls rather than over HTTP.
+ *
+ * `send` delivers each call and resolves with the host's reply, a status
+ * and a body. Replies are validated as HTTP responses are. The client has
+ * no URL, so it has no `url` or `events`.
+ *
+ * @experimental The shape may change while transports other than HTTP settle.
+ */
+ public static unstable_over(
+ send: (call: unstable_NotebookCall) => Promise<unknown>,
+ { notebookId }: { readonly notebookId: string },
+ ): Omit<NotebookClient, "url" | "events"> {
+ return new NotebookOperations({
+ // SAFETY: `request` builds each message from its operation's table
+ // entry. Its params fill the path's placeholders, its headers are the
+ // entry's headers in lowercase, and its body is parsed by the entry's
+ // schema, which is the shape `unstable_NotebookCall` gives that
+ // operation. The tests check the message for each method.
+ send: (message) => send(message as unstable_NotebookCall),
+ prefix: "/notebooks/{notebook_id}",
+ params: { notebook_id: notebookId },
+ });
+ }
+
+ /**
+ * The notebook's URL, such as `…/api/marimo/v1/notebooks/n1`.
+ *
+ * Each read returns a copy, so changing it does not redirect requests.
+ */
+ public get url(): URL {
+ return new URL(this.#url);
+ }
+
+ /**
+ * Follow the notebook's stream.
+ *
+ * The stream is served below the notebook's URL over server-sent events,
+ * and shares this client's options.
+ */
+ public events<const K extends string = NotebookKind>(
+ options: Omit<NotebookEventsOptions<K>, keyof ClientOptions> = {},
+ ): NotebookEvents<K> {
+ return new NotebookEvents<K>(below(this.#url, "/events"), {
+ ...this.#options,
+ ...options,
+ });
+ }
+}
diff --git a/packages/client/src/request.ts b/packages/client/src/request.ts
index 4efa7da1b0..c3e24a9de8 100644
--- a/packages/client/src/request.ts
+++ b/packages/client/src/request.ts
@@ -1,6 +1,6 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import type * as z from "zod";
+import * as z from "zod";
import { type OperationId, operations } from "./operations.ts";
import * as Protocol from "./protocol.ts";
@@ -72,6 +72,26 @@ export interface Target<Prefix extends string> {
readonly client: ClientOptions;
}
+/**
+ * Where a client's requests go as calls rather than HTTP requests.
+ *
+ * `params` holds the values a URL would carry for `prefix`, such as the
+ * notebook's id, so each call names every path parameter.
+ */
+export interface CallTarget<Prefix extends string> {
+ readonly send: (call: CallMessage) => Promise<unknown>;
+ readonly prefix: Prefix;
+ readonly params: Readonly<Record<string, string>>;
+}
+
+/** A call as `request` builds it, before its type is narrowed to its operation. */
+export interface CallMessage {
+ readonly operation: RequestOperationId;
+ readonly params: Readonly<Record<string, string>>;
+ readonly headers: Readonly<Record<string, string>>;
+ readonly body: unknown;
+}
+
/** What a request reads from each entry of the operations table. */
interface Operation {
readonly method: string;
@@ -96,6 +116,41 @@ type Data<Id extends RequestOperationId> = {
: undefined;
}[keyof Entry<Id>["responses"]];
+/** The placeholder names in a path, such as `notebook_id`. */
+type PathParams<Path extends string> =
+ Path extends `${string}{${infer Name}}${infer Rest}`
+ ? Name | PathParams<Rest>
+ : never;
+
+/** An operation's headers by lowercase name, with the required ones required. */
+type CallHeaders<Headers> = {
+ readonly [
+ Name in keyof Headers as Headers[Name] extends true
+ ? Lowercase<Name & string>
+ : never
+ ]: string;
+} & {
+ readonly [
+ Name in keyof Headers as Headers[Name] extends true
+ ? never
+ : Lowercase<Name & string>
+ ]?: string;
+};
+
+/** An operation as one message, the parts of its request without a URL. */
+export type OperationCall<Id extends RequestOperationId> = {
+ [K in Id]: {
+ readonly operation: K;
+ readonly params: {
+ readonly [Name in PathParams<Entry<K>["path"]>]: string;
+ };
+ readonly headers: CallHeaders<Entry<K>["headers"]>;
+ readonly body: Entry<K>["body"] extends z.ZodType
+ ? z.output<Entry<K>["body"]>
+ : undefined;
+ };
+}[Id];
+
/** What a request sends besides its operation. */
interface Call<Id extends RequestOperationId> {
/** Values for the placeholders in the path below the target's prefix. */
@@ -175,6 +230,16 @@ export function resolve<Prefix extends string>(
return below(target.url, suffix);
}
+/** A host's answer, read the same way whichever way the request went. */
+interface Answer {
+ readonly status: number;
+ /** Whether the answer describes itself as a problem. */
+ readonly problem: boolean;
+ json(): Promise<unknown>;
+}
+
+const Reply = z.object({ status: z.number().int(), body: z.unknown() });
+
/**
* Send one request and decode the host's answer.
*
@@ -186,50 +251,122 @@ export async function request<
Prefix extends string,
Id extends OperationsBelow<Prefix>,
>(
- target: Target<Prefix>,
+ target: Target<Prefix> | CallTarget<Prefix>,
id: Id,
{ params = {}, body, headers = {}, options = {} }: Call<Id>,
): Promise<Result<Data<Id>>> {
const operation = table[id];
- const { client } = target;
- const sent = new Headers();
- sent.set("Accept", "application/json, application/problem+json");
- if (client.token !== undefined) {
- sent.set("Authorization", `Bearer ${client.token}`);
- }
+ const sent: Record<string, string> = {};
if ("Idempotency-Key" in operation.headers) {
- sent.set("Idempotency-Key", options.idempotencyKey ?? idempotencyKey());
+ sent["Idempotency-Key"] = options.idempotencyKey ?? idempotencyKey();
}
for (const [name, value] of Object.entries(headers)) {
if (value !== undefined) {
- sent.set(name, value);
+ sent[name] = value;
}
}
- let payload: string | undefined;
- if (operation.body !== null) {
- sent.set("Content-Type", "application/json");
- payload = JSON.stringify(operation.body.parse(body));
- }
- const fetch = client.fetch ?? globalThis.fetch;
- const response = await fetch(resolve(target, operation.path, params), {
- method: operation.method,
- headers: sent,
- body: payload,
- signal: options.signal,
- });
- const status = response.status;
+ const payload =
+ operation.body === null ? undefined : operation.body.parse(body);
+ const answer =
+ "send" in target
+ ? await call(
+ target,
+ {
+ operation: id,
+ params: { ...target.params, ...params },
+ headers: Object.fromEntries(
+ Object.entries(sent).map(([name, value]) => [
+ name.toLowerCase(),
+ value,
+ ]),
+ ),
+ body: payload,
+ },
+ options.signal,
+ )
+ : await fetchAnswer(
+ target,
+ operation,
+ params,
+ sent,
+ payload,
+ options.signal,
+ );
+ const status = answer.status;
const schema = operation.responses[status];
if (schema === null) {
+ // SAFETY: a `null` schema is how the table marks a status with no
+ // content, and `Data<Id>` maps that status to `undefined`.
return { ok: true, status, data: undefined as Data<Id> };
}
if (schema !== undefined && schema !== "text/event-stream") {
- const data = schema.parse(await response.json()) as Data<Id>;
+ // SAFETY: `schema` is the table's schema for this status of `id`, and
+ // `Data<Id>` is the union of those schemas' outputs.
+ const data = schema.parse(await answer.json()) as Data<Id>;
return { ok: true, status, data };
}
- const type = response.headers.get("Content-Type");
- if (!response.ok && isType(type, "application/problem+json")) {
- const problem = Protocol.Problem.parse(await response.json());
+ if ((status < 200 || status >= 300) && answer.problem) {
+ const problem = Protocol.Problem.parse(await answer.json());
return { ok: false, status, problem };
}
throw new Error(`Unexpected ${status} response to ${id}`);
}
+
+async function fetchAnswer<Prefix extends string>(
+ target: Target<Prefix>,
+ operation: Operation,
+ params: Readonly<Record<string, string>>,
+ headers: Readonly<Record<string, string>>,
+ payload: unknown,
+ signal: AbortSignal | undefined,
+): Promise<Answer> {
+ const sent = new Headers(headers);
+ sent.set("Accept", "application/json, application/problem+json");
+ if (target.client.token !== undefined) {
+ sent.set("Authorization", `Bearer ${target.client.token}`);
+ }
+ if (payload !== undefined) {
+ sent.set("Content-Type", "application/json");
+ }
+ const fetch = target.client.fetch ?? globalThis.fetch;
+ const response = await fetch(resolve(target, operation.path, params), {
+ method: operation.method,
+ headers: sent,
+ body: payload === undefined ? undefined : JSON.stringify(payload),
+ signal,
+ });
+ return {
+ status: response.status,
+ problem: isType(
+ response.headers.get("Content-Type"),
+ "application/problem+json",
+ ),
+ json: () => response.json(),
+ };
+}
+
+/** Deliver a call, and stop waiting on abort. A call already sent may still apply. */
+async function call<Prefix extends string>(
+ target: CallTarget<Prefix>,
+ message: CallMessage,
+ signal: AbortSignal | undefined,
+): Promise<Answer> {
+ signal?.throwIfAborted();
+ const sending = target.send(message);
+ const reply = Reply.parse(
+ signal === undefined
+ ? await sending
+ : await new Promise((resolve, reject) => {
+ const abort = () => reject(signal.reason);
+ signal.addEventListener("abort", abort, { once: true });
+ sending
+ .then(resolve, reject)
+ .finally(() => signal.removeEventListener("abort", abort));
+ }),
+ );
+ return {
+ status: reply.status,
+ problem: true,
+ json: async () => reply.body,
+ };
+}
diff --git a/tests/_pyodide/test_pyodide_acceptance.mjs b/tests/_pyodide/test_pyodide_acceptance.mjs
index 1ef636cd5c..cae796d04d 100644
--- a/tests/_pyodide/test_pyodide_acceptance.mjs
+++ b/tests/_pyodide/test_pyodide_acceptance.mjs
@@ -12,6 +12,7 @@
*/
import http from "node:http";
+import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { pathToFileURL } from "node:url";
@@ -144,7 +145,7 @@ async function main() {
// In Node.js, loadPyodide uses the bundled files from the npm package
// Load without packages first, then add packages separately
- const pyodide = await loadPyodide();
+ const pyodide = await loadPyodide({ convertNullToNone: true });
console.log("Pyodide loaded successfully");
// Load required packages that marimo depends on
@@ -295,6 +296,36 @@ result = {
json.dumps(result)
`);
+ // Exercise the same Python proxy and callback lifetime as the worker RPC.
+ const notebook = pyodide.runPython("bridge.notebook");
+ const frames = [];
+ try {
+ await notebook.subscribe("acceptance", null, (raw) => frames.push(JSON.parse(raw)));
+ assert.equal(frames.at(-1).event, "ready");
+ const cell = frames.find((frame) => frame.event === "cell").data.cell;
+ const call = JSON.stringify({
+ operation: "notebook.edit",
+ params: { notebook_id: cell.notebook_id },
+ headers: { "idempotency-key": "wasm-acceptance-edit" },
+ body: { changes: [{
+ kind: "put_cell", base_etag: cell.etag,
+ cell: { id: cell.id, code: "x = 7", name: cell.name, config: cell.config },
+ }] },
+ });
+ const reply = JSON.parse(await notebook.call(call));
+ assert.equal(reply.status, 200);
+ assert.deepEqual(frames.at(-1).data.document, reply.body.document);
+ assert.equal(frames.at(-2).data.cell.code, "x = 7");
+ assert.equal(frames.at(-1).data.request_id, "wasm-acceptance-edit");
+ const count = frames.length;
+ assert.deepEqual(JSON.parse(await notebook.call(call)), reply);
+ assert.equal(frames.length, count);
+ assert.equal(pyodide.runPython("list(session.app_manager.app.cell_manager.codes())[0]"), "x = 7");
+ notebook.unsubscribe("acceptance");
+ } finally {
+ notebook.destroy();
+ }
+
// Step 6: Test mo.watch.file in Pyodide (within execution context)
console.log("Step 6: Testing mo.watch.file in Pyodide...");
diff --git a/tests/_pyodide/test_pyodide_notebook.py b/tests/_pyodide/test_pyodide_notebook.py
new file mode 100644
index 0000000000..4a1644586b
--- /dev/null
+++ b/tests/_pyodide/test_pyodide_notebook.py
@@ -0,0 +1,227 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import json
+from typing import TYPE_CHECKING
+
+import msgspec
+import pytest
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+from marimo._ast.app_config import _AppConfig
+from marimo._config.config import DEFAULT_CONFIG
+from marimo._core.calls import EditCall, dispatch
+from marimo._pyodide.bootstrap import instantiate
+from marimo._pyodide.pyodide_session import PyodideBridge, PyodideSession
+from marimo._runtime.commands import (
+ AppMetadata,
+ CreateNotebookCommand,
+ EditCellsCommand,
+)
+from marimo._session.model import SessionMode
+from marimo._session.notebook import AppFileManager
+
+
+def bridge(tmp_path: Path):
+ filename = tmp_path / "notebook.py"
+ filename.write_text("""import marimo
+app = marimo.App()
+def _():
+ x = 1
+ return (x,)
+""")
+ session = PyodideSession(
+ AppFileManager(str(filename)),
+ SessionMode.EDIT,
+ lambda _: None,
+ AppMetadata(
+ query_params={},
+ cli_args={},
+ app_config=_AppConfig(),
+ filename=str(filename),
+ ),
+ DEFAULT_CONFIG,
+ )
+ bridge = PyodideBridge(session)
+ yield bridge
+ bridge.close()
+
+
+async def snapshot(bridge, subscription="reader", cursor=None):
+ events = []
+ await bridge.notebook.subscribe(
+ subscription, cursor, lambda raw: events.append(json.loads(raw))
+ )
+ return events
+
+
+async def send(bridge, call):
+ return json.loads(await bridge.notebook.call(json.dumps(call)))
+
+
+def edit(events, code="x = 2", request_id="edit-1"):
+ cell = next(
+ event["data"]["cell"] for event in events if event["event"] == "cell"
+ )
+ return {
+ "operation": "notebook.edit",
+ "params": {"notebook_id": cell["notebook_id"]},
+ "headers": {"idempotency-key": request_id},
+ "body": {
+ "changes": [
+ {
+ "kind": "put_cell",
+ "base_etag": cell["etag"],
+ "cell": {
+ "id": cell["id"],
+ "code": code,
+ "name": cell["name"],
+ "config": cell["config"],
+ },
+ }
+ ]
+ },
+ }
+
+
+async def test_snapshot_edit_and_retry(bridge):
+ events = await snapshot(bridge)
+ assert [event["event"] for event in events] == [
+ "notebook",
+ "cell",
+ "document",
+ "ready",
+ ]
+ assert events[0]["data"]["notebook"]["operations"] == ["notebook.edit"]
+ request = edit(events)
+ response = await send(bridge, request)
+ assert response["status"] == 200
+ assert response["body"]["document"] == events[-1]["data"]["document"]
+ assert [event["event"] for event in events[-2:]] == ["cell", "document"]
+ assert all(
+ event["data"]["request_id"] == "edit-1" for event in events[-2:]
+ )
+ assert list(bridge.session.app_manager.app.cell_manager.codes()) == [
+ "x = 2"
+ ]
+ count = len(events)
+ assert await send(bridge, request) == response
+ assert len(events) == count
+ # A call dispatched directly shares the worker's retry receipts.
+ direct = await dispatch(
+ bridge.notebook.mutations,
+ bridge.notebook,
+ msgspec.json.decode(json.dumps(request), type=EditCall),
+ )
+ assert msgspec.json.decode(msgspec.json.encode(direct)) == [
+ response["status"],
+ response["body"],
+ ]
+ assert len(events) == count
+ conflict = await send(bridge, edit(events, "x = 3"))
+ assert conflict["body"]["type"].endswith("/conflict")
+ assert list(bridge.session.app_manager.app.cell_manager.codes()) == [
+ "x = 2"
+ ]
+
+
+async def test_atomic_conflict_and_kernel_update(bridge):
+ events = await snapshot(bridge)
+ instantiate(bridge.session, auto_instantiate=False)
+ queue = bridge.session._queue_manager.control_queue
+ assert isinstance(queue.get_nowait(), CreateNotebookCommand)
+ await send(bridge, edit(events))
+ update = queue.get_nowait()
+ assert isinstance(update, EditCellsCommand)
+ cell_id = events[1]["data"]["cell"]["id"]
+ assert update.codes == {cell_id: "x = 2"}
+ request = edit(events, "x = 3", request_id="conflict")
+ request["body"]["changes"].insert(
+ 0,
+ {
+ "kind": "put_cell",
+ "base_etag": None,
+ "after": cell_id,
+ "cell": {"id": "new", "code": "y = 1"},
+ },
+ )
+ result = await send(bridge, request)
+ assert result["status"] == 409
+ assert result["body"]["edit"]["change"] == 1
+ assert result["body"]["edit"]["cell"]["code"] == "x = 2"
+ assert list(bridge.session.app_manager.app.cell_manager.codes()) == [
+ "x = 2"
+ ]
+ assert queue.empty()
+
+
+async def test_edit_before_instantiation(bridge):
+ events = await snapshot(bridge)
+ await send(bridge, edit(events))
+ queue = bridge.session._queue_manager.control_queue
+ assert queue.empty()
+ instantiate(bridge.session, auto_instantiate=False)
+ command = queue.get_nowait()
+ assert isinstance(command, CreateNotebookCommand)
+ assert [request.code for request in command.execution_requests] == [
+ "x = 2"
+ ]
+ assert queue.empty()
+
+
+async def test_resume_and_independent_unsubscribe(bridge):
+ first = await snapshot(bridge, "first")
+ cursor = first[-1]["id"]
+ await send(bridge, edit(first))
+ second = await snapshot(bridge, "second", cursor)
+ assert [event["event"] for event in second] == [
+ "cell",
+ "document",
+ "ready",
+ ]
+ bridge.notebook.unsubscribe("first")
+ count = len(first)
+ await send(bridge, edit(second, "x = 3", request_id="edit-2"))
+ assert len(first) == count
+ assert second[-2]["data"]["cell"]["code"] == "x = 3"
+ reset = await snapshot(bridge, "third", "another-host")
+ assert [event["event"] for event in reset] == [
+ "reset",
+ "notebook",
+ "cell",
+ "document",
+ "ready",
+ ]
+ bridge.close()
+ with pytest.raises(RuntimeError, match="closed"):
+ await snapshot(bridge)
+ assert bridge.notebook._subscriptions == {}
+
+
+async def test_permissions_and_unsupported_operations(bridge):
+ bridge.session.mode = SessionMode.RUN
+ events = await snapshot(bridge)
+ assert events[0]["data"]["notebook"]["operations"] == []
+ request = edit(events)
+ assert (await send(bridge, request))["status"] == 403
+ save = {**request, "operation": "notebook.save", "body": {}}
+ assert (await send(bridge, save))["status"] == 501
+
+
+async def test_invalid_calls(bridge):
+ request = edit(await snapshot(bridge))
+ for invalid in (
+ {**request, "body": "not a request"},
+ {**request, "operation": "notebook.missing"},
+ {**request, "params": {}},
+ ):
+ reply = await send(bridge, invalid)
+ assert reply["status"] == 400
+ assert reply["body"]["type"].endswith("/invalid-request")
+ assert json.loads(await bridge.notebook.call("{"))["status"] == 400
+ other = {**request, "params": {"notebook_id": "elsewhere"}}
+ assert (await send(bridge, other))["status"] == 404