A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
Consume host events through `NotebookClient` (#11305)
Trevor Manz9bc92717addc
diff --git a/frontend/src/__tests__/mount.test.ts b/frontend/src/__tests__/mount.test.tsindex 72140c4b80..a708d9fc9e 100644--- a/frontend/src/__tests__/mount.test.ts+++ b/frontend/src/__tests__/mount.test.ts@@ -6,6 +6,7 @@ import { initialLayoutState, layoutStateAtom } from "@/core/layout/state";import { kioskModeAtom } from "@/core/mode";import { connectionAtom } from "@/core/network/connection";import { store } from "@/core/state/jotai";+import { runtimeConfigAtom } from "@/core/runtime/config";import { isStaticNotebook } from "@/core/static/static-state";import { ConnectionState } from "@/core/websocket/types";import { pairConfigAtom } from "@/core/config/pair";@@ -101,6 +102,25 @@ describe("mount", () => {});describe("connection state initialization", () => {+ it("passes the host notebook identity to the local runtime", () => {+ mount({ ...baseOptions, notebookId: "nb_local" }, mockElement);+ expect(store.get(runtimeConfigAtom).notebookId).toBe("nb_local");+ });++ it("uses a remote runtime's own notebook identity", () => {+ mount(+ {+ ...baseOptions,+ notebookId: "nb_local",+ runtimeConfig: [+ { url: "https://remote.example", notebookId: "nb_remote" },+ ],+ },+ mockElement,+ );+ expect(store.get(runtimeConfigAtom).notebookId).toBe("nb_remote");+ });+it("should set connection to CONNECTING when runtimeConfig has lazy=false", () => {mount({diff --git a/frontend/src/core/edit-app.tsx b/frontend/src/core/edit-app.tsxindex 67e070cf48..846b355ea1 100644--- a/frontend/src/core/edit-app.tsx+++ b/frontend/src/core/edit-app.tsx@@ -41,7 +41,7 @@ import { viewStateAtom } from "./mode";import { useRequestClient } from "./network/requests";import { useFilename } from "./saving/filename";import { lastSavedNotebookAtom } from "./saving/state";-import { useMarimoKernelConnection } from "./websocket/useMarimoKernelConnection";+import { useNotebookSession } from "./websocket/useNotebookSession";interface AppProps {/**@@ -83,7 +83,7 @@ export const EditApp: React.FC<AppProps> = ({};}, []);- const { connection, reconnect } = useMarimoKernelConnection({+ const { connection, reconnect } = useNotebookSession({autoInstantiate: userConfig.runtime.auto_instantiate,setCells: (cells, layout) => {setCells(cells);diff --git a/frontend/src/core/host/__tests__/events.test.ts b/frontend/src/core/host/__tests__/events.test.tsnew file mode 100644index 0000000000..74933638a7--- /dev/null+++ b/frontend/src/core/host/__tests__/events.test.ts@@ -0,0 +1,46 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { describe, expect, it } from "vitest";+import { z } from "zod";+import { parseNotebookEvent } from "../events";++describe("notebook messages", () => {+ it("normalizes session and host envelopes for native marimo messages", () => {+ const notification = {+ op: "variables",+ variables: [{ name: "x", value: Number.NaN }],+ };+ const host = { event: "marimo", data: { marimo: notification } };+ expect(parseNotebookEvent({ data: notification })).toEqual(host);+ expect(parseNotebookEvent({ ...host, id: "42" })).toEqual({+ ...host,+ id: "42",+ });+ });++ it("retains unknown event cursors without interpreting their payloads", () => {+ expect(+ parseNotebookEvent({ event: "future", id: "42", data: null }),+ ).toEqual({ event: "unknown", name: "future", id: "42" });+ });++ it("decodes known events outside the client's subscription filters", () => {+ const event = {+ event: "run.removed",+ id: "42",+ data: { id: "r1", time: "2026-10-19T12:00:00Z" },+ };+ expect(parseNotebookEvent(event)).toEqual(event);+ });++ it.each([+ { event: "cell", id: "42", data: { cell: { id: "c1" } } },+ { event: "run.removed", id: "42", data: {} },+ { event: "ready", data: {} },+ { event: "marimo", data: {} },+ {},+ null,+ ])("rejects malformed known messages: %j", (message) => {+ expect(() => parseNotebookEvent(message)).toThrow(z.ZodError);+ });+});diff --git a/frontend/src/core/host/__tests__/notebook-client.test.ts b/frontend/src/core/host/__tests__/notebook-client.test.tsnew file mode 100644index 0000000000..0fc964742c--- /dev/null+++ b/frontend/src/core/host/__tests__/notebook-client.test.ts@@ -0,0 +1,191 @@+/* Copyright 2026 Marimo. All rights reserved. */+// @vitest-environment jsdom++import { describe, expect, it, vi } from "vitest";+import { createStore } from "jotai";+import { ConnectionState } from "../../websocket/types";+import { Deferred } from "@/utils/Deferred";+import { jsonParseWithSpecialChar } from "@/utils/json/json-parser";+import { classifyCloseEvent } from "../../websocket/connection-state";+import { createNotebookClient } from "../notebook-client";++function setup() {+ const events = new EventTarget();+ const healthy = new Deferred<void>();+ const transport = {+ readyState: WebSocket.CLOSED,+ reconnect: vi.fn(),+ close: vi.fn(() => events.dispatchEvent(new CloseEvent("close"))),+ send: vi.fn(),+ addEventListener: events.addEventListener.bind(events),+ removeEventListener: events.removeEventListener.bind(events),+ };+ const onNotification = vi.fn();+ const checkHealth = vi.fn(async () => true);+ const store = createStore();+ const controller = createNotebookClient(store);+ const client = controller.client;+ const connect = (signal: AbortSignal) =>+ controller.connect({+ createTransport: () => transport,+ url: () => "ws://localhost/ws",+ messageFormat: "host",+ signal,+ waitUntilReady: () => healthy.promise,+ checkHealth,+ onNotification: (notification) => onNotification({ data: notification }),+ onMessageError: vi.fn(),+ decodeJson: jsonParseWithSpecialChar,+ classifyClose: classifyCloseEvent,+ });+ return {+ events,+ healthy,+ transport,+ client,+ connect,+ onNotification,+ store,+ checkHealth,+ };+}++describe("NotebookClient lifetime", () => {+ it.each(["{broken", JSON.stringify({ event: "ready", data: {} })])(+ "stops consuming a malformed host stream: %s",+ (data) => {+ const { connect, events, client, store, transport, onNotification } =+ setup();+ const lifetime = new AbortController();+ connect(lifetime.signal);+ events.dispatchEvent(new Event("open"));+ events.dispatchEvent(new MessageEvent("message", { data }));+ events.dispatchEvent(+ new MessageEvent("message", {+ data: JSON.stringify({+ event: "marimo",+ data: { marimo: { op: "reconnected" } },+ }),+ }),+ );+ expect(store.get(client.connectionAtom)).toEqual({+ state: ConnectionState.CLOSED,+ code: "KERNEL_DISCONNECTED",+ reason: "Failed to decode notebook message",+ });+ expect(transport.close).toHaveBeenCalledOnce();+ expect(onNotification).not.toHaveBeenCalled();+ lifetime.abort();+ },+ );++ it.each(["MARIMO_UNAUTHORIZED", "MARIMO_TRANSPORT_EXHAUSTED"])(+ "stops automatic recovery after %s but permits an explicit reconnect",+ async (reason) => {+ const {+ connect,+ client,+ store,+ events,+ transport,+ healthy,+ checkHealth,+ } = setup();+ const lifetime = new AbortController();+ connect(lifetime.signal);+ healthy.resolve();+ await healthy.promise;+ events.dispatchEvent(new CloseEvent("close", { reason }));+ events.dispatchEvent(new Event("error"));+ expect(store.get(client.connectionAtom).state).toBe(+ ConnectionState.CLOSED,+ );+ expect(transport.reconnect).toHaveBeenCalledOnce();+ await client.reconnect();+ expect(checkHealth).toHaveBeenCalledOnce();+ expect(transport.reconnect).toHaveBeenCalledTimes(2);+ lifetime.abort();+ },+ );++ it("only resets the automatic retry budget after an open event", () => {+ const { connect, events, transport } = setup();+ const lifetime = new AbortController();+ connect(lifetime.signal);+ events.dispatchEvent(new CloseEvent("close"));+ events.dispatchEvent(new Event("error"));+ events.dispatchEvent(new CloseEvent("close"));+ expect(transport.reconnect).toHaveBeenCalledOnce();+ events.dispatchEvent(new Event("open"));+ events.dispatchEvent(new CloseEvent("close"));+ expect(transport.reconnect).toHaveBeenCalledTimes(2);+ lifetime.abort();+ });++ it("does not revive an aborted lifetime when a manual health check finishes", async () => {+ const { connect, client, transport, checkHealth } = setup();+ const health = new Deferred<boolean>();+ checkHealth.mockReturnValue(health.promise);+ const lifetime = new AbortController();+ connect(lifetime.signal);+ const attempt = client.reconnect();+ lifetime.abort();+ health.resolve(true);+ await attempt;+ expect(transport.reconnect).not.toHaveBeenCalled();+ });++ it("does not connect after abort, even when the health check finishes", async () => {+ const { client, connect, healthy, transport } = setup();+ const controller = new AbortController();+ connect(controller.signal);+ controller.abort();+ healthy.resolve();+ await healthy.promise;+ client.reconnect();+ expect(transport.reconnect).not.toHaveBeenCalled();+ expect(transport.close).toHaveBeenCalledOnce();+ });++ it("detaches listeners before closing so cleanup cannot trigger a session retry", () => {+ const { connect, client, store, events, transport, onNotification } =+ setup();+ const controller = new AbortController();+ connect(controller.signal);+ controller.abort();+ events.dispatchEvent(+ new MessageEvent("message", {+ data: JSON.stringify({ data: { op: "reconnected" } }),+ }),+ );+ expect(transport.reconnect).not.toHaveBeenCalled();+ expect(store.get(client.connectionAtom)).toEqual({+ state: ConnectionState.NOT_STARTED,+ });+ expect(onNotification).not.toHaveBeenCalled();+ });++ it("can reconnect after effect cleanup without reviving the earlier client attempt", async () => {+ const { connect, healthy, transport, events, onNotification } = setup();+ const first = new AbortController();+ connect(first.signal);+ first.abort();+ const second = new AbortController();+ connect(second.signal);+ healthy.resolve();+ await healthy.promise;+ expect(transport.reconnect).toHaveBeenCalledOnce();+ events.dispatchEvent(+ new MessageEvent("message", {+ data: JSON.stringify({+ event: "marimo",+ data: { marimo: { op: "reconnected" } },+ }),+ }),+ );+ expect(onNotification).toHaveBeenCalledExactlyOnceWith({+ data: { op: "reconnected" },+ });+ second.abort();+ });+});diff --git a/frontend/src/core/host/connection.ts b/frontend/src/core/host/connection.tsnew file mode 100644index 0000000000..6ab17aabe4--- /dev/null+++ b/frontend/src/core/host/connection.ts@@ -0,0 +1,81 @@+/* Copyright 2026 Marimo. All rights reserved. */++export const ConnectionState = {+ NOT_STARTED: "NOT_STARTED",+ CONNECTING: "CONNECTING",+ OPEN: "OPEN",+ CLOSING: "CLOSING",+ CLOSED: "CLOSED",+} as const;++export type ConnectionState =+ (typeof ConnectionState)[keyof typeof ConnectionState];++export const ConnectionClosedReason = {+ KERNEL_DISCONNECTED: "KERNEL_DISCONNECTED",+ KERNEL_STARTUP_ERROR: "KERNEL_STARTUP_ERROR",+} as const;++export type ConnectionClosedReason =+ (typeof ConnectionClosedReason)[keyof typeof ConnectionClosedReason];++export type ConnectionStatus =+ | {+ state: typeof ConnectionState.CLOSED;+ code: ConnectionClosedReason;+ reason: string;+ }+ | {+ state: typeof ConnectionState.CONNECTING;+ }+ | {+ state:+ | typeof ConnectionState.OPEN+ | typeof ConnectionState.CLOSING+ | typeof ConnectionState.NOT_STARTED;+ };++/** The recovery policy for a closed connection. */+export interface CloseDecision {+ kind: "terminal" | "gave-up" | "retry";+ status: ConnectionStatus;+}++export type ConnectionEvent = "open" | "close" | "message" | "error";++export interface IConnectionTransportMap {+ open: WebSocketEventMap["open"];+ message: WebSocketEventMap["message"];+ close: WebSocketEventMap["close"];+ error: WebSocketEventMap["error"];+}++export type ConnectionTransportCallback<T extends ConnectionEvent> = (+ data: IConnectionTransportMap[T],+) => void;++/** Transport readiness, using the WebSocket readyState values. */+export const TransportReadyState = {+ CONNECTING: 0,+ OPEN: 1,+ CLOSING: 2,+ CLOSED: 3,+} as const;++export type TransportReadyState =+ (typeof TransportReadyState)[keyof typeof TransportReadyState];++/** A reconnectable source of notebook messages. */+export interface NotebookTransport {+ reconnect(code?: number | undefined, reason?: string | undefined): void;+ close(): void;+ addEventListener<T extends ConnectionEvent>(+ event: T,+ callback: ConnectionTransportCallback<T>,+ ): void;+ removeEventListener<T extends ConnectionEvent>(+ event: T,+ callback: ConnectionTransportCallback<T>,+ ): void;+ readyState: TransportReadyState;+}diff --git a/frontend/src/core/host/events.ts b/frontend/src/core/host/events.tsnew file mode 100644index 0000000000..50817ee107--- /dev/null+++ b/frontend/src/core/host/events.ts@@ -0,0 +1,60 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { z } from "zod";+import * as Protocol from "./protocol";++/**+ * Notebook stream events, including native marimo notifications.+ *+ * Known events follow the generated protocol. Unknown events retain their name+ * and cursor so clients can skip them without losing their place in the stream.+ */++/** Event kinds requested by the client; removals and controls are implicit. */+export const NOTEBOOK_EVENT_TYPES = [+ "notebook",+ "document",+ "cell",+ "marimo",+] as const satisfies readonly (Protocol.ObjectType | "marimo")[];++const envelope = z.object({+ event: z.string().min(1),+ data: z.unknown(),+ id: z.string().min(1).optional(),+});++const knownNames = new Set<string>(+ Protocol.Event.options.flatMap((schema) => schema.shape.event.options),+);++/** A decoded event, or the name and cursor of an unrecognized event. */+export type NotebookEvent =+ | Protocol.EventOutput+ | {+ readonly event: "unknown";+ readonly name: string;+ readonly id?: string;+ };++const sessionEnvelope = z.object({ data: Protocol.MarimoNotification });++/**+ * Decode a host event or a legacy `{ data: notification }` session message.+ *+ * Throws if the envelope or a known event is malformed. Native notification+ * payloads are passed through for the session handler to interpret.+ */+export function parseNotebookEvent(value: unknown): NotebookEvent {+ if (typeof value === "object" && value !== null && !("event" in value)) {+ return {+ event: "marimo",+ data: { marimo: sessionEnvelope.parse(value).data },+ };+ }+ const parsed = envelope.parse(value);+ if (knownNames.has(parsed.event)) {+ return Protocol.Event.parse(parsed);+ }+ return { event: "unknown", name: parsed.event, id: parsed.id };+}diff --git a/frontend/src/core/host/notebook-client.ts b/frontend/src/core/host/notebook-client.tsnew file mode 100644index 0000000000..5278a6e64f--- /dev/null+++ b/frontend/src/core/host/notebook-client.ts@@ -0,0 +1,226 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { Logger } from "@/utils/Logger";+import { type Atom, atom, type createStore } from "jotai/vanilla";+import {+ type ConnectionStatus,+ ConnectionState,+ ConnectionClosedReason,+ type CloseDecision,+ type NotebookTransport,+ TransportReadyState,+} from "./connection";+import { parseNotebookEvent } from "./events";++/** A connection to a notebook on a marimo host. */+export interface NotebookClient {+ /** Transport state, independent of kernel readiness. */+ readonly connectionAtom: Atom<ConnectionStatus>;+ /** Attempt to restore a closed connection after checking host health. */+ reconnect(): Promise<void>;+}++/** The transport and application callbacks needed to connect a notebook. */+export interface NotebookConnection {+ /** Create a transport that reads the URL again on each connection attempt. */+ createTransport: (url: () => string) => NotebookTransport;+ /** The current stream URL, including authentication and subscription options. */+ url: () => string;+ /** Host events require an intact stream; legacy notifications are independent. */+ messageFormat: "host" | "session";+ /** Abort to close the transport and clear the client's state. */+ signal: AbortSignal;+ /** Wait until the host can accept the initial connection. */+ waitUntilReady: () => Promise<void>;+ /** Check whether the host is reachable before an explicit reconnect. */+ checkHealth: () => Promise<boolean>;+ /** Decode wire text without interpreting its event type. */+ decodeJson: (message: string) => unknown;+ /** Handle a native marimo notification. Its payload has not been validated. */+ onNotification: (notification: unknown) => void;+ /** Report a malformed message without coupling the client to editor UI. */+ onMessageError: (error: unknown) => void;+ /** Choose the connection status and retry policy after the transport closes. */+ classifyClose: (event: CloseEvent) => CloseDecision;+}++/** Create a client without opening a connection. */+export function createNotebookClient(store: ReturnType<typeof createStore>) {+ const connectionAtom = atom<ConnectionStatus>({+ state: ConnectionState.NOT_STARTED,+ });+ let reconnect: (() => Promise<void>) | undefined;+ const client: NotebookClient = {+ connectionAtom,+ reconnect: async () => reconnect?.(),+ };++ function connect({+ createTransport,+ url,+ messageFormat,+ signal,+ waitUntilReady,+ checkHealth,+ onNotification,+ onMessageError,+ decodeJson,+ classifyClose,+ }: NotebookConnection) {+ if (signal.aborted) {+ return;+ }+ let shouldRetry = true;+ let terminal = false;+ let checkingHealth = false;+ const transport = createTransport(url);+ const setStatus = (status: ConnectionStatus) =>+ store.set(connectionAtom, status);+ const disconnected = {+ state: ConnectionState.CLOSED,+ code: ConnectionClosedReason.KERNEL_DISCONNECTED,+ reason: "kernel not found",+ } satisfies ConnectionStatus;++ function retry(code?: number, reason?: string) {+ if (!signal.aborted && !terminal && shouldRetry) {+ shouldRetry = false;+ transport.reconnect(code, reason);+ }+ }++ function onOpen() {+ if (signal.aborted || terminal) {+ return;+ }+ shouldRetry = true;+ setStatus({ state: ConnectionState.OPEN });+ }++ function onClose(event: CloseEvent) {+ if (signal.aborted || terminal) {+ return;+ }+ Logger.warn("Notebook connection closed", event.code, event.reason);+ const decision = classifyClose(event);+ setStatus(decision.status);+ if (decision.kind === "terminal") {+ terminal = true;+ transport.close();+ } else if (decision.kind === "retry") {+ retry(event.code, event.reason);+ } else {+ terminal = true;+ }+ }++ function onError(event: Event) {+ if (signal.aborted || terminal) {+ return;+ }+ Logger.warn("Notebook connection error", event);+ setStatus(disconnected);+ retry();+ }++ function onMessage(message: MessageEvent<string>) {+ if (signal.aborted || terminal) {+ return;+ }+ let event;+ try {+ event = parseNotebookEvent(decodeJson(message.data));+ } catch (error) {+ Logger.error("Failed to decode notebook message", error);+ if (messageFormat === "session") {+ onMessageError(error);+ return;+ }+ terminal = true;+ setStatus({+ ...disconnected,+ reason: "Failed to decode notebook message",+ });+ transport.close();+ return;+ }+ if (event.event === "marimo") {+ onNotification(event.data.marimo);+ }+ }++ reconnect = async () => {+ if (+ signal.aborted ||+ checkingHealth ||+ transport.readyState === TransportReadyState.OPEN ||+ transport.readyState === TransportReadyState.CONNECTING+ ) {+ return;+ }+ checkingHealth = true;+ setStatus({ state: ConnectionState.CONNECTING });+ try {+ const healthy = await checkHealth();+ if (signal.aborted) {+ return;+ }+ if (!healthy) {+ shouldRetry = false;+ setStatus(disconnected);+ return;+ }+ terminal = false;+ shouldRetry = true;+ transport.reconnect();+ } catch (error) {+ if (!signal.aborted) {+ Logger.error("Notebook health check failed", error);+ shouldRetry = false;+ setStatus(disconnected);+ }+ } finally {+ checkingHealth = false;+ }+ };++ signal.addEventListener(+ "abort",+ () => {+ transport.removeEventListener("open", onOpen);+ transport.removeEventListener("close", onClose);+ transport.removeEventListener("error", onError);+ transport.removeEventListener("message", onMessage);+ transport.close();+ reconnect = undefined;+ setStatus({ state: ConnectionState.NOT_STARTED });+ },+ { once: true },+ );++ transport.addEventListener("open", onOpen);+ transport.addEventListener("close", onClose);+ transport.addEventListener("error", onError);+ transport.addEventListener("message", onMessage);++ if (transport.readyState === TransportReadyState.CLOSED) {+ setStatus({ state: ConnectionState.CONNECTING });+ void waitUntilReady()+ .then(() => {+ if (!signal.aborted) {+ transport.reconnect();+ }+ })+ .catch((error) => {+ if (!signal.aborted) {+ Logger.error("Healthy connection never made", error);+ terminal = true;+ setStatus(disconnected);+ transport.close();+ }+ });+ }+ }++ return { client, connect };+}diff --git a/frontend/src/core/run-app.tsx b/frontend/src/core/run-app.tsxindex 14dd778dc2..dc2aa38b26 100644--- a/frontend/src/core/run-app.tsx+++ b/frontend/src/core/run-app.tsx@@ -22,7 +22,7 @@ import { getSessionId } from "./kernel/session";import { connectionAtom } from "./network/connection";import { useRequestClient } from "./network/requests";import { isAppConnecting } from "./websocket/connection-utils";-import { useMarimoKernelConnection } from "./websocket/useMarimoKernelConnection";+import { useNotebookSession } from "./websocket/useNotebookSession";interface AppProps {appConfig: AppConfig;@@ -51,7 +51,7 @@ export const RunApp: React.FC<AppProps> = ({ appConfig, hideHeader }) => {};}, []);- const { connection, reconnect } = useMarimoKernelConnection({+ const { connection, reconnect } = useNotebookSession({autoInstantiate: true,setCells: setCells,sessionId: getSessionId(),diff --git a/frontend/src/core/runtime/__tests__/runtime.test.ts b/frontend/src/core/runtime/__tests__/runtime.test.tsindex b98d08acee..0854a5fd6d 100644--- a/frontend/src/core/runtime/__tests__/runtime.test.ts+++ b/frontend/src/core/runtime/__tests__/runtime.test.ts@@ -2,14 +2,19 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { Mocks } from "@/__mocks__/common";-import type { SessionId } from "@/core/kernel/session";+import {+ generateSessionId,+ isSessionId,+ type SessionId,+} from "@/core/kernel/session";import { Logger } from "@/utils/Logger";import { RuntimeManager } from "../runtime";import type { RuntimeConfig } from "../types";// Mock the session module-vi.mock("@/core/kernel/session", () => ({- getSessionId: () => "test-session-id" as SessionId,+vi.mock("@/core/kernel/session", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/core/kernel/session")>()),+ getSessionId: () => "test-session-id",}));vi.mock("@/utils/Logger", () => ({ Logger: Mocks.quietLogger() }));@@ -51,6 +56,38 @@ describe("RuntimeManager", () => {});describe("getWsURL", () => {+ it("uses host notebook events with the existing session and auth parameters", () => {+ const original = window.location.href;+ window.history.replaceState({}, "", "/?types=run");+ try {+ const runtime = new RuntimeManager({+ ...mockConfig,+ url: "https://example.com/nested?file=notebook.py",+ notebookId: "nb_123",+ });+ const sessionId = "s_123456";+ if (!isSessionId(sessionId)) {+ throw new Error("Invalid test session ID");+ }+ const url = runtime.getWsURL(sessionId);+ expect({+ endpoint: `${url.origin}${url.pathname}`,+ params: Object.fromEntries(url.searchParams),+ }).toEqual({+ endpoint:+ "wss://example.com/nested/api/marimo/v1/notebooks/nb_123/events/ws",+ params: {+ file: "notebook.py",+ types: "marimo",+ session_id: sessionId,+ access_token: "test-token",+ },+ });+ } finally {+ window.history.replaceState({}, "", original);+ }+ });+it("should return WebSocket URL with session ID for https", () => {const runtime = new RuntimeManager(mockConfig);const sessionId = "1234" as SessionId;@@ -59,6 +96,7 @@ describe("RuntimeManager", () => {expect(url.protocol).toBe("wss:");expect(url.hostname).toBe("example.com");expect(url.pathname).toBe("/ws");+ expect(url.searchParams.has("types")).toBe(false);expect(url.searchParams.get("session_id")).toBe(sessionId);});@@ -219,14 +257,20 @@ describe("RuntimeManager", () => {});describe("getSseURL", () => {- it("should return an http(s) URL with the session ID", () => {- const runtime = new RuntimeManager(mockConfig);- const url = runtime.getSseURL("1234" as SessionId);-- expect(url.protocol).toBe("https:");- expect(url.pathname).toBe("/sse");- expect(url.searchParams.get("session_id")).toBe("1234");- });+ it.each([undefined, "nb_123"])(+ "uses the legacy session stream when notebookId is %s",+ (notebookId) => {+ const runtime = new RuntimeManager({+ ...mockConfig,+ url: "https://example.com/nested?file=notebook.py",+ notebookId,+ });+ const sessionId = generateSessionId();+ expect(runtime.getSseURL(sessionId).toString()).toBe(+ `https://example.com/nested/sse?file=notebook.py&session_id=${sessionId}`,+ );+ },+ );it("should never put the auth token in the URL, even cross-origin", () => {// SSE requests can send headers, so auth travels in thediff --git a/frontend/src/core/runtime/runtime.ts b/frontend/src/core/runtime/runtime.tsindex b4c2fbf426..5edc973139 100644--- a/frontend/src/core/runtime/runtime.ts+++ b/frontend/src/core/runtime/runtime.ts@@ -9,6 +9,8 @@ import { isStaticNotebook } from "../static/static-state";import { isWasm } from "../wasm/utils";import type { RuntimeConfig } from "./types";+const HOST_EVENT_TYPES = ["marimo"];+export class RuntimeManager {private initialHealthyCheck = new Deferred<void>();private config: RuntimeConfig;@@ -154,7 +156,18 @@ export class RuntimeManager {* The WebSocket URL of the runtime.*/public getWsURL(sessionId: SessionId): URL {- return this.formatWsURL("/ws", this.getSessionSearchParams(sessionId));+ const searchParams = this.getSessionSearchParams(sessionId);+ // TODO(MO-8039): Rediscover hosts and resolve notebooks on reconnect.+ const notebookId = this.config.notebookId;+ const path = notebookId+ ? `/api/marimo/v1/notebooks/${encodeURIComponent(notebookId)}/events/ws`+ : "/ws";+ const url = this.formatWsURL(path, searchParams);+ if (notebookId) {+ // TODO(MO-8034): Separate host options from notebook query params.+ url.searchParams.set("types", HOST_EVENT_TYPES.join(","));+ }+ return url;}/**diff --git a/frontend/src/core/runtime/types.ts b/frontend/src/core/runtime/types.tsindex 8d8e6ddf44..178df51d90 100644--- a/frontend/src/core/runtime/types.ts+++ b/frontend/src/core/runtime/types.ts@@ -1,6 +1,8 @@/* Copyright 2026 Marimo. All rights reserved. */export interface RuntimeConfig {+ /** The host notebook for WebSocket events. SSE uses the legacy session stream. */+ readonly notebookId?: string;/*** The URL of the runtime server.*/diff --git a/frontend/src/core/websocket/__tests__/useMarimoKernelConnection.test.ts b/frontend/src/core/websocket/__tests__/connection-state.test.tssimilarity index 71%rename from frontend/src/core/websocket/__tests__/useMarimoKernelConnection.test.tsrename to frontend/src/core/websocket/__tests__/connection-state.test.tsindex 842041d1bb..d40af075ab 100644--- a/frontend/src/core/websocket/__tests__/useMarimoKernelConnection.test.ts+++ b/frontend/src/core/websocket/__tests__/connection-state.test.ts@@ -3,7 +3,7 @@import { afterEach, describe, expect, it, vi } from "vitest";import { Logger } from "@/utils/Logger";import { WebSocketClosedReason, ConnectionState } from "../types";-import { classifyCloseEvent } from "../useMarimoKernelConnection";+import { classifyCloseEvent } from "../connection-state";function classify(reason: string | undefined) {return classifyCloseEvent({ reason });@@ -13,8 +13,10 @@ describe("classifyCloseEvent", () => {describe("transient closes (default branch)", () => {it("retries on empty/undefined reason", () => {const decision = classify(undefined);- expect(decision.kind).toBe("retry");- expect(decision.status).toEqual({ state: ConnectionState.CONNECTING });+ expect(decision).toEqual({+ kind: "retry",+ status: { state: ConnectionState.CONNECTING },+ });});it("treats unknown reason strings as transient and logs a warning", () => {@@ -40,29 +42,25 @@ describe("classifyCloseEvent", () => {// terminal or a rejected client would reconnect forever."MARIMO_UNAUTHORIZED","MARIMO_KIOSK_NOT_ALLOWED",- ])("%s → terminal with KERNEL_DISCONNECTED, closes transport", (reason) => {+ ])("%s → terminal with KERNEL_DISCONNECTED", (reason) => {const decision = classify(reason);- expect(decision.kind).toBe("terminal");- expect(decision.status).toMatchObject({- state: ConnectionState.CLOSED,- code: WebSocketClosedReason.KERNEL_DISCONNECTED,- });expect(decision).toMatchObject({kind: "terminal",- closeTransport: true,+ status: {+ state: ConnectionState.CLOSED,+ code: WebSocketClosedReason.KERNEL_DISCONNECTED,+ },});});- it("MARIMO_KERNEL_STARTUP_ERROR → terminal + closeTransport", () => {+ it("MARIMO_KERNEL_STARTUP_ERROR → terminal", () => {const decision = classify("MARIMO_KERNEL_STARTUP_ERROR");- expect(decision.kind).toBe("terminal");- expect(decision.status).toMatchObject({- state: ConnectionState.CLOSED,- code: WebSocketClosedReason.KERNEL_STARTUP_ERROR,- });expect(decision).toMatchObject({kind: "terminal",- closeTransport: true,+ status: {+ state: ConnectionState.CLOSED,+ code: WebSocketClosedReason.KERNEL_STARTUP_ERROR,+ },});});});diff --git a/frontend/src/core/websocket/__tests__/useWebSocket.test.ts b/frontend/src/core/websocket/__tests__/createConnectionTransport.test.tssimilarity index 94%rename from frontend/src/core/websocket/__tests__/useWebSocket.test.tsrename to frontend/src/core/websocket/__tests__/createConnectionTransport.test.tsindex 2065cec5ae..8d70252c96 100644--- a/frontend/src/core/websocket/__tests__/useWebSocket.test.ts+++ b/frontend/src/core/websocket/__tests__/createConnectionTransport.test.ts@@ -4,7 +4,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";import { BasicTransport } from "../transports/basic";import { SseTransport } from "../transports/sse";import { WsTransport } from "../transports/ws";-import { createConnectionTransport } from "../useWebSocket";+import { createConnectionTransport } from "../transports/create";vi.mock("../../wasm/utils", () => ({isWasm: () => false,diff --git a/frontend/src/core/websocket/__tests__/useNotebookClient.hook.test.tsx b/frontend/src/core/websocket/__tests__/useNotebookClient.hook.test.tsxnew file mode 100644index 0000000000..b123b635bb--- /dev/null+++ b/frontend/src/core/websocket/__tests__/useNotebookClient.hook.test.tsx@@ -0,0 +1,140 @@+/* Copyright 2026 Marimo. All rights reserved. */+// @vitest-environment jsdom++import { act, renderHook } from "@testing-library/react";+import { createStore, Provider } from "jotai";+import type { PropsWithChildren } from "react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { ConnectionState } from "../types";+import { createConnectionTransport } from "../transports/create";+import type { IConnectionTransport } from "../transports/transport";+import { useNotebookClient } from "../useNotebookClient";++vi.mock("../transports/create", () => ({ createConnectionTransport: vi.fn() }));++function makeTransport() {+ const events = new EventTarget();+ const transport: IConnectionTransport = {+ readyState: WebSocket.CLOSED,+ reconnect: vi.fn(() => {+ transport.readyState = WebSocket.OPEN;+ events.dispatchEvent(new Event("open"));+ }),+ close: vi.fn(() => {+ transport.readyState = WebSocket.CLOSED;+ events.dispatchEvent(new CloseEvent("close"));+ }),+ send: vi.fn(),+ addEventListener: events.addEventListener.bind(events),+ removeEventListener: events.removeEventListener.bind(events),+ };+ return {+ transport,+ notify: () =>+ events.dispatchEvent(+ new MessageEvent("message", {+ data: JSON.stringify({+ event: "marimo",+ data: { marimo: { op: "reconnected" } },+ }),+ }),+ ),+ };+}++function setup(strict = false) {+ const store = createStore();+ const options = {+ sessionId: "first",+ static: false,+ transportType: "websocket" as const,+ messageFormat: "host" as const,+ url: () => "ws://localhost/ws",+ headers: () => ({}),+ waitUntilReady: async () => undefined,+ checkHealth: async () => true,+ onNotification: vi.fn(),+ onMessageError: vi.fn(),+ };+ const wrapper = ({ children }: PropsWithChildren) => (+ <Provider store={store}>{children}</Provider>+ );+ const hook = renderHook((props) => useNotebookClient(props), {+ initialProps: options,+ reactStrictMode: strict,+ wrapper,+ });+ return { ...hook, options, store };+}++beforeEach(() => {+ vi.mocked(createConnectionTransport).mockReset();+});++describe("useNotebookClient", () => {+ it("uses current callbacks and URL providers without reconnecting on a rerender", async () => {+ const first = makeTransport();+ vi.mocked(createConnectionTransport).mockReturnValue(first.transport);+ const { rerender, options, unmount } = setup();+ await act(async () => Promise.resolve());+ const onNotification = vi.fn();+ rerender({ ...options, onNotification, url: () => "ws://redirected/ws" });+ act(() => first.notify());+ expect(options.onNotification).not.toHaveBeenCalled();+ expect(onNotification).toHaveBeenCalledExactlyOnceWith({+ data: { op: "reconnected" },+ });+ expect(createConnectionTransport).toHaveBeenCalledOnce();+ expect(vi.mocked(createConnectionTransport).mock.calls[0][0].url()).toBe(+ "ws://redirected/ws",+ );+ unmount();+ });++ it("replaces the transport when session identity changes and ignores old messages", async () => {+ const first = makeTransport();+ const second = makeTransport();+ vi.mocked(createConnectionTransport)+ .mockReturnValueOnce(first.transport)+ .mockReturnValueOnce(second.transport);+ const { rerender, options, unmount } = setup();+ await act(async () => Promise.resolve());+ rerender({ ...options, sessionId: "second" });+ await act(async () => Promise.resolve());+ expect(first.transport.close).toHaveBeenCalledOnce();+ act(() => {+ first.notify();+ second.notify();+ });+ expect(options.onNotification).toHaveBeenCalledOnce();+ unmount();+ });++ it("cleans up every transport under Strict Mode and only connects the active lifetime", async () => {+ const transports: ReturnType<typeof makeTransport>[] = [];+ vi.mocked(createConnectionTransport).mockImplementation(() => {+ const next = makeTransport();+ transports.push(next);+ return next.transport;+ });+ const { result, store, options, unmount } = setup(true);+ await act(async () => Promise.resolve());+ expect(transports).toHaveLength(2);+ expect(transports[0].transport.reconnect).not.toHaveBeenCalled();+ expect(transports[0].transport.close).toHaveBeenCalledOnce();+ expect(transports[1].transport.reconnect).toHaveBeenCalledOnce();+ expect(store.get(result.current.connectionAtom)).toEqual({+ state: ConnectionState.OPEN,+ });+ act(() => {+ for (const transport of transports) {+ transport.notify();+ }+ });+ expect(options.onNotification).toHaveBeenCalledOnce();+ unmount();+ expect(transports[1].transport.close).toHaveBeenCalledOnce();+ await result.current.reconnect();+ expect(transports[1].transport.reconnect).toHaveBeenCalledOnce();+ });+});diff --git a/frontend/src/core/websocket/__tests__/useMarimoKernelConnection.hook.test.tsx b/frontend/src/core/websocket/__tests__/useNotebookSession.hook.test.tsxsimilarity index 76%rename from frontend/src/core/websocket/__tests__/useMarimoKernelConnection.hook.test.tsxrename to frontend/src/core/websocket/__tests__/useNotebookSession.hook.test.tsxindex e0ab860511..2e319b4787 100644--- a/frontend/src/core/websocket/__tests__/useMarimoKernelConnection.hook.test.tsx+++ b/frontend/src/core/websocket/__tests__/useNotebookSession.hook.test.tsx@@ -21,14 +21,9 @@ import {vi,} from "vitest";-vi.mock("@/core/websocket/useWebSocket", async () => {- const actual =- await vi.importActual<typeof import("../useWebSocket")>("../useWebSocket");- return {- ...actual,- useConnectionTransport: vi.fn(),- };-});+vi.mock("../transports/create", () => ({+ createConnectionTransport: vi.fn(),+}));vi.mock("@/core/runtime/config", async () => {const actual = await vi.importActual<typeof import("@/core/runtime/config")>(@@ -41,6 +36,9 @@ vi.mock("@/core/runtime/config", async () => {});import { MockNotebook } from "@/__mocks__/notebook";+import * as Toast from "@/components/ui/use-toast";+import { Logger } from "@/utils/Logger";+import { Deferred } from "@/utils/Deferred";import { cellId } from "@/__tests__/branded";import { alertAtom, getPackageAlert } from "@/core/alerts/state";import {@@ -52,15 +50,19 @@ import { notebookAtom } from "@/core/cells/cells";import { AppConfigSchema } from "@/core/config/config-schema";import { ConnectionNotice } from "@/components/editor/alerts/connection-notice";import { kernelStartupErrorAtom } from "@/core/errors/state";+import type { RunEvent } from "@/core/host/protocol";import type { NotificationPayload } from "@/core/kernel/messages";import { useRuntimeManager } from "@/core/runtime/config";import { initialRunCompletedAtom } from "../../kernel/state";import { connectionAtom, startupProgressAtom } from "../../network/connection";-import type { SessionId } from "../../kernel/session";+import { generateSessionId } from "../../kernel/session";+import { RuntimeManager } from "../../runtime/runtime";import { WebSocketClosedReason, ConnectionState } from "../types";import type { IConnectionTransport } from "../transports/transport";-import { useMarimoKernelConnection } from "../useMarimoKernelConnection";-import { useConnectionTransport } from "../useWebSocket";+import { useNotebookSession } from "../useNotebookSession";+import { createConnectionTransport } from "../transports/create";++const SESSION_ID = generateSessionId();interface MockTransport {readyState: 0 | 1 | 2 | 3;@@ -84,16 +86,47 @@ function makeTransport(};}+function getTransportHandlers() {+ const result = vi.mocked(createConnectionTransport).mock.results.at(-1);+ if (!result || result.type !== "return") {+ throw new Error("No connection transport was created");+ }+ const transport = result.value;+ function emit(+ event: "open" | "close" | "error" | "message",+ message: Event | CloseEvent | MessageEvent,+ ) {+ const callback = vi+ .mocked(transport.addEventListener)+ .mock.calls.find(([name]) => name === event)?.[1];+ callback?.(message);+ }+ return {+ onError: (event: Event) => emit("error", event),+ onOpen: (event: Event) => emit("open", event),+ onClose: (event: CloseEvent) => emit("close", event),+ onMessage: (event: MessageEvent) => emit("message", event),+ };+}+function makeRuntimeManager(reconcileFromHealth = vi.fn<() => Promise<boolean>>().mockResolvedValue(true),) {- return {+ const runtime = new RuntimeManager(+ { url: "http://localhost", lazy: true },+ true,+ );+ vi.spyOn(runtime, "reconcileFromHealth").mockImplementation(reconcileFromHealth,- probeHealth: vi.fn().mockResolvedValue(true),- getWsURL: () => new URL("ws://localhost/ws"),- waitForHealthy: vi.fn().mockResolvedValue(undefined),- isSameOrigin: true,- };+ );+ vi.spyOn(runtime, "probeHealth").mockResolvedValue(true);+ vi.spyOn(runtime, "getWsURL").mockReturnValue(new URL("ws://localhost/ws"));+ // Keep the initial connection pending; these tests exercise session retries.+ vi.spyOn(runtime, "waitForHealthy").mockReturnValue(+ new Deferred<void>().promise,+ );+ vi.spyOn(runtime, "isSameOrigin", "get").mockReturnValue(false);+ return runtime;}function renderConnectionHook(store: ReturnType<typeof createStore>) {@@ -104,16 +137,16 @@ function renderConnectionHook(store: ReturnType<typeof createStore>) {);return renderHook(() =>- useMarimoKernelConnection({- sessionId: "test-session" as SessionId,+ useNotebookSession({+ sessionId: SESSION_ID,autoInstantiate: false,- setCells: () => {},+ setCells: vi.fn(),}),{ wrapper },);}-describe("useMarimoKernelConnection.reconnect()", () => {+describe("useNotebookSession.reconnect()", () => {let transport: MockTransport;let isHealthy: Mock<() => Promise<boolean>>;let store: ReturnType<typeof createStore>;@@ -127,12 +160,8 @@ describe("useMarimoKernelConnection.reconnect()", () => {code: WebSocketClosedReason.KERNEL_DISCONNECTED,reason: "kernel not found",});- vi.mocked(useConnectionTransport).mockReturnValue(transport);- vi.mocked(useRuntimeManager).mockReturnValue(- makeRuntimeManager(isHealthy) as unknown as ReturnType<- typeof useRuntimeManager- >,- );+ vi.mocked(createConnectionTransport).mockReturnValue(transport);+ vi.mocked(useRuntimeManager).mockReturnValue(makeRuntimeManager(isHealthy));});function renderUseHook() {@@ -188,17 +217,29 @@ describe("useMarimoKernelConnection.reconnect()", () => {});});-describe("useMarimoKernelConnection messages", () => {- it("replaces attachment snapshots, including the last detach", () => {- const store = createStore();- vi.mocked(useConnectionTransport).mockReturnValue(+describe("useNotebookSession messages", () => {+ let store: ReturnType<typeof createStore>;++ beforeEach(() => {+ store = createStore();+ vi.mocked(createConnectionTransport).mockClear();+ vi.mocked(createConnectionTransport).mockReturnValue(makeTransport(WebSocket.OPEN),);- vi.mocked(useRuntimeManager).mockReturnValue(- makeRuntimeManager() as unknown as ReturnType<typeof useRuntimeManager>,- );+ vi.mocked(useRuntimeManager).mockReturnValue(makeRuntimeManager());renderConnectionHook(store);- const options = vi.mocked(useConnectionTransport).mock.calls.at(-1)![0];+ });++ function receive(payload: unknown) {+ const options = getTransportHandlers();+ act(() => {+ options.onMessage(+ new MessageEvent("message", { data: JSON.stringify(payload) }),+ );+ });+ }++ it("replaces attachment snapshots, including the last detach", () => {const agent: Attachment = {id: "a1",kind: "agent",@@ -215,46 +256,157 @@ describe("useMarimoKernelConnection messages", () => {notebook_id: "nb-test",};for (const attachments of [[agent, client], [client], []]) {- act(() =>- options.onMessage(- new MessageEvent("message", {- data: JSON.stringify({- op: "attachments",- data: { op: "attachments", attachments },- }),- }),- ),- );+ receive({ data: { op: "attachments", attachments } });expect(store.get(attachmentsAtom)).toEqual(attachments);}});- it("records completion of the initial run", () => {+ it.each(["{broken", "null"])(+ "reports a malformed legacy frame and continues applying notifications: %s",+ (data) => {+ const toast = vi.spyOn(Toast, "toast");+ try {+ receive({ data: { op: "reconnected" } });+ act(() =>+ getTransportHandlers().onMessage(+ new MessageEvent("message", { data }),+ ),+ );+ expect(toast).toHaveBeenCalledExactlyOnceWith({+ title: "Failed to handle message",+ description: expect.any(String),+ variant: "danger",+ });+ expect(store.get(connectionAtom)).toEqual({+ state: ConnectionState.OPEN,+ });+ receive({+ data: {+ op: "completed-run",+ run_id: "r1",+ outcome: "succeeded",+ error: null,+ },+ });+ expect(store.get(initialRunCompletedAtom)).toBe(true);+ } finally {+ toast.mockRestore();+ }+ },+ );++ it.each(["session", "host"])(+ "records completion of the initial run from the %s stream",+ (stream) => {+ const notification = {+ op: "completed-run",+ run_id: null,+ outcome: "succeeded",+ error: null,+ } satisfies NotificationPayload["data"];+ expect(store.get(initialRunCompletedAtom)).toBe(false);+ receive(+ stream === "host"+ ? { id: "42", event: "marimo", data: { marimo: notification } }+ : { op: notification.op, data: notification },+ );+ expect(store.get(initialRunCompletedAtom)).toBe(true);+ },+ );++ it("ignores other host events before handling the next notification", () => {+ const errors = vi.spyOn(Logger, "error").mockImplementation(vi.fn());+ try {+ receive({ id: "1", event: "ready", data: {} });+ receive({+ id: "2",+ event: "run",+ data: {+ run: {+ id: "r1",+ notebook_id: "n1",+ caused_by: null,+ status: "completed",+ outcome: "succeeded",+ started_at: "2026-10-19T12:00:00Z",+ completed_at: "2026-10-19T12:00:01Z",+ },+ },+ } satisfies RunEvent);+ receive({+ id: "3",+ event: "future-event",+ data: { marimo: { op: "completed-run", run_id: "r1" } },+ });+ receive({ id: "4", event: "another-event", data: null });+ expect(store.get(initialRunCompletedAtom)).toBe(false);+ receive({+ id: "5",+ event: "marimo",+ data: {+ marimo: {+ op: "completed-run",+ run_id: "r1",+ outcome: "succeeded",+ error: null,+ },+ },+ });+ expect(store.get(initialRunCompletedAtom)).toBe(true);+ expect(errors).not.toHaveBeenCalled();+ } finally {+ errors.mockRestore();+ }+ });+});++it.each(["kernel-ready", "reconnected"])(+ "waits for %s before marking the session connected",+ async (op) => {const store = createStore();- vi.mocked(useConnectionTransport).mockClear();- vi.mocked(useConnectionTransport).mockReturnValue(+ store.set(connectionAtom, { state: ConnectionState.CONNECTING });+ vi.mocked(createConnectionTransport).mockClear();+ vi.mocked(createConnectionTransport).mockReturnValue(makeTransport(WebSocket.OPEN),);- vi.mocked(useRuntimeManager).mockReturnValue(- makeRuntimeManager() as unknown as ReturnType<typeof useRuntimeManager>,- );+ vi.mocked(useRuntimeManager).mockReturnValue(makeRuntimeManager());renderConnectionHook(store);+ const options = getTransportHandlers();++ await act(async () => {+ await options.onOpen(new Event("open"));+ });+ expect(store.get(connectionAtom).state).toBe(ConnectionState.CONNECTING);- const options = vi.mocked(useConnectionTransport).mock.calls.at(-1)?.[0];- expect(store.get(initialRunCompletedAtom)).toBe(false);act(() => {- options?.onMessage(+ options.onMessage(new MessageEvent("message", {data: JSON.stringify({- op: "completed-run",- data: { op: "completed-run", run_id: null },+ op,+ data: {+ op,+ cell_ids: [],+ codes: [],+ names: [],+ configs: [],+ layout: null,+ resumed: true,+ ui_values: {},+ last_executed_code: {},+ last_execution_time: {},+ app_config: { width: "normal" },+ kiosk: false,+ capabilities: { terminal: false },+ auto_instantiated: false,+ consumer_capabilities: { edit: true, interact: true },+ },}),}),);});- expect(store.get(initialRunCompletedAtom)).toBe(true);- });-});+ expect(store.get(connectionAtom).state).toBe(ConnectionState.OPEN);+ },+);describe("attachment snapshots across browser connections", () => {const agent: Attachment = {@@ -271,12 +423,10 @@ describe("attachment snapshots across browser connections", () => {store.set(connectionAtom, { state: ConnectionState.OPEN });store.set(attachmentsAtom, [agent]);const transport = makeTransport(WebSocket.OPEN);- vi.mocked(useConnectionTransport).mockReturnValue(transport);- vi.mocked(useRuntimeManager).mockReturnValue(- makeRuntimeManager() as unknown as ReturnType<typeof useRuntimeManager>,- );+ vi.mocked(createConnectionTransport).mockReturnValue(transport);+ vi.mocked(useRuntimeManager).mockReturnValue(makeRuntimeManager());renderConnectionHook(store);- const options = vi.mocked(useConnectionTransport).mock.calls.at(-1)![0];+ const options = getTransportHandlers();const receive = (data: NotificationPayload["data"]) =>act(() => {options.onMessage(@@ -351,56 +501,6 @@ describe("attachment snapshots across browser connections", () => {});});-it.each(["kernel-ready", "reconnected"])(- "waits for %s before marking the session connected",- async (op) => {- const store = createStore();- store.set(connectionAtom, { state: ConnectionState.CONNECTING });- vi.mocked(useConnectionTransport).mockClear();- vi.mocked(useConnectionTransport).mockReturnValue(- makeTransport(WebSocket.OPEN),- );- vi.mocked(useRuntimeManager).mockReturnValue(- makeRuntimeManager() as unknown as ReturnType<typeof useRuntimeManager>,- );- renderConnectionHook(store);- const options = vi.mocked(useConnectionTransport).mock.calls.at(-1)![0];-- await act(async () => {- await options.onOpen(new Event("open"));- });- expect(store.get(connectionAtom).state).toBe(ConnectionState.CONNECTING);-- act(() => {- options.onMessage(- new MessageEvent("message", {- data: JSON.stringify({- op,- data: {- op,- cell_ids: [],- codes: [],- names: [],- configs: [],- layout: null,- resumed: true,- ui_values: {},- last_executed_code: {},- last_execution_time: {},- app_config: { width: "normal" },- kiosk: false,- capabilities: { terminal: false },- auto_instantiated: false,- consumer_capabilities: { edit: true, interact: true },- },- }),- }),- );- });- expect(store.get(connectionAtom).state).toBe(ConnectionState.OPEN);- },-);-it.each([true, false])("keeps attachments only when kernel-ready resumes the session: %s",(resumed) => {@@ -416,14 +516,12 @@ it.each([true, false])(},];store.set(attachmentsAtom, attachments);- vi.mocked(useConnectionTransport).mockReturnValue(+ vi.mocked(createConnectionTransport).mockReturnValue(makeTransport(WebSocket.OPEN),);- vi.mocked(useRuntimeManager).mockReturnValue(- makeRuntimeManager() as unknown as ReturnType<typeof useRuntimeManager>,- );+ vi.mocked(useRuntimeManager).mockReturnValue(makeRuntimeManager());renderConnectionHook(store);- const options = vi.mocked(useConnectionTransport).mock.calls.at(-1)![0];+ const options = getTransportHandlers();act(() =>options.onMessage(new MessageEvent("message", {@@ -462,15 +560,13 @@ describe("connection notice", () => {const store = createStore();store.set(connectionAtom, { state: ConnectionState.CONNECTING });const transport = makeTransport(WebSocket.OPEN);- vi.mocked(useConnectionTransport).mockReturnValue(transport);- vi.mocked(useRuntimeManager).mockReturnValue(- makeRuntimeManager() as unknown as ReturnType<typeof useRuntimeManager>,- );+ vi.mocked(createConnectionTransport).mockReturnValue(transport);+ vi.mocked(useRuntimeManager).mockReturnValue(makeRuntimeManager());const Connection = () => {- const { reconnect } = useMarimoKernelConnection({- sessionId: "test-session" as SessionId,+ const { reconnect } = useNotebookSession({+ sessionId: SESSION_ID,autoInstantiate: false,- setCells: () => {},+ setCells: vi.fn(),});return (<ConnectionNotice@@ -486,7 +582,7 @@ describe("connection notice", () => {</ErrorBoundary></JotaiProvider>,);- const options = vi.mocked(useConnectionTransport).mock.calls.at(-1)![0];+ const options = getTransportHandlers();const send = (data: NotificationPayload["data"]) =>act(() => {options.onMessage(@@ -675,15 +771,13 @@ describe("connection notice", () => {it("replaces environment state from snapshots, then continues live progress", () => {const store = createStore();- vi.mocked(useConnectionTransport).mockClear();- vi.mocked(useConnectionTransport).mockReturnValue(+ vi.mocked(createConnectionTransport).mockClear();+ vi.mocked(createConnectionTransport).mockReturnValue(makeTransport(WebSocket.OPEN),);- vi.mocked(useRuntimeManager).mockReturnValue(- makeRuntimeManager() as unknown as ReturnType<typeof useRuntimeManager>,- );+ vi.mocked(useRuntimeManager).mockReturnValue(makeRuntimeManager());renderConnectionHook(store);- const options = vi.mocked(useConnectionTransport).mock.calls.at(-1)?.[0];+ const options = getTransportHandlers();function receive(data: NotificationPayload["data"]) {act(() =>options?.onMessage(diff --git a/frontend/src/core/websocket/connection-state.ts b/frontend/src/core/websocket/connection-state.tsnew file mode 100644index 0000000000..921e6a7574--- /dev/null+++ b/frontend/src/core/websocket/connection-state.ts@@ -0,0 +1,70 @@+/* Copyright 2026 Marimo. All rights reserved. */++import type { CloseDecision } from "../host/connection";+import { Logger } from "@/utils/Logger";+import { TRANSPORT_EXHAUSTED_REASON } from "./transports/ws";+import { ConnectionState, WebSocketClosedReason } from "./types";++// Keep server reasons in sync with ws_endpoint.py and ws/*.py.+// SSE carries the same reasons in close events. Unclassified reasons retry.+export function classifyCloseEvent(event: { reason?: string }): CloseDecision {+ switch (event.reason) {+ case TRANSPORT_EXHAUSTED_REASON:+ return {+ kind: "gave-up",+ status: {+ state: ConnectionState.CLOSED,+ code: WebSocketClosedReason.KERNEL_DISCONNECTED,+ reason: "kernel not found",+ },+ };+ case "MARIMO_NO_FILE_KEY":+ case "MARIMO_NO_SESSION_ID":+ case "MARIMO_NO_SESSION":+ case "MARIMO_SHUTDOWN":+ return {+ kind: "terminal",+ status: {+ state: ConnectionState.CLOSED,+ code: WebSocketClosedReason.KERNEL_DISCONNECTED,+ reason: "kernel not found",+ },+ };+ case "MARIMO_UNAUTHORIZED":+ return {+ kind: "terminal",+ status: {+ state: ConnectionState.CLOSED,+ code: WebSocketClosedReason.KERNEL_DISCONNECTED,+ reason: "not authorized",+ },+ };+ case "MARIMO_KIOSK_NOT_ALLOWED":+ return {+ kind: "terminal",+ status: {+ state: ConnectionState.CLOSED,+ code: WebSocketClosedReason.KERNEL_DISCONNECTED,+ reason: "kiosk mode is not available for this session",+ },+ };+ case "MARIMO_KERNEL_STARTUP_ERROR":+ return {+ kind: "terminal",+ status: {+ state: ConnectionState.CLOSED,+ code: WebSocketClosedReason.KERNEL_STARTUP_ERROR,+ reason: "Failed to start kernel sandbox",+ },+ };+ default:+ if (event.reason) {+ Logger.warn("Unrecognized connection close reason", event.reason);+ }+ }++ return {+ kind: "retry",+ status: { state: ConnectionState.CONNECTING },+ };+}diff --git a/frontend/src/core/websocket/transports/__tests__/sse.test.ts b/frontend/src/core/websocket/transports/__tests__/sse.test.tsindex 208ce62b4b..c4392ff462 100644--- a/frontend/src/core/websocket/transports/__tests__/sse.test.ts+++ b/frontend/src/core/websocket/transports/__tests__/sse.test.ts@@ -108,8 +108,6 @@ describe("SseTransport", () => {transport.reconnect();await vi.waitFor(() => expect(opens).toHaveLength(1));- // Stop retrying when the consumer treats the close as terminal,- // mirroring useMarimoKernelConnection's terminal path.transport.addEventListener("close", () => transport.close());push('event: close\ndata: {"code": 1000, "reason": "MARIMO_SHUTDOWN"}\n\n');await vi.waitFor(() => expect(closes).toHaveLength(1));@@ -146,8 +144,7 @@ describe("SseTransport", () => {fetchMock.mockResolvedValueOnce(sseResponse(first.stream)).mockResolvedValueOnce(sseResponse(second.stream));- // Mirror useMarimoKernelConnection's retry path: reconnect()- // synchronously from inside the close handler.+ // Reconnect synchronously from the close handler.transport.addEventListener("close", () => transport.reconnect());transport.reconnect();diff --git a/frontend/src/core/websocket/transports/create.ts b/frontend/src/core/websocket/transports/create.tsnew file mode 100644index 0000000000..016bf2d869--- /dev/null+++ b/frontend/src/core/websocket/transports/create.ts@@ -0,0 +1,31 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { createPyodideConnection } from "../../wasm/bridge";+import { isWasm } from "../../wasm/utils";+import { BasicTransport } from "./basic";+import { SseTransport } from "./sse";+import { WsTransport } from "./ws";+import type { IConnectionTransport } from "./transport";++export interface ConnectionTransportOptions {+ url: () => string;+ static: boolean;+ transportType: "websocket" | "sse";+ headers: () => Record<string, string>;+}++export function createConnectionTransport(+ options: ConnectionTransportOptions,+): IConnectionTransport {+ if (options.static) {+ return BasicTransport.empty();+ }+ if (isWasm()) {+ return createPyodideConnection();+ }+ // Read the URL lazily to follow runtime redirects.+ if (options.transportType === "sse") {+ return new SseTransport(options.url, options.headers);+ }+ return new WsTransport(options.url);+}diff --git a/frontend/src/core/websocket/transports/transport.ts b/frontend/src/core/websocket/transports/transport.tsindex 2460845c2a..bd8c5e6e4b 100644--- a/frontend/src/core/websocket/transports/transport.ts+++ b/frontend/src/core/websocket/transports/transport.ts@@ -1,30 +1,19 @@/* Copyright 2026 Marimo. All rights reserved. */-export type ConnectionEvent = "open" | "close" | "message" | "error";-export interface IConnectionTransportMap {- open: WebSocketEventMap["open"];- message: WebSocketEventMap["message"];- close: WebSocketEventMap["close"];- error: WebSocketEventMap["error"];-}--export type ConnectionTransportCallback<T extends ConnectionEvent> = (- data: IConnectionTransportMap[T],-) => void;+import type {+ NotebookTransport,+ ConnectionEvent,+ ConnectionTransportCallback,+ IConnectionTransportMap,+} from "../../host/connection";+export type {+ ConnectionEvent,+ ConnectionTransportCallback,+ IConnectionTransportMap,+} from "../../host/connection";-export interface IConnectionTransport {- reconnect(code?: number | undefined, reason?: string | undefined): void;- close(): void;+export interface IConnectionTransport extends NotebookTransport {send(data: string | ArrayBuffer | Blob | ArrayBufferView<ArrayBuffer>): void;- addEventListener<T extends ConnectionEvent>(- event: T,- callback: ConnectionTransportCallback<T>,- ): void;- removeEventListener<T extends ConnectionEvent>(- event: T,- callback: ConnectionTransportCallback<T>,- ): void;- readyState: WebSocket["readyState"];}export class ConnectionSubscriptions {diff --git a/frontend/src/core/websocket/types.ts b/frontend/src/core/websocket/types.tsindex ec7c6f2903..cd0389684e 100644--- a/frontend/src/core/websocket/types.ts+++ b/frontend/src/core/websocket/types.ts@@ -1,47 +1,17 @@/* Copyright 2026 Marimo. All rights reserved. */+import type { ConnectionStatus as HostConnectionStatus } from "../host/connection";import type { NotificationMessageData } from "../kernel/messages";+export {+ ConnectionState,+ ConnectionClosedReason as WebSocketClosedReason,+} from "../host/connection";+export type ConnectionPhase =| NotificationMessageData<"startup-progress">["phase"]| "reconnecting";-export const ConnectionState = {- NOT_STARTED: "NOT_STARTED",- CONNECTING: "CONNECTING",- OPEN: "OPEN",- CLOSING: "CLOSING",- CLOSED: "CLOSED",-} as const;--export type ConnectionState =- (typeof ConnectionState)[keyof typeof ConnectionState];--export const WebSocketClosedReason = {- KERNEL_DISCONNECTED: "KERNEL_DISCONNECTED",- KERNEL_STARTUP_ERROR: "KERNEL_STARTUP_ERROR",-} as const;--export type WebSocketClosedReason =- (typeof WebSocketClosedReason)[keyof typeof WebSocketClosedReason];--export type ConnectionStatus =- | {- state: typeof ConnectionState.CLOSED;- code: WebSocketClosedReason;- /**- * Human-readable reason for closing the connection.- */- reason: string;- phase?: ConnectionPhase;- }- | {- state: typeof ConnectionState.CONNECTING;- phase?: ConnectionPhase;- }- | {- state:- | typeof ConnectionState.OPEN- | typeof ConnectionState.CLOSING- | typeof ConnectionState.NOT_STARTED;- };+export type ConnectionStatus = HostConnectionStatus & {+ phase?: ConnectionPhase;+};diff --git a/frontend/src/core/websocket/useNotebookClient.ts b/frontend/src/core/websocket/useNotebookClient.tsnew file mode 100644index 0000000000..7764ae06dc--- /dev/null+++ b/frontend/src/core/websocket/useNotebookClient.ts@@ -0,0 +1,80 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { useStore } from "jotai";+import { useEffect, useMemo } from "react";+import useEvent from "react-use-event-hook";+import { jsonParseWithSpecialChar } from "@/utils/json/json-parser";+import type {+ NotificationMessage,+ NotificationPayload,+} from "../kernel/messages";+import {+ createNotebookClient,+ type NotebookClient,+ type NotebookConnection,+} from "../host/notebook-client";+import { classifyCloseEvent } from "./connection-state";+import {+ createConnectionTransport,+ type ConnectionTransportOptions,+} from "./transports/create";++type Options = ConnectionTransportOptions & {+ sessionId: string;+ messageFormat: NotebookConnection["messageFormat"];+ waitUntilReady: () => Promise<void>;+ checkHealth: () => Promise<boolean>;+ onNotification: (notification: NotificationPayload) => void;+ onMessageError: NotebookConnection["onMessageError"];+};++export function useNotebookClient(options: Options): NotebookClient {+ const store = useStore();+ const { sessionId, static: isStatic, transportType, messageFormat } = options;+ const controller = useMemo(() => createNotebookClient(store), [store]);+ const url = useEvent(options.url);+ const headers = useEvent(options.headers);+ const waitUntilReady = useEvent(options.waitUntilReady);+ const checkHealth = useEvent(options.checkHealth);+ const onNotification = useEvent(options.onNotification);+ const onMessageError = useEvent(options.onMessageError);++ useEffect(() => {+ const lifetime = new AbortController();+ controller.connect({+ createTransport: (url) =>+ createConnectionTransport({+ url,+ headers,+ static: isStatic,+ transportType,+ }),+ url,+ messageFormat,+ signal: lifetime.signal,+ waitUntilReady,+ checkHealth,+ onMessageError,+ // The host validates the envelope, not the native notification contents.+ onNotification: (notification) =>+ onNotification({ data: notification as NotificationMessage }),+ decodeJson: jsonParseWithSpecialChar,+ classifyClose: classifyCloseEvent,+ });+ return () => lifetime.abort();+ }, [+ controller,+ sessionId,+ isStatic,+ transportType,+ messageFormat,+ url,+ headers,+ waitUntilReady,+ checkHealth,+ onNotification,+ onMessageError,+ ]);++ return controller.client;+}diff --git a/frontend/src/core/websocket/useMarimoKernelConnection.tsx b/frontend/src/core/websocket/useNotebookSession.tsxsimilarity index 67%rename from frontend/src/core/websocket/useMarimoKernelConnection.tsxrename to frontend/src/core/websocket/useNotebookSession.tsxindex 07e6fcb356..53055bdab5 100644--- a/frontend/src/core/websocket/useMarimoKernelConnection.tsx+++ b/frontend/src/core/websocket/useNotebookSession.tsx@@ -1,8 +1,8 @@/* Copyright 2026 Marimo. All rights reserved. */import { invalidatePackageData } from "@/core/packages/package-data";-import { useAtom, useAtomValue, useSetAtom } from "jotai";-import { useRef } from "react";+import { useAtom, useAtomValue, useSetAtom, useStore } from "jotai";+import { useLayoutEffect } from "react";import { useErrorBoundary } from "react-error-boundary";import { toast } from "@/components/ui/use-toast";import { attachmentsAtom } from "@/core/attachments/state";@@ -13,8 +13,7 @@ import type {NotificationMessageData,NotificationPayload,} from "@/core/kernel/messages";-import { TRANSPORT_EXHAUSTED_REASON } from "@/core/websocket/transports/ws";-import { useConnectionTransport } from "@/core/websocket/useWebSocket";+import { useNotebookClient } from "@/core/websocket/useNotebookClient";import { renderHTML } from "@/plugins/core/RenderHTML";import {handleWidgetMessage,@@ -22,11 +21,7 @@ import {} from "@/plugins/impl/anywidget/registry";import { logNever } from "@/utils/assertNever";import { prettyError } from "@/utils/errors";-import {- type JsonString,- safeExtractSetUIElementMessageBuffers,-} from "@/utils/json/base64";-import { jsonParseWithSpecialChar } from "@/utils/json/json-parser";+import { safeExtractSetUIElementMessageBuffers } from "@/utils/json/base64";import { Logger } from "@/utils/Logger";import { reloadSafe } from "@/utils/reload-safe";import { useAlertActions } from "../alerts/state";@@ -71,7 +66,7 @@ import { type LayoutState, useLayoutActions } from "../layout/state";import { kioskModeAtom } from "../mode";import { connectionAtom, startupProgressAtom } from "../network/connection";import type { RequestId } from "../network/DeferredRequestRegistry";-import { useRuntimeManager } from "../runtime/config";+import { runtimeConfigAtom, useRuntimeManager } from "../runtime/config";import { SECRETS_REGISTRY } from "../secrets/request-registry";import { isStaticNotebook } from "../static/static-state";import {@@ -82,104 +77,10 @@ import { useStorageActions } from "../storage/state";import { useVariablesActions } from "../variables/state";import type { VariableName } from "../variables/types";import { isWasm } from "../wasm/utils";-import {- type ConnectionStatus,- WebSocketClosedReason,- ConnectionState,-} from "./types";+import { WebSocketClosedReason, ConnectionState } from "./types";const SUPPORTS_LAZY_KERNELS = true;-// All MARIMO_* reasons except TRANSPORT_EXHAUSTED are emitted by the backend-// (marimo/_server/api/endpoints/ws_endpoint.py and ws/*.py). Keep in sync with-// the backend literals. Over the SSE transport these arrive as in-band-// `close` events rather than WebSocket close frames, so every terminal-// reason must be classified here — an unclassified reason falls into the-// retry path.-export type CloseReason =- | "MARIMO_NO_FILE_KEY"- | "MARIMO_NO_SESSION_ID"- | "MARIMO_NO_SESSION"- | "MARIMO_SHUTDOWN"- | "MARIMO_KERNEL_STARTUP_ERROR"- | "MARIMO_UNAUTHORIZED"- | "MARIMO_KIOSK_NOT_ALLOWED"- | typeof TRANSPORT_EXHAUSTED_REASON;--export type CloseDecision =- | { kind: "terminal"; status: ConnectionStatus; closeTransport: boolean }- | { kind: "gave-up"; status: ConnectionStatus }- | { kind: "retry"; status: ConnectionStatus };--export function classifyCloseEvent(event: { reason?: string }): CloseDecision {- switch (event.reason as CloseReason | undefined) {- case TRANSPORT_EXHAUSTED_REASON:- return {- kind: "gave-up",- status: {- state: ConnectionState.CLOSED,- code: WebSocketClosedReason.KERNEL_DISCONNECTED,- reason: "kernel not found",- },- };- case "MARIMO_NO_FILE_KEY":- case "MARIMO_NO_SESSION_ID":- case "MARIMO_NO_SESSION":- case "MARIMO_SHUTDOWN":- return {- kind: "terminal",- status: {- state: ConnectionState.CLOSED,- code: WebSocketClosedReason.KERNEL_DISCONNECTED,- reason: "kernel not found",- },- closeTransport: true,- };- case "MARIMO_UNAUTHORIZED":- return {- kind: "terminal",- status: {- state: ConnectionState.CLOSED,- code: WebSocketClosedReason.KERNEL_DISCONNECTED,- reason: "not authorized",- },- closeTransport: true,- };- case "MARIMO_KIOSK_NOT_ALLOWED":- return {- kind: "terminal",- status: {- state: ConnectionState.CLOSED,- code: WebSocketClosedReason.KERNEL_DISCONNECTED,- reason: "kiosk mode is not available for this session",- },- closeTransport: true,- };- case "MARIMO_KERNEL_STARTUP_ERROR":- return {- kind: "terminal",- status: {- state: ConnectionState.CLOSED,- code: WebSocketClosedReason.KERNEL_STARTUP_ERROR,- reason: "Failed to start kernel sandbox",- },- closeTransport: true,- };- default:- // Empty/undefined reasons are normal transient closes. Anything else is- // an unknown server reason; warn so a new MARIMO_* reason doesn't fall- // silently into the retry path.- if (event.reason) {- logNever(event.reason as never);- }- }-- return {- kind: "retry",- status: { state: ConnectionState.CONNECTING },- };-}-function getExistingCells(): CellData[] | undefined {if (!SUPPORTS_LAZY_KERNELS) {return undefined;@@ -191,16 +92,12 @@ function getExistingCells(): CellData[] | undefined {);}-/**- * Creates a connection to the Marimo kernel and handles incoming messages.- */-export function useMarimoKernelConnection(opts: {+/** Coordinate session startup and apply notifications to the editor. */+export function useNotebookSession(opts: {sessionId: SessionId;autoInstantiate: boolean;setCells: (cells: CellData[], layout: LayoutState) => void;}) {- // Track whether we want to try reconnecting.- const shouldTryReconnecting = useRef<boolean>(true);const { autoInstantiate, sessionId, setCells } = opts;const { showBoundary } = useErrorBoundary();@@ -237,26 +134,26 @@ export function useMarimoKernelConnection(opts: {} = useAlertActions();const setKioskMode = useSetAtom(kioskModeAtom);const setStableSessionId = useSetAtom(stableSessionIdAtom);- const setAttachments = useSetAtom(attachmentsAtom);const setCapabilities = useSetAtom(capabilitiesAtom);const runtimeManager = useRuntimeManager();+ const { notebookId } = useAtomValue(runtimeConfigAtom);const transportType = useAtomValue(connectionTransportTypeAtom);const setCacheInfo = useSetAtom(cacheInfoAtom);const setKernelStartupError = useSetAtom(kernelStartupErrorAtom);+ const setAttachments = useSetAtom(attachmentsAtom);const {setNamespaces: setStorageNamespaces,filterFromVariables: filterStorageFromVariables,} = useStorageActions();- const handleMessage = (e: MessageEvent<JsonString<NotificationPayload>>) => {- const msg = jsonParseWithSpecialChar(e.data);+ const handleNotification = (msg: NotificationPayload) => {switch (msg.data.op) {- case "reload":- reloadSafe();- return;case "attachments":setAttachments(msg.data.attachments);return;+ case "reload":+ reloadSafe();+ return;case "startup-progress": {const { phase } = msg.data;updateStartupProgress(msg.data);@@ -511,109 +408,59 @@ export function useMarimoKernelConnection(opts: {}};- const tryReconnecting = (code?: number, reason?: string) => {- // If not properly gated, we could try reconnecting forever if the- // issue is not transient. So we want to try reconnecting only once after an- // open connection is closed.- if (shouldTryReconnecting.current) {- shouldTryReconnecting.current = false;- ws.reconnect(code, reason);- }+ const store = useStore();+ const onMessageError = (error: unknown) => {+ toast({+ title: "Failed to handle message",+ description: prettyError(error),+ variant: "danger",+ });};-- // Manual reconnect. Probes /health first to fail fast when the runtime- // is unreachable, instead of waiting on partysocket's retry budget.- const reconnect = async () => {- if (- ws.readyState === WebSocket.OPEN ||- ws.readyState === WebSocket.CONNECTING- ) {- return;- }- shouldTryReconnecting.current = true;- setKernelStartupError(null);- setConnection({ state: ConnectionState.CONNECTING });- const healthy = await runtimeManager.reconcileFromHealth();- if (!healthy) {- shouldTryReconnecting.current = false;- setConnection({- state: ConnectionState.CLOSED,- code: WebSocketClosedReason.KERNEL_DISCONNECTED,- reason: "kernel not found",- });- return;- }- ws.reconnect();- };-- const ws = useConnectionTransport({+ const notebook = useNotebookClient({+ sessionId,static: isStaticNotebook(),transportType,- /**- * Unique URL for this session.- */+ messageFormat:+ notebookId && transportType === "websocket" ? "host" : "session",url: () =>transportType === "sse"? runtimeManager.getSseURL(sessionId).toString(): runtimeManager.getWsURL(sessionId).toString(),- /**- * Auth headers for the SSE transport. WebSockets cannot send headers- * and instead put the access token in the URL.- */+ // SSE uses headers for auth. WebSockets carry the token in the URL.headers: () => runtimeManager.headers(),-- /**- * The transport is open; kernel-ready establishes session readiness.- */- onOpen: async () => {- updateStartupProgress(null);- setAttachments([]);- // If we are open, we can reset our reconnecting flag.- shouldTryReconnecting.current = true;- },-- /**- * Wait to connect, in case the remote kernel still starting up.- */- waitToConnect: async () => {- if (isStaticNotebook()) {- return;- }- if (isWasm()) {- return;- }-- if (runtimeManager.isSameOrigin) {- return;+ waitUntilReady: async () => {+ if (!isStaticNotebook() && !isWasm() && !runtimeManager.isSameOrigin) {+ await runtimeManager.waitForHealthy();}- await runtimeManager.waitForHealthy();},-- /**- * Handle messages sent by the kernel.- */- onMessage: (e) => {+ checkHealth: () => runtimeManager.reconcileFromHealth(),+ onMessageError,+ onNotification: (notification) => {try {- handleMessage(e);+ handleNotification(notification);} catch (error) {- Logger.error("Failed to handle message", e.data, error);- toast({- title: "Failed to handle message",- description: prettyError(error),- variant: "danger",- });+ Logger.error("Failed to handle notification", notification, error);+ onMessageError(error);}},+ });- /**- * Handle a close event. We may want to reconnect.- */- onClose: (e) => {- Logger.warn("WebSocket closed", e.code, e.reason);+ // Subscribe before passive connection setup: static/WASM transports can emit synchronously.+ useLayoutEffect(() => {+ const updateConnection = () => {+ const status = store.get(notebook.connectionAtom);+ if (status.state === ConnectionState.NOT_STARTED) {+ return;+ }setAttachments([]);- const decision = classifyCloseEvent(e);+ if (status.state === ConnectionState.OPEN) {+ updateStartupProgress(null);+ return; // kernel-ready, not the socket, establishes session readiness.+ }+ if (status.state === ConnectionState.CONNECTING) {+ setKernelStartupError(null);+ }setConnection((previous) => {- const status = decision.status;if (status.state === ConnectionState.CLOSED &&status.code === WebSocketClosedReason.KERNEL_STARTUP_ERROR &&@@ -632,32 +479,18 @@ export function useMarimoKernelConnection(opts: {}return status;});- if (decision.kind === "terminal" && decision.closeTransport) {- ws.close(); // close to prevent reconnecting- return;- }- if (decision.kind === "retry") {- // Session should be valid- // - browser tab might have been closed or re-opened- // - computer might have just woken from sleep- tryReconnecting(e.code, e.reason);- }- },-- /**- * When we encounter an error, we should close the connection.- */- onError: (e) => {- Logger.warn("WebSocket error", e);- setAttachments([]);- setConnection({- state: ConnectionState.CLOSED,- code: WebSocketClosedReason.KERNEL_DISCONNECTED,- reason: "kernel not found",- });- tryReconnecting();- },- });-- return { connection, reconnect };+ };+ const unsubscribe = store.sub(notebook.connectionAtom, updateConnection);+ updateConnection();+ return unsubscribe;+ }, [+ notebook,+ store,+ setConnection,+ setAttachments,+ setKernelStartupError,+ updateStartupProgress,+ ]);++ return { notebook, connection, reconnect: notebook.reconnect };}diff --git a/frontend/src/core/websocket/useWebSocket.tsx b/frontend/src/core/websocket/useWebSocket.tsxdeleted file mode 100644index 48e12823fe..0000000000--- a/frontend/src/core/websocket/useWebSocket.tsx+++ /dev/null@@ -1,88 +0,0 @@-/* Copyright 2026 Marimo. All rights reserved. */--import { useEffect, useState } from "react";-import { Logger } from "@/utils/Logger";-import { createPyodideConnection } from "../wasm/bridge";-import { isWasm } from "../wasm/utils";-import { BasicTransport } from "./transports/basic";-import { SseTransport } from "./transports/sse";-import { WsTransport } from "./transports/ws";-import type { IConnectionTransport } from "./transports/transport";--interface UseConnectionTransportOptions {- url: () => string;- static: boolean;- transportType: "websocket" | "sse";- /** Request headers for the SSE transport (auth); unused by WebSockets. */- headers: () => Record<string, string>;- waitToConnect: () => Promise<void>;- onOpen: (event: WebSocketEventMap["open"]) => void;- onMessage: (event: WebSocketEventMap["message"]) => void;- onClose: (event: WebSocketEventMap["close"]) => void;- onError: (event: WebSocketEventMap["error"]) => void;-}--export function createConnectionTransport(- options: Pick<- UseConnectionTransportOptions,- "url" | "static" | "transportType" | "headers"- >,-): IConnectionTransport {- if (options.static) {- return BasicTransport.empty();- }- if (isWasm()) {- return createPyodideConnection();- }- // urlProvider is passed lazily; it may change after a runtime redirect.- if (options.transportType === "sse") {- return new SseTransport(options.url, options.headers);- }- return new WsTransport(options.url);-}--/**- * A hook for creating a connection transport with React.- */-export function useConnectionTransport(options: UseConnectionTransportOptions) {- const { onOpen, onMessage, onClose, onError, waitToConnect } = options;-- // oxlint-disable-next-line react/hook-use-state- const [transport] = useState<IConnectionTransport>(() => {- const socket = createConnectionTransport(options);-- socket.addEventListener("open", onOpen);- socket.addEventListener("close", onClose);- socket.addEventListener("error", onError);- socket.addEventListener("message", onMessage);-- return socket;- });-- useEffect(() => {- // If it's closed, reconnect- // This starts closed, so we need to connect for the first time- if (transport.readyState === WebSocket.CLOSED) {- void waitToConnect()- .then(() => transport.reconnect())- .catch((error) => {- Logger.error("Healthy connection never made", error);- transport.close();- });- }-- return () => {- Logger.warn(- "useConnectionTransport is unmounting. This likely means there is a bug.",- );- transport.close();- transport.removeEventListener("open", onOpen);- transport.removeEventListener("close", onClose);- transport.removeEventListener("error", onError);- transport.removeEventListener("message", onMessage);- };- // oxlint-disable-next-line react-hooks/exhaustive-deps- }, [transport]);-- return transport;-}diff --git a/frontend/src/mount.tsx b/frontend/src/mount.tsxindex 213da3ea2a..f95561747d 100644--- a/frontend/src/mount.tsx+++ b/frontend/src/mount.tsx@@ -274,6 +274,8 @@ const mountOptionsSchema = z.object({.transform((val) => val as api.Notebook["NotebookV1"]),]),+ notebookId: z.string().optional(),+/*** Runtime configs*/@@ -284,6 +286,7 @@ const mountOptionsSchema = z.object({// Lazy by default, but can be overridden by the runtime configlazy: z.boolean().default(true),authToken: z.string().nullish(),+ notebookId: z.string().optional(),}),).nullish()@@ -364,6 +367,7 @@ function initStore(options: unknown) {} else {store.set(runtimeConfigAtom, {...DEFAULT_RUNTIME_CONFIG,+ notebookId: parsedOptions.data.notebookId,lazy: false,serverToken: parsedOptions.data.serverToken,});diff --git a/marimo/_server/api/endpoints/assets.py b/marimo/_server/api/endpoints/assets.pyindex d7ac82ce6a..ce63c27b72 100644--- a/marimo/_server/api/endpoints/assets.py+++ b/marimo/_server/api/endpoints/assets.py@@ -50,6 +50,8 @@ from marimo._utils.paths import (if TYPE_CHECKING:from starlette.requests import Request+ from marimo._server.host.context import HostContext+LOGGER = _loggers.marimo_logger()# Router for serving static assets@@ -415,6 +417,21 @@ async def index(request: Request) -> Response:except ValueError:pass # Keep absolute if not under directory+ notebook_id = None+ context: HostContext | None = getattr(+ request.app.state, "host_context", None+ )+ if (+ context is not None+ and absolute_filepath+ and not app_state.remote_url+ ):+ record = context.bridge.index.notebook_for(absolute_filepath)+ if record is None:+ record = context.bridge.index.ensure(absolute_filepath)+ if record is not None:+ notebook_id = record.id+html = notebook_page_template(html=html,base_url=app_state.base_url,@@ -427,6 +444,7 @@ async def index(request: Request) -> Response:lsp_workspace=lsp_workspace,mode=app_state.mode,notebook_snapshot=notebook_snapshot,+ notebook_id=notebook_id,runtime_config=[{"url": app_state.remote_url}]if app_state.remote_urlelse None,diff --git a/marimo/_templates.py b/marimo/_templates.pyindex 75d232487a..c23045f5b3 100644--- a/marimo/_templates.py+++ b/marimo/_templates.py@@ -108,6 +108,7 @@ def _get_mount_config(session_snapshot: NotebookSessionV1 | None = None,notebook_snapshot: NotebookV1 | None = None,runtime_config: list[dict[str, Any]] | None = None,+ notebook_id: str | None = None,layout: LayoutConfig | None = None,) -> str:"""@@ -146,6 +147,11 @@ def _get_mount_config("hostEnabled": GLOBAL_SETTINGS.ENABLE_HOST and mode == "edit",})+ host_notebook = (+ ',\n "notebookId": ' + json_script(notebook_id)+ if notebook_id is not None+ else ""+ )return """{{"filename": {filename},@@ -161,12 +167,13 @@ def _get_mount_config("view": {view},"notebook": {notebook},"session": {session},- "runtimeConfig": {runtime_config},+ "runtimeConfig": {runtime_config}{host_notebook},"pairConfig": {pair_config}}}""".format(**{k: json_script(v) for k, v in options.items()},pair_config=pair_config,+ host_notebook=host_notebook,).strip()@@ -300,6 +307,7 @@ def notebook_page_template(session_snapshot: NotebookSessionV1 | None = None,notebook_snapshot: NotebookV1 | None = None,runtime_config: list[dict[str, Any]] | None = None,+ notebook_id: str | None = None,asset_url: str | None = None,html_head: str | None = None,execute_opengraph_generators: bool = False,@@ -343,6 +351,7 @@ def notebook_page_template(config_overrides=config_overrides,app_config=app_config,runtime_config=runtime_config,+ notebook_id=notebook_id,notebook_snapshot=notebook_snapshot,session_snapshot=session_snapshot,),diff --git a/protocols/host/README.md b/protocols/host/README.mdindex 8f2ce43e93..5fd954f94e 100644--- a/protocols/host/README.md+++ b/protocols/host/README.md@@ -14,6 +14,13 @@ The OpenAPI schema is the source of truth for the Python types in`frontend/src/core/host/protocol.ts`. The frontend generator also adds thenative `marimo` event with an `unknown` payload.+With `MARIMO_ENABLE_HOST=1`, the editor consumes host events over WebSockets+when its runtime configuration includes a `notebookId`. With+`server.transport = "sse"`, it continues using the legacy `/sse` session+stream, even when a notebook ID is available. The host's SSE endpoint serves+protocol consumers but does not establish the editor session; editor support+requires that session integration as well as host event framing.+Generate and check the Python bindings from the repository root:```shdiff --git a/tests/_server/api/endpoints/test_assets.py b/tests/_server/api/endpoints/test_assets.pyindex 6a4e6129ca..8f1dcf9d70 100644--- a/tests/_server/api/endpoints/test_assets.py+++ b/tests/_server/api/endpoints/test_assets.py@@ -17,6 +17,8 @@ from marimo._server.api.endpoints.assets import (DEFAULT_NOTEBOOK_NAME,_inject_service_worker,)+from marimo._server.host.bridge import SessionBridge+from marimo._server.host.context import HostContextfrom marimo._server.workspace import (DirectoryWorkspace,EmptyWorkspace,@@ -32,6 +34,7 @@ from tests._server.mocks import (with_workspace,workspace_scope,)+from tests._server.templates.utils import parse_mount_configif TYPE_CHECKING:from starlette.testclient import TestClient@@ -977,3 +980,40 @@ def test_serve_static_allowed_files(client: TestClient) -> None:assert response.status_code in (200, 404), (f"Unexpected status {response.status_code} for {name!r}")++[email protected]("remote_url", [None, "https://remote.example"])[email protected]("cataloged", [True, False])+def test_index_supplies_the_local_host_notebook_identity(+ client: TestClient, remote_url: str | None, cataloged: bool+) -> None:+ state = AppState.from_app(cast(Any, client.app))+ bridge = SessionBridge(state.session_manager)+ bridge.index.refresh()+ (original_id,) = bridge.host.notebooks+ if not cataloged:+ bridge.index.forget(original_id)+ initial_notebooks = dict(bridge.host.notebooks)+ client.app.state.host_context = HostContext(+ bridge=bridge, token="host-token", port=1234+ ) # type: ignore[union-attr]+ client.app.state.remote_url = remote_url # type: ignore[union-attr]+ response = client.get("/", headers=token_header())+ assert response.status_code == 200+ config = parse_mount_config(response.text)+ if remote_url is not None:+ assert config.get("notebookId") is None+ assert bridge.host.notebooks == initial_notebooks+ else:+ (notebook_id,) = bridge.host.notebooks+ assert config.get("notebookId") == notebook_id+ if cataloged:+ assert notebook_id == original_id+ notebooks = dict(bridge.host.notebooks)+ reloaded = client.get("/", headers=token_header())+ assert reloaded.status_code == 200+ assert (+ parse_mount_config(reloaded.text).get("notebookId") == notebook_id+ )+ assert bridge.host.notebooks == notebooks+ assert not state.session_manager.sessions