Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

Own the notebook connection lifecycle in the client (#11508)

Trevor Manzf6f4bf2bc065
diff --git a/frontend/src/components/editor/chrome/wrapper/__tests__/attachment-status.test.tsx b/frontend/src/components/editor/chrome/wrapper/__tests__/attachment-status.test.tsx
index 2a025bf827..83ec8ad3f5 100644
--- a/frontend/src/components/editor/chrome/wrapper/__tests__/attachment-status.test.tsx
+++ b/frontend/src/components/editor/chrome/wrapper/__tests__/attachment-status.test.tsx
@@ -46,7 +46,7 @@ function renderStatus(attachments: Attachment[] = [AGENT], preview = true) {
store.set(connectionAtom, { state: ConnectionState.OPEN });
store.set(pairConfigAtom, { ...PAIR_CONFIG, hostEnabled: preview });
store.set(notebookClientAtom, {
- ...createNotebookClient(store).client,
+ ...createNotebookClient(store),
connectionAtom: atom({ state: ConnectionState.OPEN }),
attachmentsAtom,
});
diff --git a/frontend/src/components/editor/errors/__tests__/send-error-report-button.test.tsx b/frontend/src/components/editor/errors/__tests__/send-error-report-button.test.tsx
index d8681ae10f..4e16582982 100644
--- a/frontend/src/components/editor/errors/__tests__/send-error-report-button.test.tsx
+++ b/frontend/src/components/editor/errors/__tests__/send-error-report-button.test.tsx
@@ -98,7 +98,7 @@ function renderButton({
store.set(connectionAtom, { state: ConnectionState.OPEN });
store.set(pairConfigAtom, { ...PAIR_CONFIG, hostEnabled: preview });
store.set(notebookClientAtom, {
- ...createNotebookClient(store).client,
+ ...createNotebookClient(store),
connectionAtom: atom({ state: ConnectionState.OPEN }),
attachmentsAtom,
});
diff --git a/frontend/src/core/host/__tests__/fixtures.ts b/frontend/src/core/host/__tests__/fixtures.ts
index af23252aa8..783f176672 100644
--- a/frontend/src/core/host/__tests__/fixtures.ts
+++ b/frontend/src/core/host/__tests__/fixtures.ts
@@ -2,7 +2,37 @@
import NodeFs from "node:fs";
import NodeUrl from "node:url";
+import type { NotebookTransport } from "@marimo-team/client";
import * as Protocol from "@marimo-team/client/protocol";
+import { vi } from "vitest";
+import type { NotebookBackend } from "../backend";
+
+type Commands = ReturnType<NotebookBackend["notebook"]>;
+
+/** A backend command, with the notebook it was sent to. */
+export type FakeEdit = (
+ notebookId: Protocol.NotebookId,
+ ...args: Parameters<Commands["edit"]>
+) => ReturnType<Commands["edit"]>;
+
+/** A backend over `transport` whose edits go to `edit`. */
+export function fakeBackend({
+ transport = async () => undefined,
+ edit = vi.fn<FakeEdit>(),
+ checkHealth,
+}: {
+ transport?: NotebookTransport;
+ edit?: FakeEdit;
+ checkHealth?: () => Promise<boolean>;
+} = {}): NotebookBackend {
+ return {
+ transport,
+ notebook: (notebookId) => ({
+ edit: (...args) => edit(notebookId, ...args),
+ }),
+ checkHealth,
+ };
+}
/** Read the protocol's portable examples as transport messages. */
export function fixtureMessages(name: string) {
diff --git a/frontend/src/core/host/__tests__/notebook-client.test.ts b/frontend/src/core/host/__tests__/notebook-client.test.ts
index ecaf9eee38..d9ce5441f7 100644
--- a/frontend/src/core/host/__tests__/notebook-client.test.ts
+++ b/frontend/src/core/host/__tests__/notebook-client.test.ts
@@ -3,13 +3,17 @@
import { type NotebookTransport, StreamStopped } from "@marimo-team/client";
import { createStore } from "jotai";
-import { afterEach, describe, expect, it, vi } from "vitest";
+import { afterEach, describe, expect, it, onTestFinished, 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 } from "../notebook-client";
-import { fixtureEvents, fixtureMessages } from "./fixtures";
+import {
+ type FakeEdit,
+ fakeBackend,
+ fixtureEvents,
+ fixtureMessages,
+} from "./fixtures";
/** One connection the fake transport opened. */
interface Attempt {
@@ -23,14 +27,7 @@ interface Attempt {
stop(status?: ConnectionStatus): void;
}
-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>()) {
+function setup(edit = vi.fn<FakeEdit>()) {
const attempts: Attempt[] = [];
const transport: NotebookTransport = ({ cursor, signal }, handlers) =>
new Promise((resolve, reject) => {
@@ -48,19 +45,15 @@ function setup(edit = vi.fn<Edit>()) {
const onNotification = vi.fn();
const checkHealth = vi.fn(async () => true);
const store = createStore();
- 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({
- backend,
- signal,
- checkHealth,
+ const backend = fakeBackend({ transport, edit, checkHealth });
+ const client = createNotebookClient(store);
+ /** Follow the backend until `signal` aborts. */
+ const connect = (signal: AbortSignal) => {
+ const disconnect = client.connect(backend, {
onNotification: (notification) => onNotification({ data: notification }),
});
+ signal.addEventListener("abort", disconnect, { once: true });
+ };
let next = 0;
/** Wait for the next connection, and open it. */
const opened = async () => {
@@ -71,6 +64,7 @@ function setup(edit = vi.fn<Edit>()) {
};
return {
attempts,
+ backend,
client,
connect,
onNotification,
@@ -110,8 +104,25 @@ const notebook = {
};
describe("NotebookClient lifetime", () => {
+ it("ends the previous connection when it connects again", async () => {
+ const { attempts, backend, client, opened, store } = setup();
+ const first = client.connect(backend, { onNotification: vi.fn() });
+ const { receive } = await opened();
+ fixtureMessages("notebook-events.sse").forEach(receive);
+ const second = client.connect(backend, { onNotification: vi.fn() });
+ onTestFinished(second);
+ expect(attempts[0].signal.aborted).toBe(true);
+ expect(store.get(client.documentAtom)).toBeNull();
+ await opened();
+ first();
+ expect(attempts[1].signal.aborted).toBe(false);
+ expect(store.get(client.connectionAtom)).toEqual({
+ state: ConnectionState.OPEN,
+ });
+ });
+
it("keeps an edit's target and request identity across a stream reset", async () => {
- const edit = vi.fn<Edit>().mockResolvedValue({
+ const edit = vi.fn<FakeEdit>().mockResolvedValue({
ok: false,
status: 409,
problem: { type: "conflict", title: "conflict", status: 409 },
diff --git a/frontend/src/core/host/backend.ts b/frontend/src/core/host/backend.ts
index 58f20fdb57..bc42f2bcf9 100644
--- a/frontend/src/core/host/backend.ts
+++ b/frontend/src/core/host/backend.ts
@@ -12,4 +12,6 @@ export interface NotebookBackend {
* Method presence is not permission. The notebook advertises its operations.
*/
notebook(id: NotebookId): Pick<NotebookClient, "edit">;
+ /** Whether the host is reachable before an explicit reconnect. Absent means always. */
+ checkHealth?(): Promise<boolean>;
}
diff --git a/frontend/src/core/host/notebook-client.ts b/frontend/src/core/host/notebook-client.ts
index 1d52404352..30b7ff2894 100644
--- a/frontend/src/core/host/notebook-client.ts
+++ b/frontend/src/core/host/notebook-client.ts
@@ -56,22 +56,23 @@ export interface NotebookClient {
): Promise<Result<EditResponseOutput>>;
/** Live attachments, empty until the stream is ready or while disconnected. */
readonly attachmentsAtom: Atom<readonly Attachment[]>;
- /** Attempt to restore a closed connection after checking host health. */
+ /**
+ * Follow a backend, replacing any current connection.
+ *
+ * The returned function ends this connection and clears the client's state.
+ * It does nothing once another connection has replaced this one.
+ */
+ connect(
+ backend: NotebookBackend,
+ options: {
+ /** Handle a native marimo notification. Its payload has not been validated. */
+ onNotification: (notification: unknown) => void;
+ },
+ ): () => void;
+ /** Restore the current connection after its stream closed, if the host is healthy. */
reconnect(): Promise<void>;
}
-/** The backend and application callbacks needed to follow a notebook. */
-export interface NotebookConnection {
- /** 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. */
- checkHealth: () => Promise<boolean>;
- /** Handle a native marimo notification. Its payload has not been validated. */
- onNotification: (notification: unknown) => void;
-}
-
const disconnected = {
state: ConnectionState.CLOSED,
code: ConnectionClosedReason.KERNEL_DISCONNECTED,
@@ -104,7 +105,9 @@ function statusAfter(error: unknown): ConnectionStatus {
}
/** Create a client without opening a connection. */
-export function createNotebookClient(store: ReturnType<typeof createStore>) {
+export function createNotebookClient(
+ store: ReturnType<typeof createStore>,
+): NotebookClient {
// `useNotebookSession` copies this into the editor's shared `connectionAtom`,
// which gates features until MO-8051 derives availability separately.
const connectionAtom = atom<ConnectionStatus>({
@@ -130,9 +133,22 @@ export function createNotebookClient(store: ReturnType<typeof createStore>) {
? get(streamAtom).resources.attachments
: attachments.initial,
);
- let reconnect: (() => Promise<void>) | undefined;
let backend: NotebookBackend | undefined;
- const client: NotebookClient = {
+ /** The connection this client follows. Connecting again ends it. */
+ let current: { end(): void; reconnect(): Promise<void> } | undefined;
+
+ function setStatus(status: ConnectionStatus) {
+ store.set(readyAtom, false);
+ store.set(connectionAtom, status);
+ }
+
+ /** Drop what the stream reported and show `status`. */
+ function clear(status: ConnectionStatus) {
+ store.set(streamAtom, reducer.initial);
+ setStatus(status);
+ }
+
+ return {
connectionAtom,
notebookAtom,
documentAtom,
@@ -156,23 +172,18 @@ export function createNotebookClient(store: ReturnType<typeof createStore>) {
return backend.notebook(notebookId).edit(changes, options);
},
attachmentsAtom,
- reconnect: async () => reconnect?.(),
+ connect,
+ reconnect: async () => current?.reconnect(),
};
- function setStatus(status: ConnectionStatus) {
- store.set(readyAtom, false);
- store.set(connectionAtom, status);
- }
-
- function connect({
- backend: connected,
- signal,
- checkHealth,
- onNotification,
- }: NotebookConnection) {
- if (signal.aborted) {
- return;
- }
+ function connect(
+ connected: NotebookBackend,
+ { onNotification }: { onNotification: (notification: unknown) => void },
+ ) {
+ current?.end();
+ const lifetime = new AbortController();
+ const { signal } = lifetime;
+ const checkHealth = connected.checkHealth ?? (async () => true);
backend = connected;
const { transport } = connected;
let events: NotebookEvents<(typeof TYPES)[number]> | undefined;
@@ -222,8 +233,7 @@ export function createNotebookClient(store: ReturnType<typeof createStore>) {
source.close();
// The cursor can already include an event the replica rejected.
resumable = false;
- store.set(streamAtom, reducer.initial);
- setStatus(malformed);
+ clear(malformed);
}
function apply(source: NotebookEvents<string>, event: EditorEvent) {
@@ -250,7 +260,7 @@ export function createNotebookClient(store: ReturnType<typeof createStore>) {
}
}
- reconnect = async () => {
+ const reconnect = async () => {
if (signal.aborted || checkingHealth || events?.status !== "closed") {
return;
}
@@ -276,22 +286,23 @@ export function createNotebookClient(store: ReturnType<typeof createStore>) {
}
};
- signal.addEventListener(
- "abort",
- () => {
- reconnect = undefined;
- if (backend === connected) {
+ const connection = {
+ end: () => {
+ if (signal.aborted) {
+ return;
+ }
+ lifetime.abort();
+ if (current === connection) {
+ current = undefined;
backend = undefined;
}
- store.set(streamAtom, reducer.initial);
- setStatus({ state: ConnectionState.NOT_STARTED });
+ clear({ state: ConnectionState.NOT_STARTED });
},
- { once: true },
- );
-
+ reconnect,
+ };
+ current = connection;
setStatus({ state: ConnectionState.CONNECTING });
follow();
+ return connection.end;
}
-
- return { client, connect };
}
diff --git a/frontend/src/core/websocket/__tests__/backend.test.ts b/frontend/src/core/websocket/__tests__/backend.test.ts
index e029f7f714..af0ca8860a 100644
--- a/frontend/src/core/websocket/__tests__/backend.test.ts
+++ b/frontend/src/core/websocket/__tests__/backend.test.ts
@@ -1,7 +1,11 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { NotebookEvents } from "@marimo-team/client";
-import { afterEach, describe, expect, it, vi } from "vitest";
+import { createStore } from "jotai/vanilla";
+import { afterEach, describe, expect, it, onTestFinished, vi } from "vitest";
+import { Deferred } from "@/utils/Deferred";
+import { ConnectionState } from "../../host/connection";
+import { createNotebookClient } from "../../host/notebook-client";
import { createEditorBackend } from "../backend";
const wasm = vi.hoisted(() => ({ enabled: false, consumer: vi.fn() }));
@@ -16,16 +20,34 @@ afterEach(() => {
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}`),
- };
+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}`),
+ waitUntilReady: async () => undefined,
+ checkHealth: async () => true,
+};
+
+/** Record each socket the transport opens. They never connect. */
+function sockets() {
+ const opened: string[] = [];
+ vi.stubGlobal(
+ "WebSocket",
+ class extends EventTarget {
+ public constructor(url: URL) {
+ super();
+ opened.push(String(url));
+ }
+ public close() {}
+ },
+ );
+ return opened;
+}
+describe("createEditorBackend", () => {
it.each([
["a static notebook", { ...options, static: true }, "idle"],
["WASM", options, "wasm"],
@@ -34,18 +56,8 @@ describe("createEditorBackend", () => {
] as const)("follows %s", async (_name, chosen, expected) => {
wasm.enabled = expected === "wasm";
const fetch = vi.fn(() => new Promise<Response>(() => undefined));
- const socket = vi.fn();
+ const opened = sockets();
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(
@@ -54,7 +66,7 @@ describe("createEditorBackend", () => {
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,
+ socket: opened.length === 1,
}[expected],
).toBe(true),
);
@@ -109,3 +121,80 @@ describe("createEditorBackend", () => {
expect(fetch).not.toHaveBeenCalled();
});
});
+
+describe("the session backend's startup", () => {
+ it.each([true, false])(
+ "rechecks health after failed startup (healthy: %s)",
+ async (healthy) => {
+ const opened = sockets();
+ const waitUntilReady = vi
+ .fn()
+ .mockRejectedValue(new Error("Startup gave up"));
+ const checkHealth = vi.fn().mockResolvedValue(healthy);
+ const store = createStore();
+ const client = createNotebookClient(store);
+ onTestFinished(
+ client.connect(
+ createEditorBackend({ ...options, waitUntilReady, checkHealth }),
+ { onNotification: vi.fn() },
+ ),
+ );
+ await vi.waitFor(() =>
+ expect(store.get(client.connectionAtom).state).toBe(
+ ConnectionState.CLOSED,
+ ),
+ );
+
+ await client.reconnect();
+ await vi.waitFor(() => expect(opened).toHaveLength(healthy ? 1 : 0));
+ expect({
+ healthChecks: checkHealth.mock.calls.length,
+ startupWaits: waitUntilReady.mock.calls.length,
+ state: store.get(client.connectionAtom).state,
+ }).toEqual({
+ healthChecks: 1,
+ startupWaits: 1,
+ state: healthy ? ConnectionState.CONNECTING : ConnectionState.CLOSED,
+ });
+ },
+ );
+
+ it("shares one startup wait across connections", async () => {
+ const opened = sockets();
+ const ready = new Deferred<void>();
+ const waitUntilReady = vi.fn(() => ready.promise);
+ const backend = createEditorBackend({ ...options, waitUntilReady });
+ const client = createNotebookClient(createStore());
+ // Strict Mode connects, disconnects, and connects again.
+ client.connect(backend, { onNotification: vi.fn() })();
+ onTestFinished(client.connect(backend, { onNotification: vi.fn() }));
+ await Promise.resolve();
+ expect(opened).toEqual([]);
+
+ ready.resolve();
+ await vi.waitFor(() => expect(opened).toHaveLength(1));
+ expect(waitUntilReady).toHaveBeenCalledOnce();
+ });
+
+ it("opens nothing for a connection that ended during startup", async () => {
+ const opened = sockets();
+ const ready = new Deferred<void>();
+ const store = createStore();
+ const client = createNotebookClient(store);
+ const disconnect = client.connect(
+ createEditorBackend({ ...options, waitUntilReady: () => ready.promise }),
+ { onNotification: vi.fn() },
+ );
+ expect(store.get(client.connectionAtom)).toEqual({
+ state: ConnectionState.CONNECTING,
+ });
+ disconnect();
+ ready.resolve();
+ await ready.promise;
+ await Promise.resolve();
+ expect(opened).toEqual([]);
+ expect(store.get(client.connectionAtom)).toEqual({
+ state: ConnectionState.NOT_STARTED,
+ });
+ });
+});
diff --git a/frontend/src/core/websocket/__tests__/useNotebookClient.hook.test.tsx b/frontend/src/core/websocket/__tests__/useNotebookClient.hook.test.tsx
index 77f1c9f769..f793cb3f79 100644
--- a/frontend/src/core/websocket/__tests__/useNotebookClient.hook.test.tsx
+++ b/frontend/src/core/websocket/__tests__/useNotebookClient.hook.test.tsx
@@ -7,20 +7,19 @@ import type { PropsWithChildren } from "react";
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 type { NotebookBackend } from "../../host/backend";
import { createEditorBackend } from "../backend";
import { useNotebookClient } from "../useNotebookClient";
-import { fixtureMessages } from "../../host/__tests__/fixtures";
+import { fakeBackend, fixtureMessages } from "../../host/__tests__/fixtures";
import { agentAttachmentsAtom } from "../../attachments/state";
import { notebookClientAtom } from "../state";
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 host-framed native notification. */
+const reconnected = {
+ event: "marimo",
+ data: { marimo: { op: "reconnected" } },
+};
/** A transport whose connections the test drives. */
function makeTransport() {
@@ -38,21 +37,11 @@ function makeTransport() {
transport,
opened,
/** Open the latest connection and deliver a host-framed notification. */
- notify: () =>
- opened.at(-1)?.receive({
- event: "marimo",
- data: { marimo: { op: "reconnected" } },
- }),
+ notify: () => opened.at(-1)?.receive(reconnected),
};
}
-function setup(
- strict = false,
- readiness: {
- waitUntilReady?: () => Promise<void>;
- checkHealth?: () => Promise<boolean>;
- } = {},
-) {
+function setup(strict = false) {
const store = createStore();
const options = {
static: false,
@@ -63,7 +52,6 @@ function setup(
waitUntilReady: async () => undefined,
checkHealth: async () => true,
onNotification: vi.fn(),
- ...readiness,
};
const wrapper = ({ children }: PropsWithChildren) => (
<Provider store={store}>{children}</Provider>
@@ -81,83 +69,11 @@ beforeEach(() => {
});
describe("useNotebookClient", () => {
- it.each([true, false])(
- "rechecks health after failed startup (healthy: %s)",
- async (healthy) => {
- const fake = makeTransport();
- 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()
- .mockRejectedValue(new Error("Startup gave up"));
- const checkHealth = vi.fn().mockResolvedValue(healthy);
- const { result, store, unmount } = setup(false, {
- waitUntilReady,
- checkHealth,
- });
- await act(async () => Promise.resolve());
- expect(store.get(result.current.connectionAtom).state).toBe(
- ConnectionState.CLOSED,
- );
-
- await act(async () => result.current.reconnect());
- expect({
- healthChecks: checkHealth.mock.calls.length,
- initialWaits: waitUntilReady.mock.calls.length,
- connections: fake.opened.length,
- state: store.get(result.current.connectionAtom).state,
- }).toEqual({
- healthChecks: 1,
- initialWaits: 1,
- connections: healthy ? 1 : 0,
- state: healthy ? ConnectionState.CONNECTING : ConnectionState.CLOSED,
- });
- act(() => fake.opened.at(-1)?.open());
- expect(store.get(result.current.connectionAtom).state).toBe(
- healthy ? ConnectionState.OPEN : ConnectionState.CLOSED,
- );
- unmount();
- },
- );
-
- it("waits for initial readiness without reviving an unmounted connection", async () => {
- const ready = new Deferred<void>();
- const resolvedUrl = vi.fn();
- vi.mocked(createEditorBackend).mockImplementation(({ url }) =>
- backend(async () => {
- if (typeof url === "function") {
- await url();
- resolvedUrl();
- }
- }),
- );
- const { result, store, unmount } = setup(false, {
- waitUntilReady: () => ready.promise,
- });
- await act(async () => Promise.resolve());
- expect(resolvedUrl).not.toHaveBeenCalled();
- expect(store.get(result.current.connectionAtom)).toEqual({
- state: ConnectionState.CONNECTING,
- });
- unmount();
- await act(async () => ready.resolve());
- expect(store.get(result.current.connectionAtom)).toEqual({
- state: ConnectionState.NOT_STARTED,
- });
- expect(store.get(notebookClientAtom)).toBeNull();
- });
-
it("exposes host presence to the UI without waiting for kernel-ready", async () => {
const fake = makeTransport();
- vi.mocked(createEditorBackend).mockReturnValue(backend(fake.transport));
+ vi.mocked(createEditorBackend).mockReturnValue(
+ fakeBackend({ transport: fake.transport }),
+ );
const { result, store, unmount } = setup();
await act(async () => Promise.resolve());
expect(store.get(notebookClientAtom)).toBe(result.current);
@@ -182,7 +98,9 @@ describe("useNotebookClient", () => {
it("uses current callbacks and URL providers without reconnecting on a rerender", async () => {
const fake = makeTransport();
- vi.mocked(createEditorBackend).mockReturnValue(backend(fake.transport));
+ vi.mocked(createEditorBackend).mockReturnValue(
+ fakeBackend({ transport: fake.transport }),
+ );
const { rerender, options, unmount } = setup();
await act(async () => Promise.resolve());
const onNotification = vi.fn();
@@ -192,37 +110,32 @@ describe("useNotebookClient", () => {
expect(onNotification).toHaveBeenCalledExactlyOnceWith({
data: { op: "reconnected" },
});
- expect(createEditorBackend).toHaveBeenCalledOnce();
const [{ url }] = vi.mocked(createEditorBackend).mock.calls[0];
- expect(String(await (url as () => Promise<string>)())).toBe(
- "ws://redirected/ws",
- );
+ expect(url()).toBe("ws://redirected/ws");
+ expect(fake.opened).toHaveLength(1);
unmount();
});
- it("closes every stream under Strict Mode and only follows the active lifetime", async () => {
- const fakes: ReturnType<typeof makeTransport>[] = [];
- vi.mocked(createEditorBackend).mockImplementation(() => {
- const next = makeTransport();
- fakes.push(next);
- return backend(next.transport);
- });
+ it("follows only the active connection under Strict Mode", async () => {
+ const fake = makeTransport();
+ vi.mocked(createEditorBackend).mockReturnValue(
+ fakeBackend({ transport: fake.transport }),
+ );
const { result, store, options, unmount } = setup(true);
await act(async () => Promise.resolve());
- expect(fakes).toHaveLength(2);
- expect(fakes[0].opened.every((attempt) => attempt.signal.aborted)).toBe(
- true,
- );
- const [active] = fakes[1].opened;
+ const live = fake.opened.filter((attempt) => !attempt.signal.aborted);
+ expect(live).toHaveLength(1);
+ const [active] = live;
act(() => active.open());
expect(store.get(result.current.connectionAtom)).toEqual({
state: ConnectionState.OPEN,
});
- act(() => fakes.forEach((fake) => fake.notify()));
+ act(() => fake.opened.forEach((attempt) => attempt.receive(reconnected)));
expect(options.onNotification).toHaveBeenCalledOnce();
unmount();
expect(active.signal.aborted).toBe(true);
+ const attempts = fake.opened.length;
await result.current.reconnect();
- expect(fakes[1].opened).toHaveLength(1);
+ expect(fake.opened).toHaveLength(attempts);
});
});
diff --git a/frontend/src/core/websocket/__tests__/useNotebookSession.hook.test.tsx b/frontend/src/core/websocket/__tests__/useNotebookSession.hook.test.tsx
index 6eca0f212a..5165eeef2e 100644
--- a/frontend/src/core/websocket/__tests__/useNotebookSession.hook.test.tsx
+++ b/frontend/src/core/websocket/__tests__/useNotebookSession.hook.test.tsx
@@ -52,6 +52,7 @@ import { RuntimeManager } from "../../runtime/runtime";
import { WebSocketClosedReason, ConnectionState } from "../types";
import { classifyCloseEvent } from "../connection-state";
import { createEditorBackend } from "../backend";
+import { fakeBackend } from "../../host/__tests__/fixtures";
import { useNotebookSession } from "../useNotebookSession";
import { type NotebookTransport, StreamStopped } from "@marimo-team/client";
@@ -85,10 +86,9 @@ type FakeTransport = ReturnType<typeof makeTransport>;
/** Use a fake transport for the next session the hook follows. */
function withTransport(fake: FakeTransport = makeTransport()) {
- vi.mocked(createEditorBackend).mockReturnValue({
- transport: fake.transport,
- notebook: () => ({ edit: vi.fn() }),
- });
+ vi.mocked(createEditorBackend).mockImplementation(({ checkHealth }) =>
+ fakeBackend({ transport: fake.transport, checkHealth }),
+ );
return fake;
}
diff --git a/frontend/src/core/websocket/backend.ts b/frontend/src/core/websocket/backend.ts
index f69bc28286..3f62bb7192 100644
--- a/frontend/src/core/websocket/backend.ts
+++ b/frontend/src/core/websocket/backend.ts
@@ -1,6 +1,6 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import { NotebookClient, type StreamUrl } from "@marimo-team/client";
+import { NotebookClient, StreamStopped } from "@marimo-team/client";
import type { NotebookId } from "@marimo-team/client/protocol";
import type { NotebookBackend } from "../host/backend";
import { PyodideBridge } from "../wasm/bridge";
@@ -18,11 +18,45 @@ export interface EditorBackendOptions {
static: boolean;
transportType: "websocket" | "sse";
/** The session route, read before each connection. */
- url: StreamUrl;
+ url: () => string;
/** 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;
+ /** Wait until the host can accept the first connection. */
+ waitUntilReady: () => Promise<void>;
+ /** Whether the host is reachable before an explicit reconnect. */
+ checkHealth: () => Promise<boolean>;
+}
+
+/**
+ * Read the session route once the host has started.
+ *
+ * Every connection waits for the same startup. Once it settles, even by
+ * giving up, connections read the route directly. An explicit reconnect
+ * checks the host's health instead.
+ */
+function afterStartup({
+ url,
+ waitUntilReady,
+}: Pick<EditorBackendOptions, "url" | "waitUntilReady">) {
+ let startup: Promise<void> | undefined;
+ let settled = false;
+ return async () => {
+ if (!settled) {
+ startup ??= waitUntilReady().finally(() => {
+ settled = true;
+ });
+ try {
+ await startup;
+ } catch (error) {
+ throw new StreamStopped("Healthy connection never made", {
+ cause: error,
+ });
+ }
+ }
+ return url();
+ };
}
/** Commands for a notebook the editor cannot change through its backend. */
@@ -55,14 +89,16 @@ export function createEditorBackend(
notebook: uneditable,
};
}
+ const url = afterStartup(options);
return {
transport:
options.transportType === "sse"
- ? sessionSse(options.url, options.headers)
- : websocket(options.url),
+ ? sessionSse(url, options.headers)
+ : websocket(url),
notebook: (id) =>
new NotebookClient(options.notebookUrl(id), {
fetch: withHeaders(options.headers),
}),
+ checkHealth: options.checkHealth,
};
}
diff --git a/frontend/src/core/websocket/transports/__tests__/notebook.test.ts b/frontend/src/core/websocket/transports/__tests__/notebook.test.ts
index c9d09d57f6..39b8f3be76 100644
--- a/frontend/src/core/websocket/transports/__tests__/notebook.test.ts
+++ b/frontend/src/core/websocket/transports/__tests__/notebook.test.ts
@@ -8,7 +8,7 @@ import {
import { createStore } from "jotai/vanilla";
import { afterEach, describe, expect, it, onTestFinished, vi } from "vitest";
import { createNotebookClient } from "../../../host/notebook-client";
-import { fixtureMessages } from "../../../host/__tests__/fixtures";
+import { fakeBackend, fixtureMessages } from "../../../host/__tests__/fixtures";
import { ConnectionState } from "../../../host/connection";
import { Deferred } from "@/utils/Deferred";
import { pyodide, sessionSse, websocket } from "../notebook";
@@ -76,7 +76,7 @@ function network(transportType: "websocket" | "sse", url: StreamUrl) {
transportType === "websocket"
? websocket(url)
: sessionSse(url, () => ({}));
- const backend = { transport, notebook: () => ({ edit: vi.fn() }) };
+ const backend = fakeBackend({ transport });
let index = 0;
return {
backend,
@@ -296,15 +296,10 @@ describe.each(["websocket", "sse"] as const)(
const url = vi.fn(() => target);
const connection = network(transportType, url);
const store = createStore();
- const { client, connect } = createNotebookClient(store);
- const lifetime = new AbortController();
- onTestFinished(() => lifetime.abort());
- connect({
- backend: connection.backend,
- signal: lifetime.signal,
- checkHealth: async () => true,
- onNotification: vi.fn(),
- });
+ const client = createNotebookClient(store);
+ onTestFinished(
+ client.connect(connection.backend, { onNotification: vi.fn() }),
+ );
const first = await connection.opened();
const snapshot = fixtureMessages("notebook-events.sse");
snapshot.forEach(first.receive);
@@ -363,15 +358,10 @@ describe.each(["websocket", "sse"] as const)(
let target = `${base}?session_id=s1&file=a.py&access_token=a`;
const connection = network(transportType, () => target);
const store = createStore();
- const { client, connect } = createNotebookClient(store);
- const lifetime = new AbortController();
- onTestFinished(() => lifetime.abort());
- connect({
- backend: connection.backend,
- signal: lifetime.signal,
- checkHealth: async () => true,
- onNotification: vi.fn(),
- });
+ const client = createNotebookClient(store);
+ onTestFinished(
+ client.connect(connection.backend, { onNotification: vi.fn() }),
+ );
const first = await connection.opened();
fixtureMessages("notebook-events.sse").forEach(first.receive);
await vi.waitFor(() =>
diff --git a/frontend/src/core/websocket/useNotebookClient.ts b/frontend/src/core/websocket/useNotebookClient.ts
index 472fac6fde..4762b1701d 100644
--- a/frontend/src/core/websocket/useNotebookClient.ts
+++ b/frontend/src/core/websocket/useNotebookClient.ts
@@ -1,6 +1,5 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import { StreamStopped } from "@marimo-team/client";
import { useStore } from "jotai";
import { useEffect, useMemo } from "react";
import useEvent from "react-use-event-hook";
@@ -15,75 +14,57 @@ import {
import { notebookClientAtom } from "./state";
import { createEditorBackend, type EditorBackendOptions } from "./backend";
-type Options = Omit<EditorBackendOptions, "url"> & {
- /** The session route, read before each connection. */
- url: () => string;
- /** Wait until the host can accept a connection. */
- waitUntilReady: () => Promise<void>;
- checkHealth: () => Promise<boolean>;
+type Options = EditorBackendOptions & {
onNotification: (notification: NotificationPayload) => void;
};
export function useNotebookClient(options: Options): NotebookClient {
const store = useStore();
const { static: isStatic, transportType } = options;
- const controller = useMemo(() => createNotebookClient(store), [store]);
+ const client = 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);
-
- useEffect(() => {
- const lifetime = new AbortController();
- let needsInitialReadiness = true;
- store.set(notebookClientAtom, controller.client);
- controller.connect({
- backend: createEditorBackend({
+ // Opens nothing until the client follows it.
+ const backend = useMemo(
+ () =>
+ createEditorBackend({
static: isStatic,
transportType,
- url: async () => {
- if (needsInitialReadiness) {
- // Explicit retries check current health, even if startup failed.
- needsInitialReadiness = false;
- try {
- await waitUntilReady();
- } catch (error) {
- throw new StreamStopped("Healthy connection never made", {
- cause: error,
- });
- }
- }
- return url();
- },
+ url,
headers,
notebookUrl,
+ waitUntilReady,
+ checkHealth,
}),
- signal: lifetime.signal,
+ [
+ isStatic,
+ transportType,
+ url,
+ headers,
+ notebookUrl,
+ waitUntilReady,
checkHealth,
+ ],
+ );
+
+ useEffect(() => {
+ store.set(notebookClientAtom, client);
+ const disconnect = client.connect(backend, {
// The host validates the envelope, not the native notification contents.
onNotification: (notification) =>
onNotification({ data: notification as NotificationMessage }),
});
return () => {
- lifetime.abort();
- if (store.get(notebookClientAtom) === controller.client) {
+ disconnect();
+ if (store.get(notebookClientAtom) === client) {
store.set(notebookClientAtom, null);
}
};
- }, [
- controller,
- store,
- isStatic,
- transportType,
- url,
- headers,
- notebookUrl,
- waitUntilReady,
- checkHealth,
- onNotification,
- ]);
+ }, [client, backend, store, onNotification]);
- return controller.client;
+ return client;
}