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.

Route the editor's notebook through a backend (#11507)

Trevor Manzad2a7bc63422
diff --git a/frontend/src/core/host/__tests__/notebook-client.test.ts b/frontend/src/core/host/__tests__/notebook-client.test.ts
index a41a14dfe8..ecaf9eee38 100644
--- a/frontend/src/core/host/__tests__/notebook-client.test.ts
+++ b/frontend/src/core/host/__tests__/notebook-client.test.ts
@@ -6,8 +6,9 @@ import { createStore } from "jotai";
import { afterEach, describe, expect, it, vi } from "vitest";
import { Deferred } from "@/utils/Deferred";
import { ConnectionState } from "../../websocket/types";
+import type { NotebookBackend } from "../backend";
import type { ConnectionStatus } from "../connection";
-import { createNotebookClient, type NotebookClient } from "../notebook-client";
+import { createNotebookClient } from "../notebook-client";
import { fixtureEvents, fixtureMessages } from "./fixtures";
/** One connection the fake transport opened. */
@@ -22,7 +23,14 @@ interface Attempt {
stop(status?: ConnectionStatus): void;
}
-function setup(edit?: NotebookClient["edit"]) {
+type Commands = ReturnType<NotebookBackend["notebook"]>;
+/** A backend edit with the notebook it was sent to. */
+type Edit = (
+ id: string,
+ ...args: Parameters<Commands["edit"]>
+) => ReturnType<Commands["edit"]>;
+
+function setup(edit = vi.fn<Edit>()) {
const attempts: Attempt[] = [];
const transport: NotebookTransport = ({ cursor, signal }, handlers) =>
new Promise((resolve, reject) => {
@@ -40,11 +48,15 @@ function setup(edit?: NotebookClient["edit"]) {
const onNotification = vi.fn();
const checkHealth = vi.fn(async () => true);
const store = createStore();
- const controller = createNotebookClient(store, { edit });
+ const backend: NotebookBackend = {
+ transport,
+ notebook: (id) => ({ edit: (...args) => edit(id, ...args) }),
+ };
+ const controller = createNotebookClient(store);
const client = controller.client;
const connect = (signal: AbortSignal) =>
controller.connect({
- transport,
+ backend,
signal,
checkHealth,
onNotification: (notification) => onNotification({ data: notification }),
@@ -99,7 +111,7 @@ const notebook = {
describe("NotebookClient lifetime", () => {
it("keeps an edit's target and request identity across a stream reset", async () => {
- const edit = vi.fn<NotebookClient["edit"]>().mockResolvedValue({
+ const edit = vi.fn<Edit>().mockResolvedValue({
ok: false,
status: 409,
problem: { type: "conflict", title: "conflict", status: 409 },
@@ -127,7 +139,7 @@ describe("NotebookClient lifetime", () => {
expect(edit).toHaveBeenCalledTimes(2);
});
- it("rejects aborted edits and reports a missing edit adapter", async () => {
+ it("rejects aborted edits and reports edits before connecting", async () => {
const { client } = setup();
const controller = lifetime();
await expect(
diff --git a/frontend/src/core/host/__tests__/static.test.ts b/frontend/src/core/host/__tests__/static.test.ts
index 505869fdc1..43f7825374 100644
--- a/frontend/src/core/host/__tests__/static.test.ts
+++ b/frontend/src/core/host/__tests__/static.test.ts
@@ -129,7 +129,7 @@ describe("static notebook backend", () => {
it("advertises no mutations and returns a protocol failure for direct edits", async () => {
const backend = createStaticNotebookBackend(snapshot());
- expect(await backend.client.edit([])).toEqual({
+ expect(await backend.notebook(snapshot().notebook.id).edit([])).toEqual({
ok: false,
status: 501,
problem: {
@@ -154,7 +154,9 @@ describe("static notebook backend", () => {
expect(open).not.toHaveBeenCalled();
expect(message).not.toHaveBeenCalled();
await expect(
- backend.client.edit([], { signal: before.signal }),
+ backend
+ .notebook(snapshot().notebook.id)
+ .edit([], { signal: before.signal }),
).rejects.toBe(before.signal.reason);
const during = new AbortController();
message.mockImplementation(() => during.abort());
diff --git a/frontend/src/core/host/__tests__/wasm.test.ts b/frontend/src/core/host/__tests__/wasm.test.ts
index 2bbbcb0455..43c619a933 100644
--- a/frontend/src/core/host/__tests__/wasm.test.ts
+++ b/frontend/src/core/host/__tests__/wasm.test.ts
@@ -102,9 +102,9 @@ describe("WASM notebook backend", () => {
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(
+ await backend.notebook("n1").edit([], { idempotencyKey: "edit-7" }),
+ ).toEqual(reply);
expect(bridge.call).toHaveBeenCalledWith({
operation: "notebook.edit",
params: { notebook_id: "n1" },
@@ -117,13 +117,15 @@ describe("WASM notebook backend", () => {
status: 403,
};
bridge.call.mockResolvedValue({ status: 403, body: problem });
- expect(await backend.client.edit([])).toEqual({
+ expect(await backend.notebook("n1").edit([])).toEqual({
ok: false,
status: 403,
problem,
});
bridge.call.mockResolvedValue({ status: 200, body: {} });
- await expect(backend.client.edit([])).rejects.toThrow(/Invalid input/);
+ await expect(backend.notebook("n1").edit([])).rejects.toThrow(
+ /Invalid input/,
+ );
});
it("cancels waiting for an accepted edit and permits retry with the same key", async () => {
@@ -132,7 +134,7 @@ describe("WASM notebook backend", () => {
bridge.call.mockReturnValue(pending.promise);
const backend = createWasmNotebookBackend(bridge);
const controller = new AbortController();
- const editing = backend.client.edit([], {
+ const editing = backend.notebook("n1").edit([], {
signal: controller.signal,
idempotencyKey: "edit-8",
});
@@ -140,12 +142,12 @@ describe("WASM notebook backend", () => {
controller.abort();
await expect(editing).rejects.toBe(controller.signal.reason);
pending.resolve(wire);
- expect(await backend.client.edit([], { idempotencyKey: "edit-8" })).toEqual(
- reply,
- );
+ expect(
+ await backend.notebook("n1").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 }),
+ backend.notebook("n1").edit([], { signal: controller.signal }),
).rejects.toBe(controller.signal.reason);
expect(bridge.call).toHaveBeenCalledTimes(2);
});
diff --git a/frontend/src/core/host/backend.ts b/frontend/src/core/host/backend.ts
index e019aac380..58f20fdb57 100644
--- a/frontend/src/core/host/backend.ts
+++ b/frontend/src/core/host/backend.ts
@@ -1,10 +1,15 @@
/* Copyright 2026 Marimo. All rights reserved. */
import type { NotebookClient, NotebookTransport } from "@marimo-team/client";
+import type { NotebookId } from "@marimo-team/client/protocol";
-/** Events and commands for the same notebook, independent of React or a replica. */
+/** Events and commands for a notebook, independent of React or a replica. */
export interface NotebookBackend {
readonly transport: NotebookTransport;
- /** Method presence is not permission; the notebook advertises its operations. */
- readonly client: Pick<NotebookClient, "edit">;
+ /**
+ * Commands for a notebook the transport reported.
+ *
+ * Method presence is not permission. The notebook advertises its operations.
+ */
+ notebook(id: NotebookId): Pick<NotebookClient, "edit">;
}
diff --git a/frontend/src/core/host/notebook-client.ts b/frontend/src/core/host/notebook-client.ts
index 061b7cd1c9..1d52404352 100644
--- a/frontend/src/core/host/notebook-client.ts
+++ b/frontend/src/core/host/notebook-client.ts
@@ -5,7 +5,6 @@ import {
createNotebookReducer,
type NotebookEvent,
NotebookEvents,
- type NotebookTransport,
type Result,
StreamStopped,
} from "@marimo-team/client";
@@ -18,6 +17,7 @@ import type {
} from "@marimo-team/client/protocol";
import { type Atom, atom, type createStore } from "jotai/vanilla";
import { z } from "zod";
+import type { NotebookBackend } from "./backend";
import {
ConnectionClosedReason,
ConnectionState,
@@ -60,10 +60,10 @@ export interface NotebookClient {
reconnect(): Promise<void>;
}
-/** The transport and application callbacks needed to follow a notebook. */
+/** The backend and application callbacks needed to follow a notebook. */
export interface NotebookConnection {
- /** Opens one connection to the notebook's stream. */
- transport: NotebookTransport;
+ /** Follows the notebook's stream and sends its commands. */
+ backend: NotebookBackend;
/** Abort to close the stream and clear the client's state. */
signal: AbortSignal;
/** Check whether the host is reachable before an explicit reconnect. */
@@ -103,14 +103,8 @@ function statusAfter(error: unknown): ConnectionStatus {
return disconnected;
}
-/**
- * Create a client without opening a connection.
- * The session supplies edits authenticated for the same host as its stream.
- */
-export function createNotebookClient(
- store: ReturnType<typeof createStore>,
- { edit }: { edit?: NotebookClient["edit"] } = {},
-) {
+/** Create a client without opening a connection. */
+export function createNotebookClient(store: ReturnType<typeof createStore>) {
// `useNotebookSession` copies this into the editor's shared `connectionAtom`,
// which gates features until MO-8051 derives availability separately.
const connectionAtom = atom<ConnectionStatus>({
@@ -137,6 +131,7 @@ export function createNotebookClient(
: attachments.initial,
);
let reconnect: (() => Promise<void>) | undefined;
+ let backend: NotebookBackend | undefined;
const client: NotebookClient = {
connectionAtom,
notebookAtom,
@@ -147,7 +142,7 @@ export function createNotebookClient(
if (currentId !== null && currentId !== notebookId) {
throw new Error("The notebook changed before the edit was sent");
}
- if (edit === undefined) {
+ if (backend === undefined) {
return {
ok: false,
status: 501,
@@ -158,7 +153,7 @@ export function createNotebookClient(
},
};
}
- return edit(notebookId, changes, options);
+ return backend.notebook(notebookId).edit(changes, options);
},
attachmentsAtom,
reconnect: async () => reconnect?.(),
@@ -170,7 +165,7 @@ export function createNotebookClient(
}
function connect({
- transport,
+ backend: connected,
signal,
checkHealth,
onNotification,
@@ -178,6 +173,8 @@ export function createNotebookClient(
if (signal.aborted) {
return;
}
+ backend = connected;
+ const { transport } = connected;
let events: NotebookEvents<(typeof TYPES)[number]> | undefined;
let checkingHealth = false;
// Whether the replica still holds the state the last cursor describes.
@@ -283,6 +280,9 @@ export function createNotebookClient(
"abort",
() => {
reconnect = undefined;
+ if (backend === connected) {
+ backend = undefined;
+ }
store.set(streamAtom, reducer.initial);
setStatus({ state: ConnectionState.NOT_STARTED });
},
diff --git a/frontend/src/core/host/static.ts b/frontend/src/core/host/static.ts
index 5b60921710..ed1c2ceb0b 100644
--- a/frontend/src/core/host/static.ts
+++ b/frontend/src/core/host/static.ts
@@ -51,7 +51,7 @@ export function createStaticNotebookBackend(
message(frame);
}
}),
- client: {
+ notebook: () => ({
edit: async (_changes, options) => {
options?.signal?.throwIfAborted();
return {
@@ -65,6 +65,6 @@ export function createStaticNotebookBackend(
},
};
},
- },
+ }),
};
}
diff --git a/frontend/src/core/host/wasm.ts b/frontend/src/core/host/wasm.ts
index 2e5bda6d59..5458321c4e 100644
--- a/frontend/src/core/host/wasm.ts
+++ b/frontend/src/core/host/wasm.ts
@@ -39,6 +39,9 @@ function abortable<T>(
export function createWasmNotebookBackend(
bridge: WasmNotebookBridge,
): NotebookBackend {
+ const client = NotebookClient.unstable_over((call) => bridge.call(call), {
+ notebookId: bridge.notebookId,
+ });
return {
transport: async ({ cursor, signal }, { open, message }) => {
if (signal.aborted) {
@@ -85,8 +88,6 @@ export function createWasmNotebookBackend(
signal.removeEventListener("abort", abort);
}
},
- client: NotebookClient.unstable_over((call) => bridge.call(call), {
- notebookId: bridge.notebookId,
- }),
+ notebook: () => client,
};
}
diff --git a/frontend/src/core/runtime/__tests__/runtime.test.ts b/frontend/src/core/runtime/__tests__/runtime.test.ts
index 061efd4bb2..04c1695566 100644
--- a/frontend/src/core/runtime/__tests__/runtime.test.ts
+++ b/frontend/src/core/runtime/__tests__/runtime.test.ts
@@ -220,6 +220,23 @@ describe("RuntimeManager", () => {
});
});
+ describe("getNotebookURL", () => {
+ it("addresses the notebook below the host API without the auth token", () => {
+ const runtime = new RuntimeManager(
+ {
+ url: "https://sandbox.example.com/base",
+ lazy: true,
+ authToken: "my-secret-token",
+ },
+ true,
+ );
+ const url = runtime.getNotebookURL("n/1");
+
+ expect(url.pathname).toBe("/base/api/marimo/v1/notebooks/n%2F1");
+ expect(url.toString()).not.toContain("my-secret-token");
+ });
+ });
+
describe("getSseURL", () => {
it("should never put the auth token in the URL, even cross-origin", () => {
// SSE requests can send headers, so auth travels in the
diff --git a/frontend/src/core/runtime/runtime.ts b/frontend/src/core/runtime/runtime.ts
index cb155d4a19..6c441104dd 100644
--- a/frontend/src/core/runtime/runtime.ts
+++ b/frontend/src/core/runtime/runtime.ts
@@ -1,5 +1,6 @@
/* Copyright 2026 Marimo. All rights reserved. */
+import type { NotebookId } from "@marimo-team/client/protocol";
import { Deferred } from "@/utils/Deferred";
import { Logger } from "@/utils/Logger";
import { KnownQueryParams } from "../constants";
@@ -171,6 +172,18 @@ export class RuntimeManager {
return url;
}
+ /**
+ * The host API URL of a notebook, below which its operations are served.
+ * Requests send auth in headers (see `headers()`), never in the URL.
+ */
+ public getNotebookURL(notebookId: NotebookId): URL {
+ const url = this.formatHttpURL({
+ path: `/api/marimo/v1/notebooks/${encodeURIComponent(notebookId)}`,
+ });
+ url.searchParams.delete(KnownQueryParams.accessToken);
+ return url;
+ }
+
/**
* The WebSocket Sync URL of the runtime, for real-time updates.
*/
diff --git a/frontend/src/core/websocket/__tests__/backend.test.ts b/frontend/src/core/websocket/__tests__/backend.test.ts
new file mode 100644
index 0000000000..e029f7f714
--- /dev/null
+++ b/frontend/src/core/websocket/__tests__/backend.test.ts
@@ -0,0 +1,111 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { NotebookEvents } from "@marimo-team/client";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { createEditorBackend } from "../backend";
+
+const wasm = vi.hoisted(() => ({ enabled: false, consumer: vi.fn() }));
+vi.mock("../../wasm/utils", () => ({ isWasm: () => wasm.enabled }));
+vi.mock("../../wasm/bridge", () => ({
+ PyodideBridge: { INSTANCE: { attachMessageConsumer: wasm.consumer } },
+}));
+
+afterEach(() => {
+ wasm.enabled = false;
+ wasm.consumer.mockReset();
+ vi.unstubAllGlobals();
+});
+
+describe("createEditorBackend", () => {
+ const options = {
+ static: false,
+ transportType: "websocket" as const,
+ url: () => "ws://localhost/ws",
+ headers: () => ({}),
+ notebookUrl: (id: string) =>
+ new URL(`http://localhost/api/marimo/v1/notebooks/${id}`),
+ };
+
+ it.each([
+ ["a static notebook", { ...options, static: true }, "idle"],
+ ["WASM", options, "wasm"],
+ ["SSE", { ...options, transportType: "sse" as const }, "fetch"],
+ ["the default", options, "socket"],
+ ] as const)("follows %s", async (_name, chosen, expected) => {
+ wasm.enabled = expected === "wasm";
+ const fetch = vi.fn(() => new Promise<Response>(() => undefined));
+ const socket = vi.fn();
+ vi.stubGlobal("fetch", fetch);
+ vi.stubGlobal(
+ "WebSocket",
+ class extends EventTarget {
+ public constructor(url: URL) {
+ super();
+ socket(url);
+ }
+ public close() {}
+ },
+ );
+ const events = new NotebookEvents(createEditorBackend(chosen).transport);
+ await vi.waitFor(() =>
+ expect(
+ {
+ idle:
+ events.status === "connected" && !wasm.consumer.mock.calls.length,
+ wasm: wasm.consumer.mock.calls.length === 1,
+ fetch: fetch.mock.calls.length === 1,
+ socket: socket.mock.calls.length === 1,
+ }[expected],
+ ).toBe(true),
+ );
+ events.close();
+ });
+
+ it("edits a reported notebook on its host with the session's headers", async () => {
+ const fetch = vi.fn(
+ async (_input: RequestInfo | URL, _init?: RequestInit) =>
+ new Response(
+ JSON.stringify({ type: "conflict", title: "Conflict", status: 409 }),
+ {
+ status: 409,
+ headers: { "Content-Type": "application/problem+json" },
+ },
+ ),
+ );
+ vi.stubGlobal("fetch", fetch);
+ const backend = createEditorBackend({
+ ...options,
+ headers: () => ({
+ Authorization: "Bearer editor-token",
+ "Marimo-Server-Token": "server-token",
+ }),
+ });
+ const result = await backend
+ .notebook("n1")
+ .edit([], { idempotencyKey: "edit-1" });
+ expect(result).toMatchObject({ ok: false, status: 409 });
+ const [[input, init]] = fetch.mock.calls;
+ expect(String(input)).toBe(
+ "http://localhost/api/marimo/v1/notebooks/n1/edits",
+ );
+ const headers = new Headers(init?.headers);
+ expect(init?.method).toBe("POST");
+ expect(headers.get("Authorization")).toBe("Bearer editor-token");
+ expect(headers.get("Marimo-Server-Token")).toBe("server-token");
+ expect(headers.get("Idempotency-Key")).toBe("edit-1");
+ });
+
+ it.each([
+ ["a static notebook", { ...options, static: true }, false],
+ ["WASM", options, true],
+ ] as const)("does not edit %s", async (_name, chosen, isWasm) => {
+ wasm.enabled = isWasm;
+ const fetch = vi.fn();
+ vi.stubGlobal("fetch", fetch);
+ const result = await createEditorBackend(chosen)
+ .notebook("n1")
+ .edit([], { idempotencyKey: "edit-1" });
+ expect(result).toMatchObject({ ok: false, status: 501 });
+ expect(fetch).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/core/websocket/__tests__/useNotebookClient.hook.test.tsx b/frontend/src/core/websocket/__tests__/useNotebookClient.hook.test.tsx
index 98ac4d9206..77f1c9f769 100644
--- a/frontend/src/core/websocket/__tests__/useNotebookClient.hook.test.tsx
+++ b/frontend/src/core/websocket/__tests__/useNotebookClient.hook.test.tsx
@@ -8,13 +8,19 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import type { NotebookTransport } from "@marimo-team/client";
import { ConnectionState } from "../types";
import { Deferred } from "@/utils/Deferred";
-import { createNotebookTransport } from "../transports/notebook";
+import type { NotebookBackend } from "../../host/backend";
+import { createEditorBackend } from "../backend";
import { useNotebookClient } from "../useNotebookClient";
import { fixtureMessages } from "../../host/__tests__/fixtures";
import { agentAttachmentsAtom } from "../../attachments/state";
import { notebookClientAtom } from "../state";
-vi.mock("../transports/notebook", () => ({ createNotebookTransport: vi.fn() }));
+vi.mock("../backend", () => ({ createEditorBackend: vi.fn() }));
+
+/** A backend that follows `transport` and cannot edit. */
+function backend(transport: NotebookTransport): NotebookBackend {
+ return { transport, notebook: () => ({ edit: vi.fn() }) };
+}
/** A transport whose connections the test drives. */
function makeTransport() {
@@ -53,6 +59,7 @@ function setup(
transportType: "websocket" as const,
url: () => "ws://localhost/ws",
headers: () => ({}),
+ notebookUrl: (id: string) => new URL(`http://localhost/notebooks/${id}`),
waitUntilReady: async () => undefined,
checkHealth: async () => true,
onNotification: vi.fn(),
@@ -70,7 +77,7 @@ function setup(
}
beforeEach(() => {
- vi.mocked(createNotebookTransport).mockReset();
+ vi.mocked(createEditorBackend).mockReset();
});
describe("useNotebookClient", () => {
@@ -78,16 +85,15 @@ describe("useNotebookClient", () => {
"rechecks health after failed startup (healthy: %s)",
async (healthy) => {
const fake = makeTransport();
- vi.mocked(createNotebookTransport).mockImplementation(
- ({ url }) =>
- async (attempt, handlers) => {
- if (typeof url === "function") {
- await url();
- }
- if (!attempt.signal.aborted) {
- return fake.transport(attempt, handlers);
- }
- },
+ vi.mocked(createEditorBackend).mockImplementation(({ url }) =>
+ backend(async (attempt, handlers) => {
+ if (typeof url === "function") {
+ await url();
+ }
+ if (!attempt.signal.aborted) {
+ return fake.transport(attempt, handlers);
+ }
+ }),
);
const waitUntilReady = vi
.fn()
@@ -125,14 +131,13 @@ describe("useNotebookClient", () => {
it("waits for initial readiness without reviving an unmounted connection", async () => {
const ready = new Deferred<void>();
const resolvedUrl = vi.fn();
- vi.mocked(createNotebookTransport).mockImplementation(
- ({ url }) =>
- async () => {
- if (typeof url === "function") {
- await url();
- resolvedUrl();
- }
- },
+ vi.mocked(createEditorBackend).mockImplementation(({ url }) =>
+ backend(async () => {
+ if (typeof url === "function") {
+ await url();
+ resolvedUrl();
+ }
+ }),
);
const { result, store, unmount } = setup(false, {
waitUntilReady: () => ready.promise,
@@ -152,7 +157,7 @@ describe("useNotebookClient", () => {
it("exposes host presence to the UI without waiting for kernel-ready", async () => {
const fake = makeTransport();
- vi.mocked(createNotebookTransport).mockReturnValue(fake.transport);
+ vi.mocked(createEditorBackend).mockReturnValue(backend(fake.transport));
const { result, store, unmount } = setup();
await act(async () => Promise.resolve());
expect(store.get(notebookClientAtom)).toBe(result.current);
@@ -177,7 +182,7 @@ describe("useNotebookClient", () => {
it("uses current callbacks and URL providers without reconnecting on a rerender", async () => {
const fake = makeTransport();
- vi.mocked(createNotebookTransport).mockReturnValue(fake.transport);
+ vi.mocked(createEditorBackend).mockReturnValue(backend(fake.transport));
const { rerender, options, unmount } = setup();
await act(async () => Promise.resolve());
const onNotification = vi.fn();
@@ -187,8 +192,8 @@ describe("useNotebookClient", () => {
expect(onNotification).toHaveBeenCalledExactlyOnceWith({
data: { op: "reconnected" },
});
- expect(createNotebookTransport).toHaveBeenCalledOnce();
- const [{ url }] = vi.mocked(createNotebookTransport).mock.calls[0];
+ expect(createEditorBackend).toHaveBeenCalledOnce();
+ const [{ url }] = vi.mocked(createEditorBackend).mock.calls[0];
expect(String(await (url as () => Promise<string>)())).toBe(
"ws://redirected/ws",
);
@@ -197,10 +202,10 @@ describe("useNotebookClient", () => {
it("closes every stream under Strict Mode and only follows the active lifetime", async () => {
const fakes: ReturnType<typeof makeTransport>[] = [];
- vi.mocked(createNotebookTransport).mockImplementation(() => {
+ vi.mocked(createEditorBackend).mockImplementation(() => {
const next = makeTransport();
fakes.push(next);
- return next.transport;
+ return backend(next.transport);
});
const { result, store, options, unmount } = setup(true);
await act(async () => Promise.resolve());
diff --git a/frontend/src/core/websocket/__tests__/useNotebookSession.hook.test.tsx b/frontend/src/core/websocket/__tests__/useNotebookSession.hook.test.tsx
index 08850489ed..6eca0f212a 100644
--- a/frontend/src/core/websocket/__tests__/useNotebookSession.hook.test.tsx
+++ b/frontend/src/core/websocket/__tests__/useNotebookSession.hook.test.tsx
@@ -21,8 +21,8 @@ import {
vi,
} from "vitest";
-vi.mock("../transports/notebook", () => ({
- createNotebookTransport: vi.fn(),
+vi.mock("../backend", () => ({
+ createEditorBackend: vi.fn(),
}));
vi.mock("@/core/runtime/config", async () => {
@@ -51,7 +51,7 @@ import { generateSessionId } from "../../kernel/session";
import { RuntimeManager } from "../../runtime/runtime";
import { WebSocketClosedReason, ConnectionState } from "../types";
import { classifyCloseEvent } from "../connection-state";
-import { createNotebookTransport } from "../transports/notebook";
+import { createEditorBackend } from "../backend";
import { useNotebookSession } from "../useNotebookSession";
import { type NotebookTransport, StreamStopped } from "@marimo-team/client";
@@ -85,7 +85,10 @@ type FakeTransport = ReturnType<typeof makeTransport>;
/** Use a fake transport for the next session the hook follows. */
function withTransport(fake: FakeTransport = makeTransport()) {
- vi.mocked(createNotebookTransport).mockReturnValue(fake.transport);
+ vi.mocked(createEditorBackend).mockReturnValue({
+ transport: fake.transport,
+ notebook: () => ({ edit: vi.fn() }),
+ });
return fake;
}
diff --git a/frontend/src/core/websocket/backend.ts b/frontend/src/core/websocket/backend.ts
new file mode 100644
index 0000000000..f69bc28286
--- /dev/null
+++ b/frontend/src/core/websocket/backend.ts
@@ -0,0 +1,68 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { NotebookClient, type StreamUrl } from "@marimo-team/client";
+import type { NotebookId } from "@marimo-team/client/protocol";
+import type { NotebookBackend } from "../host/backend";
+import { PyodideBridge } from "../wasm/bridge";
+import { isWasm } from "../wasm/utils";
+import {
+ idle,
+ pyodide,
+ sessionSse,
+ websocket,
+ withHeaders,
+} from "./transports/notebook";
+
+/** How the editor follows its notebook. */
+export interface EditorBackendOptions {
+ static: boolean;
+ transportType: "websocket" | "sse";
+ /** The session route, read before each connection. */
+ url: StreamUrl;
+ /** The runtime's headers, read before each request. */
+ headers: () => Record<string, string>;
+ /** The host URL of a notebook the stream reported. */
+ notebookUrl: (notebookId: NotebookId) => URL;
+}
+
+/** Commands for a notebook the editor cannot change through its backend. */
+function uneditable(): ReturnType<NotebookBackend["notebook"]> {
+ return {
+ edit: async () => ({
+ ok: false,
+ status: 501,
+ problem: {
+ type: "tag:marimo.io,2026:host/unsupported-operation",
+ title: "Document editing is unavailable on this connection",
+ status: 501,
+ },
+ }),
+ };
+}
+
+/** Choose the backend for the editor's notebook. */
+export function createEditorBackend(
+ options: EditorBackendOptions,
+): NotebookBackend {
+ if (options.static) {
+ return { transport: idle, notebook: uneditable };
+ }
+ if (isWasm()) {
+ return {
+ transport: pyodide((consumer) =>
+ PyodideBridge.INSTANCE.attachMessageConsumer(consumer),
+ ),
+ notebook: uneditable,
+ };
+ }
+ return {
+ transport:
+ options.transportType === "sse"
+ ? sessionSse(options.url, options.headers)
+ : websocket(options.url),
+ notebook: (id) =>
+ new NotebookClient(options.notebookUrl(id), {
+ fetch: withHeaders(options.headers),
+ }),
+ };
+}
diff --git a/frontend/src/core/websocket/transports/__tests__/notebook.test.ts b/frontend/src/core/websocket/transports/__tests__/notebook.test.ts
index 6f48eb2a9a..c9d09d57f6 100644
--- a/frontend/src/core/websocket/transports/__tests__/notebook.test.ts
+++ b/frontend/src/core/websocket/transports/__tests__/notebook.test.ts
@@ -11,18 +11,7 @@ import { createNotebookClient } from "../../../host/notebook-client";
import { fixtureMessages } from "../../../host/__tests__/fixtures";
import { ConnectionState } from "../../../host/connection";
import { Deferred } from "@/utils/Deferred";
-import {
- createNotebookTransport,
- pyodide,
- sessionSse,
- websocket,
-} from "../notebook";
-
-const wasm = vi.hoisted(() => ({ enabled: false, consumer: vi.fn() }));
-vi.mock("../../../wasm/utils", () => ({ isWasm: () => wasm.enabled }));
-vi.mock("../../../wasm/bridge", () => ({
- PyodideBridge: { INSTANCE: { attachMessageConsumer: wasm.consumer } },
-}));
+import { pyodide, sessionSse, websocket } from "../notebook";
const encoder = new TextEncoder();
@@ -83,14 +72,14 @@ function network(transportType: "websocket" | "sse", url: StreamUrl) {
);
const count = () =>
transportType === "websocket" ? FakeSocket.opened.length : requests.length;
- const transport = createNotebookTransport({
- static: false,
- transportType,
- url,
- headers: () => ({}),
- });
+ const transport =
+ transportType === "websocket"
+ ? websocket(url)
+ : sessionSse(url, () => ({}));
+ const backend = { transport, notebook: () => ({ edit: vi.fn() }) };
let index = 0;
return {
+ backend,
transport,
count,
opened: async () => {
@@ -126,8 +115,6 @@ function network(transportType: "websocket" | "sse", url: StreamUrl) {
afterEach(() => {
FakeSocket.opened.length = 0;
- wasm.enabled = false;
- wasm.consumer.mockReset();
vi.unstubAllGlobals();
vi.useRealTimers();
});
@@ -313,7 +300,7 @@ describe.each(["websocket", "sse"] as const)(
const lifetime = new AbortController();
onTestFinished(() => lifetime.abort());
connect({
- transport: connection.transport,
+ backend: connection.backend,
signal: lifetime.signal,
checkHealth: async () => true,
onNotification: vi.fn(),
@@ -380,7 +367,7 @@ describe.each(["websocket", "sse"] as const)(
const lifetime = new AbortController();
onTestFinished(() => lifetime.abort());
connect({
- transport: connection.transport,
+ backend: connection.backend,
signal: lifetime.signal,
checkHealth: async () => true,
onNotification: vi.fn(),
@@ -466,37 +453,3 @@ describe("pyodide", () => {
events.close();
});
});
-
-describe("createNotebookTransport", () => {
- const options = {
- static: false,
- transportType: "websocket" as const,
- url: () => "ws://localhost/ws",
- headers: () => ({}),
- };
-
- it.each([
- ["a static notebook", { ...options, static: true }, "idle"],
- ["WASM", options, "wasm"],
- ["SSE", { ...options, transportType: "sse" as const }, "fetch"],
- ["the default", options, "socket"],
- ] as const)("follows %s", async (_name, chosen, expected) => {
- wasm.enabled = expected === "wasm";
- const fetch = vi.fn(() => new Promise<Response>(() => undefined));
- vi.stubGlobal("fetch", fetch);
- vi.stubGlobal("WebSocket", FakeSocket);
- const events = new NotebookEvents(createNotebookTransport(chosen));
- await vi.waitFor(() =>
- expect(
- {
- idle:
- events.status === "connected" && !wasm.consumer.mock.calls.length,
- wasm: wasm.consumer.mock.calls.length === 1,
- fetch: fetch.mock.calls.length === 1,
- socket: FakeSocket.opened.length === 1,
- }[expected],
- ).toBe(true),
- );
- events.close();
- });
-});
diff --git a/frontend/src/core/websocket/transports/notebook.ts b/frontend/src/core/websocket/transports/notebook.ts
index aa5ce9c85d..aa728a3fca 100644
--- a/frontend/src/core/websocket/transports/notebook.ts
+++ b/frontend/src/core/websocket/transports/notebook.ts
@@ -7,8 +7,6 @@ import {
type StreamUrl,
} from "@marimo-team/client";
import { jsonParseWithSpecialChar } from "@/utils/json/json-parser";
-import { PyodideBridge } from "../../wasm/bridge";
-import { isWasm } from "../../wasm/utils";
import { classifyCloseEvent } from "../connection-state";
/** The server can be slow to accept when many notebooks are open. */
@@ -40,6 +38,19 @@ async function resolve(url: StreamUrl): Promise<URL | undefined> {
}
}
+/** Send each request with the runtime's headers, read before each request. */
+export function withHeaders(
+ headers: () => Record<string, string>,
+): typeof globalThis.fetch {
+ return (input, init) => {
+ const sent = new Headers(init?.headers);
+ for (const [name, value] of Object.entries(headers())) {
+ sent.set(name, value);
+ }
+ return globalThis.fetch(input, { ...init, headers: sent });
+ };
+}
+
/** A resume cursor and replica belong to the session that produced them. */
function withSessionIdentity(
url: StreamUrl,
@@ -131,13 +142,7 @@ export function sessionSse(
return withSessionIdentity(url, (target) =>
sse(target, {
parseData: jsonParseWithSpecialChar,
- fetch: (input, init) => {
- const sent = new Headers(init?.headers);
- for (const [name, value] of Object.entries(headers())) {
- sent.set(name, value);
- }
- return globalThis.fetch(input, { ...init, headers: sent });
- },
+ fetch: withHeaders(headers),
stop: (frame) =>
frame.event === "close"
? stopOn(frame.data as { code?: number; reason?: string })
@@ -147,7 +152,7 @@ export function sessionSse(
}
/** A connection that opens and delivers nothing, for static notebooks. */
-const idle: NotebookTransport = ({ signal }, { open }) =>
+export const idle: NotebookTransport = ({ signal }, { open }) =>
new Promise((settle) => {
open();
signal.addEventListener("abort", () => settle(), { once: true });
@@ -183,31 +188,3 @@ export function pyodide(
signal.addEventListener("abort", () => settle(), { once: true });
});
}
-
-/** How the editor follows its notebook. */
-export interface NotebookTransportOptions {
- static: boolean;
- transportType: "websocket" | "sse";
- /** The session route, read before each connection. */
- url: StreamUrl;
- /** The runtime's headers, read before each request. */
- headers: () => Record<string, string>;
-}
-
-/** Choose the transport for the editor's notebook. */
-export function createNotebookTransport(
- options: NotebookTransportOptions,
-): NotebookTransport {
- if (options.static) {
- return idle;
- }
- if (isWasm()) {
- return pyodide((consumer) =>
- PyodideBridge.INSTANCE.attachMessageConsumer(consumer),
- );
- }
- if (options.transportType === "sse") {
- return sessionSse(options.url, options.headers);
- }
- return websocket(options.url);
-}
diff --git a/frontend/src/core/websocket/useNotebookClient.ts b/frontend/src/core/websocket/useNotebookClient.ts
index 0d894f2a64..472fac6fde 100644
--- a/frontend/src/core/websocket/useNotebookClient.ts
+++ b/frontend/src/core/websocket/useNotebookClient.ts
@@ -13,12 +13,9 @@ import {
type NotebookClient,
} from "../host/notebook-client";
import { notebookClientAtom } from "./state";
-import {
- createNotebookTransport,
- type NotebookTransportOptions,
-} from "./transports/notebook";
+import { createEditorBackend, type EditorBackendOptions } from "./backend";
-type Options = Omit<NotebookTransportOptions, "url"> & {
+type Options = Omit<EditorBackendOptions, "url"> & {
/** The session route, read before each connection. */
url: () => string;
/** Wait until the host can accept a connection. */
@@ -33,6 +30,7 @@ export function useNotebookClient(options: Options): NotebookClient {
const controller = useMemo(() => createNotebookClient(store), [store]);
const url = useEvent(options.url);
const headers = useEvent(options.headers);
+ const notebookUrl = useEvent(options.notebookUrl);
const waitUntilReady = useEvent(options.waitUntilReady);
const checkHealth = useEvent(options.checkHealth);
const onNotification = useEvent(options.onNotification);
@@ -42,7 +40,7 @@ export function useNotebookClient(options: Options): NotebookClient {
let needsInitialReadiness = true;
store.set(notebookClientAtom, controller.client);
controller.connect({
- transport: createNotebookTransport({
+ backend: createEditorBackend({
static: isStatic,
transportType,
url: async () => {
@@ -60,6 +58,7 @@ export function useNotebookClient(options: Options): NotebookClient {
return url();
},
headers,
+ notebookUrl,
}),
signal: lifetime.signal,
checkHealth,
@@ -80,6 +79,7 @@ export function useNotebookClient(options: Options): NotebookClient {
transportType,
url,
headers,
+ notebookUrl,
waitUntilReady,
checkHealth,
onNotification,
diff --git a/frontend/src/core/websocket/useNotebookSession.tsx b/frontend/src/core/websocket/useNotebookSession.tsx
index 41f56b9ec3..806684fdd4 100644
--- a/frontend/src/core/websocket/useNotebookSession.tsx
+++ b/frontend/src/core/websocket/useNotebookSession.tsx
@@ -75,7 +75,6 @@ import {
import { useStorageActions } from "../storage/state";
import { useVariablesActions } from "../variables/state";
import type { VariableName } from "../variables/types";
-import { isWasm } from "../wasm/utils";
import { WebSocketClosedReason, ConnectionState } from "./types";
const SUPPORTS_LAZY_KERNELS = true;
@@ -418,8 +417,10 @@ export function useNotebookSession(opts: {
: runtimeManager.getWsURL(sessionId).toString(),
// SSE uses headers for auth. WebSockets carry the token in the URL.
headers: () => runtimeManager.headers(),
+ notebookUrl: (notebookId) => runtimeManager.getNotebookURL(notebookId),
+ // Only the host's transports read the URL, so static and WASM never wait.
waitUntilReady: async () => {
- if (!isStaticNotebook() && !isWasm() && !runtimeManager.isSameOrigin) {
+ if (!runtimeManager.isSameOrigin) {
await runtimeManager.waitForHealthy();
}
},