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.

Consume host events in edit and app mode (#11357)

Trevor Manzebcd855a616d
diff --git a/frontend/src/__tests__/mount.test.ts b/frontend/src/__tests__/mount.test.ts
index 328210f8b3..72140c4b80 100644
--- a/frontend/src/__tests__/mount.test.ts
+++ b/frontend/src/__tests__/mount.test.ts
@@ -6,7 +6,6 @@ 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";
@@ -102,20 +101,6 @@ describe("mount", () => {
});
describe("connection state initialization", () => {
- it("uses the remote runtime's framing instead of the page's", () => {
- mount(
- {
- ...baseOptions,
- messageFormat: "host",
- runtimeConfig: [
- { url: "https://remote.example", messageFormat: "session" },
- ],
- },
- mockElement,
- );
- expect(store.get(runtimeConfigAtom).messageFormat).toBe("session");
- });
-
it("should set connection to CONNECTING when runtimeConfig has lazy=false", () => {
mount(
{
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 898e8b77d1..2a025bf827 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
@@ -16,6 +16,7 @@ import { TooltipProvider } from "@/components/ui/tooltip";
import { toast } from "@/components/ui/use-toast";
import type { Attachment } from "@/core/attachments/state";
import { pairConfigAtom } from "@/core/config/pair";
+import { createNotebookClient } from "@/core/host/notebook-client";
import {
type StableSessionId,
stableSessionIdAtom,
@@ -45,10 +46,9 @@ 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,
connectionAtom: atom({ state: ConnectionState.OPEN }),
- documentAtom: atom(null),
attachmentsAtom,
- reconnect: async () => undefined,
});
store.set(attachmentsAtom, attachments);
store.set(stableSessionIdAtom, "stable/test" as StableSessionId);
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 8404d1350b..d8681ae10f 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
@@ -25,6 +25,7 @@ import {
} from "@/core/cells/error-report";
import { pairConfigAtom } from "@/core/config/pair";
import { notebookStateFromSession } from "@/core/cells/session";
+import { createNotebookClient } from "@/core/host/notebook-client";
import type { MarimoError, OutputMessage } from "@/core/kernel/messages";
import {
type StableSessionId,
@@ -97,10 +98,9 @@ function renderButton({
store.set(connectionAtom, { state: ConnectionState.OPEN });
store.set(pairConfigAtom, { ...PAIR_CONFIG, hostEnabled: preview });
store.set(notebookClientAtom, {
+ ...createNotebookClient(store).client,
connectionAtom: atom({ state: ConnectionState.OPEN }),
- documentAtom: atom(null),
attachmentsAtom,
- reconnect: async () => undefined,
});
store.set(attachmentsAtom, attachments);
store.set(stableSessionIdAtom, stableId);
diff --git a/frontend/src/core/host/__tests__/notebook-client.test.ts b/frontend/src/core/host/__tests__/notebook-client.test.ts
index 6ae20a2b57..f76ebe9850 100644
--- a/frontend/src/core/host/__tests__/notebook-client.test.ts
+++ b/frontend/src/core/host/__tests__/notebook-client.test.ts
@@ -49,12 +49,10 @@ function setup(url: () => string = () => "ws://localhost/ws") {
return transport;
},
url,
- messageFormat: "host",
signal,
waitUntilReady: () => healthy.promise,
checkHealth,
onNotification: (notification) => onNotification({ data: notification }),
- onMessageError: vi.fn(),
decodeJson: jsonParseWithSpecialChar,
classifyClose: classifyCloseEvent,
});
@@ -76,6 +74,71 @@ function setup(url: () => string = () => "ws://localhost/ws") {
}
describe("NotebookClient lifetime", () => {
+ it("exposes identity and capabilities only after the notebook is ready", async () => {
+ const { connect, healthy, events, receive, client, store } = setup();
+ const lifetime = new AbortController();
+ connect(lifetime.signal);
+ healthy.resolve();
+ await healthy.promise;
+ events.dispatchEvent(new Event("open"));
+ const notebook = {
+ id: "nb/with space",
+ project_id: "p1",
+ path: null,
+ name: "Notebook",
+ operations: ["notebook.edit"],
+ updated_at: null,
+ };
+ receive({ event: "notebook", data: { notebook } });
+ expect(store.get(client.notebookAtom)).toBeNull();
+ receive({ event: "ready", id: "1", data: {} });
+ expect(store.get(client.notebookAtom)).toEqual(notebook);
+ receive({
+ event: "notebook",
+ id: "2",
+ data: { notebook: { ...notebook, operations: [] } },
+ });
+ expect(store.get(client.notebookAtom)?.operations).toEqual([]);
+ receive({ event: "notebook.removed", id: "3", data: { id: notebook.id } });
+ expect(store.get(client.notebookAtom)).toBeNull();
+ lifetime.abort();
+ });
+
+ it("rebuilds the replica after a reconnect reset selects a new notebook", async () => {
+ const notebookId = "n2";
+ const { connect, events, healthy, urls, receive, client, store } = setup(
+ () => "ws://localhost/ws?session_id=visitor",
+ );
+ const lifetime = new AbortController();
+ connect(lifetime.signal);
+ healthy.resolve();
+ await healthy.promise;
+ events.dispatchEvent(new Event("open"));
+ fixtureMessages("notebook-events.sse").forEach(receive);
+ expect(store.get(client.documentAtom)?.revision.notebook_id).toBe("n1");
+
+ events.dispatchEvent(new CloseEvent("close"));
+ expect(urls.at(-1)?.searchParams.get("cursor")).toBe("97");
+ expect(store.get(client.documentAtom)?.revision.notebook_id).toBe("n1");
+ expect(store.get(client.notebookAtom)).toBeNull();
+ events.dispatchEvent(new Event("open"));
+ receive({ event: "reset", data: {} });
+ expect(store.get(client.documentAtom)).toBeNull();
+ for (const event of fixtureMessages("notebook-events.sse")) {
+ receive(
+ JSON.parse(
+ JSON.stringify(event).replaceAll('"n1"', JSON.stringify(notebookId)),
+ ),
+ );
+ }
+ expect(store.get(client.documentAtom)?.revision.notebook_id).toBe(
+ notebookId,
+ );
+ expect(store.get(client.connectionAtom).state).toBe(ConnectionState.OPEN);
+ expect(store.get(client.notebookAtom)?.id).toBe(notebookId);
+ lifetime.abort();
+ });
+
it.each(["{broken", JSON.stringify({ event: "ready", data: {} })])(
"stops consuming a malformed host stream: %s",
(data) => {
@@ -423,7 +486,7 @@ describe("NotebookClient attachments", () => {
},
);
- it("keeps legacy sessions empty", async () => {
+ it("keeps host resources empty for notification-only WASM connections", async () => {
const { client, store, receive, lifetime } = await open();
receive({ data: { op: "kernel-ready" } });
receive({ data: { op: "reconnected" } });
diff --git a/frontend/src/core/host/events.ts b/frontend/src/core/host/events.ts
index aa80e4eed2..f982aaef5d 100644
--- a/frontend/src/core/host/events.ts
+++ b/frontend/src/core/host/events.ts
@@ -10,15 +10,6 @@ import * as Protocol from "@marimo-team/client/protocol";
* 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",
- "attachment",
- "marimo",
-] as const satisfies readonly (Protocol.ObjectType | "marimo")[];
-
const envelope = z.object({
event: z.string().min(1),
data: z.unknown(),
@@ -54,7 +45,7 @@ export type NotebookEvent =
const sessionEnvelope = z.object({ data: z.unknown() });
/**
- * Decode a host event or a legacy `{ data: notification }` session message.
+ * Decode a host event or an in-process WASM `{ data: notification }` message.
*
* Throws if the envelope or a known event is malformed. Native notification
* payloads are passed through for the session handler to interpret.
diff --git a/frontend/src/core/host/notebook-client.ts b/frontend/src/core/host/notebook-client.ts
index 2fa379b6d1..69b61300bb 100644
--- a/frontend/src/core/host/notebook-client.ts
+++ b/frontend/src/core/host/notebook-client.ts
@@ -1,7 +1,7 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { Logger } from "@/utils/Logger";
-import type { Attachment } from "@marimo-team/client/protocol";
+import type { Attachment, NotebookOutput } from "@marimo-team/client/protocol";
import { createReducer } from "@marimo-team/client/reducer";
import { type Atom, atom, type createStore } from "jotai/vanilla";
import {
@@ -27,6 +27,8 @@ const UNCURSORED = new Set<NotebookEvent["event"]>([
export interface NotebookClient {
/** Client connection status, independent of application session readiness. */
readonly connectionAtom: Atom<ConnectionStatus>;
+ /** Identity and capabilities, available while the stream is connected and ready. */
+ readonly notebookAtom: Atom<NotebookOutput | null>;
/**
* The most recently confirmed document.
*
@@ -47,8 +49,6 @@ export interface NotebookConnection {
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. */
@@ -59,8 +59,6 @@ export interface NotebookConnection {
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;
}
@@ -75,6 +73,11 @@ export function createNotebookClient(store: ReturnType<typeof createStore>) {
const streamAtom = atom(reducer.initial);
// A resumed stream is live, but presence waits for this connection's ready.
const readyAtom = atom(false);
+ const notebookAtom = atom((get) =>
+ get(readyAtom) && get(connectionAtom).state === ConnectionState.OPEN
+ ? get(streamAtom).notebook
+ : null,
+ );
const documentAtom = atom(
(get) => get(streamAtom).resources.document.current,
);
@@ -86,6 +89,7 @@ export function createNotebookClient(store: ReturnType<typeof createStore>) {
let reconnect: (() => Promise<void>) | undefined;
const client: NotebookClient = {
connectionAtom,
+ notebookAtom,
documentAtom,
attachmentsAtom,
reconnect: async () => reconnect?.(),
@@ -94,12 +98,10 @@ export function createNotebookClient(store: ReturnType<typeof createStore>) {
function connect({
createTransport,
url,
- messageFormat,
signal,
waitUntilReady,
checkHealth,
onNotification,
- onMessageError,
decodeJson,
classifyClose,
}: NotebookConnection) {
@@ -113,9 +115,6 @@ export function createNotebookClient(store: ReturnType<typeof createStore>) {
// The id of the last live event. Null before `ready` and after `reset`.
let cursor: string | null = null;
const transport = createTransport(() => {
- if (messageFormat === "session") {
- return url();
- }
const next = new URL(url());
next.searchParams.delete("cursor");
if (signal.aborted) {
@@ -131,11 +130,9 @@ export function createNotebookClient(store: ReturnType<typeof createStore>) {
// A live stream keeps its state and resumes from the cursor. An
// incomplete snapshot starts over.
const state =
- key !== streamKey
+ key !== streamKey || current.phase === "snapshot"
? reducer.initial
- : current.phase === "snapshot"
- ? { ...reducer.initial, notebookId: current.notebookId }
- : current;
+ : current;
if (state.phase === "snapshot") {
cursor = null;
}
@@ -226,10 +223,6 @@ export function createNotebookClient(store: ReturnType<typeof createStore>) {
}
} catch (error) {
Logger.error("Failed to decode notebook message", error);
- if (messageFormat === "session") {
- onMessageError(error);
- return;
- }
store.set(streamAtom, reducer.initial);
cursor = null;
terminal = true;
diff --git a/frontend/src/core/runtime/__tests__/createWsUrl.test.ts b/frontend/src/core/runtime/__tests__/createWsUrl.test.ts
index 6159eeadc4..91e196992a 100644
--- a/frontend/src/core/runtime/__tests__/createWsUrl.test.ts
+++ b/frontend/src/core/runtime/__tests__/createWsUrl.test.ts
@@ -13,7 +13,9 @@ describe("RuntimeManager.getWsURL", () => {
});
const sessionId = "1234" as SessionId;
const url = runtime.getWsURL(sessionId);
- expect(url.toString()).toBe("wss://marimo.app/ws?session_id=1234");
+ expect(url.toString()).toBe(
+ "wss://marimo.app/ws?session_id=1234&message_format=host",
+ );
expect(url.searchParams.get(KnownQueryParams.sessionId)).toBe(sessionId);
});
@@ -24,7 +26,9 @@ describe("RuntimeManager.getWsURL", () => {
});
const sessionId = "1234" as SessionId;
const url = runtime.getWsURL(sessionId);
- expect(url.toString()).toBe("ws://marimo.app/ws?session_id=1234");
+ expect(url.toString()).toBe(
+ "ws://marimo.app/ws?session_id=1234&message_format=host",
+ );
expect(url.searchParams.get(KnownQueryParams.sessionId)).toBe(sessionId);
});
@@ -35,7 +39,9 @@ describe("RuntimeManager.getWsURL", () => {
});
const sessionId = "1234" as SessionId;
const url = runtime.getWsURL(sessionId);
- expect(url.toString()).toBe("ws://marimo.app/nested/ws?session_id=1234");
+ expect(url.toString()).toBe(
+ "ws://marimo.app/nested/ws?session_id=1234&message_format=host",
+ );
expect(url.searchParams.get(KnownQueryParams.sessionId)).toBe(sessionId);
});
@@ -48,7 +54,7 @@ describe("RuntimeManager.getWsURL", () => {
const sessionId = "1234" as SessionId;
const url = runtime.getWsURL(sessionId);
expect(url.toString()).toBe(
- "ws://marimo.app/nested/ws?foo=bar&file=test.py&session_id=1234",
+ "ws://marimo.app/nested/ws?foo=bar&file=test.py&session_id=1234&message_format=host",
);
expect(url.searchParams.get(KnownQueryParams.sessionId)).toBe(sessionId);
});
@@ -62,7 +68,7 @@ describe("RuntimeManager.getWsURL", () => {
const sessionId = "1234" as SessionId;
const url = runtime.getWsURL(sessionId);
expect(url.toString()).toBe(
- "ws://marimo.app/ws?file=test.py&search=test&other=last&session_id=1234",
+ "ws://marimo.app/ws?file=test.py&search=test&other=last&session_id=1234&message_format=host",
);
expect(url.searchParams.get("file")).toBe("test.py");
expect(url.searchParams.get("search")).toBe("test");
diff --git a/frontend/src/core/runtime/__tests__/runtime.test.ts b/frontend/src/core/runtime/__tests__/runtime.test.ts
index ad42a012c1..ad63b9e815 100644
--- a/frontend/src/core/runtime/__tests__/runtime.test.ts
+++ b/frontend/src/core/runtime/__tests__/runtime.test.ts
@@ -51,24 +51,6 @@ describe("RuntimeManager", () => {
});
});
- it.each(["getWsURL", "getSseURL"] as const)(
- "%s selects host framing on the session endpoint",
- (method) => {
- const runtime = new RuntimeManager({
- ...mockConfig,
- url: "https://example.com/nested?file=notebook.py",
- messageFormat: "host",
- });
- const url = runtime[method]("1234" as SessionId);
- expect(url.pathname).toBe(
- method === "getWsURL" ? "/nested/ws" : "/nested/sse",
- );
- expect(url.searchParams.get("message_format")).toBe("host");
- expect(url.searchParams.get("session_id")).toBe("1234");
- expect(url.searchParams.get("file")).toBe("notebook.py");
- },
- );
-
describe("getWsURL", () => {
it("should return WebSocket URL with session ID for https", () => {
const runtime = new RuntimeManager(mockConfig);
@@ -78,6 +60,7 @@ describe("RuntimeManager", () => {
expect(url.protocol).toBe("wss:");
expect(url.hostname).toBe("example.com");
expect(url.pathname).toBe("/ws");
+ expect(url.searchParams.get("message_format")).toBe("host");
expect(url.searchParams.has("types")).toBe(false);
expect(url.searchParams.get("session_id")).toBe(sessionId);
});
@@ -253,6 +236,7 @@ describe("RuntimeManager", () => {
);
const url = runtime.getSseURL("s_123" as SessionId);
+ expect(url.searchParams.get("message_format")).toBe("host");
expect(url.searchParams.get("access_token")).toBeNull();
expect(url.toString()).not.toContain("my-secret-token");
});
@@ -756,7 +740,7 @@ describe("RuntimeManager", () => {
const sessionId = "test" as SessionId;
expect(runtime.getWsURL(sessionId).toString()).toMatchInlineSnapshot(
- `"blob:https://example.com/12345678-1234-1234-1234-123456789abc?session_id=test"`,
+ `"blob:https://example.com/12345678-1234-1234-1234-123456789abc?session_id=test&message_format=host"`,
);
expect(Logger.warn).toHaveBeenCalledOnce();
});
diff --git a/frontend/src/core/runtime/runtime.ts b/frontend/src/core/runtime/runtime.ts
index 3d6833f501..5daf064ad9 100644
--- a/frontend/src/core/runtime/runtime.ts
+++ b/frontend/src/core/runtime/runtime.ts
@@ -155,11 +155,7 @@ export class RuntimeManager {
public getWsURL(sessionId: SessionId): URL {
const searchParams = this.getSessionSearchParams(sessionId);
const url = this.formatWsURL("/ws", searchParams);
- if (this.config.messageFormat === "host") {
- url.searchParams.set("message_format", "host");
- } else {
- url.searchParams.delete("message_format");
- }
+ url.searchParams.set("message_format", "host");
return url;
}
@@ -175,11 +171,7 @@ export class RuntimeManager {
searchParams: this.getSessionSearchParams(sessionId),
restrictToKnownQueryParams: false,
});
- if (this.config.messageFormat === "host") {
- url.searchParams.set("message_format", "host");
- } else {
- url.searchParams.delete("message_format");
- }
+ url.searchParams.set("message_format", "host");
// The page URL can still carry access_token (merged in from the
// current page's params, before auth cleanup strips it); never
// forward it — a token in the URL leaks into proxy/server logs.
diff --git a/frontend/src/core/runtime/types.ts b/frontend/src/core/runtime/types.ts
index e6ae39490d..8d8e6ddf44 100644
--- a/frontend/src/core/runtime/types.ts
+++ b/frontend/src/core/runtime/types.ts
@@ -1,8 +1,6 @@
/* Copyright 2026 Marimo. All rights reserved. */
export interface RuntimeConfig {
- /** Temporary stream framing selection during the host migration. */
- readonly messageFormat?: "host" | "session";
/**
* The URL of the runtime server.
*/
diff --git a/frontend/src/core/websocket/__tests__/useNotebookClient.hook.test.tsx b/frontend/src/core/websocket/__tests__/useNotebookClient.hook.test.tsx
index c78b81c7d0..316fcf02c9 100644
--- a/frontend/src/core/websocket/__tests__/useNotebookClient.hook.test.tsx
+++ b/frontend/src/core/websocket/__tests__/useNotebookClient.hook.test.tsx
@@ -15,11 +15,12 @@ import { notebookClientAtom } from "../state";
vi.mock("../transports/create", () => ({ createConnectionTransport: vi.fn() }));
-function makeTransport() {
+function makeTransport(url?: () => string) {
const events = new EventTarget();
const transport: IConnectionTransport = {
readyState: WebSocket.CLOSED,
reconnect: vi.fn(() => {
+ url?.();
transport.readyState = WebSocket.OPEN;
events.dispatchEvent(new Event("open"));
}),
@@ -52,16 +53,13 @@ function makeTransport() {
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>
@@ -121,25 +119,6 @@ describe("useNotebookClient", () => {
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(() => {
diff --git a/frontend/src/core/websocket/__tests__/useNotebookSession.hook.test.tsx b/frontend/src/core/websocket/__tests__/useNotebookSession.hook.test.tsx
index dba018eff6..bbacfe96a0 100644
--- a/frontend/src/core/websocket/__tests__/useNotebookSession.hook.test.tsx
+++ b/frontend/src/core/websocket/__tests__/useNotebookSession.hook.test.tsx
@@ -36,7 +36,6 @@ 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";
@@ -235,36 +234,29 @@ describe("useNotebookSession messages", () => {
}
it.each(["{broken", "null"])(
- "reports a malformed legacy frame and continues applying notifications: %s",
+ "closes a malformed stream and ignores subsequent 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: {
+ receive({ event: "marimo", data: { marimo: { op: "reconnected" } } });
+ act(() =>
+ getTransportHandlers().onMessage(new MessageEvent("message", { data })),
+ );
+ expect(store.get(connectionAtom)).toEqual({
+ state: ConnectionState.CLOSED,
+ code: "KERNEL_DISCONNECTED",
+ reason: "Failed to decode notebook message",
+ });
+ receive({
+ event: "marimo",
+ data: {
+ marimo: {
op: "completed-run",
run_id: "r1",
outcome: "succeeded",
error: null,
},
- });
- expect(store.get(initialRunCompletedAtom)).toBe(true);
- } finally {
- toast.mockRestore();
- }
+ },
+ });
+ expect(store.get(initialRunCompletedAtom)).toBe(false);
},
);
diff --git a/frontend/src/core/websocket/useNotebookClient.ts b/frontend/src/core/websocket/useNotebookClient.ts
index 08d4fffbe0..c242df7f91 100644
--- a/frontend/src/core/websocket/useNotebookClient.ts
+++ b/frontend/src/core/websocket/useNotebookClient.ts
@@ -11,7 +11,6 @@ import type {
import {
createNotebookClient,
type NotebookClient,
- type NotebookConnection,
} from "../host/notebook-client";
import { classifyCloseEvent } from "./connection-state";
import { notebookClientAtom } from "./state";
@@ -21,24 +20,20 @@ import {
} 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 { static: isStatic, transportType } = 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();
@@ -52,11 +47,9 @@ export function useNotebookClient(options: Options): NotebookClient {
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 }),
@@ -72,16 +65,13 @@ export function useNotebookClient(options: Options): NotebookClient {
}, [
controller,
store,
- sessionId,
isStatic,
transportType,
- messageFormat,
url,
headers,
waitUntilReady,
checkHealth,
onNotification,
- onMessageError,
]);
return controller.client;
diff --git a/frontend/src/core/websocket/useNotebookSession.tsx b/frontend/src/core/websocket/useNotebookSession.tsx
index d9c370fb63..41f56b9ec3 100644
--- a/frontend/src/core/websocket/useNotebookSession.tsx
+++ b/frontend/src/core/websocket/useNotebookSession.tsx
@@ -65,7 +65,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 { runtimeConfigAtom, useRuntimeManager } from "../runtime/config";
+import { useRuntimeManager } from "../runtime/config";
import { SECRETS_REGISTRY } from "../secrets/request-registry";
import { isStaticNotebook } from "../static/static-state";
import {
@@ -135,7 +135,6 @@ export function useNotebookSession(opts: {
const setStableSessionId = useSetAtom(stableSessionIdAtom);
const setCapabilities = useSetAtom(capabilitiesAtom);
const runtimeManager = useRuntimeManager();
- const { messageFormat = "session" } = useAtomValue(runtimeConfigAtom);
const transportType = useAtomValue(connectionTransportTypeAtom);
const setCacheInfo = useSetAtom(cacheInfoAtom);
const setKernelStartupError = useSetAtom(kernelStartupErrorAtom);
@@ -411,10 +410,8 @@ export function useNotebookSession(opts: {
});
};
const notebook = useNotebookClient({
- sessionId,
static: isStaticNotebook(),
transportType,
- messageFormat,
url: () =>
transportType === "sse"
? runtimeManager.getSseURL(sessionId).toString()
@@ -427,7 +424,6 @@ export function useNotebookSession(opts: {
}
},
checkHealth: () => runtimeManager.reconcileFromHealth(),
- onMessageError,
onNotification: (notification) => {
try {
handleNotification(notification);
diff --git a/frontend/src/mount.tsx b/frontend/src/mount.tsx
index 32835d4b34..213da3ea2a 100644
--- a/frontend/src/mount.tsx
+++ b/frontend/src/mount.tsx
@@ -274,8 +274,6 @@ const mountOptionsSchema = z.object({
.transform((val) => val as api.Notebook["NotebookV1"]),
]),
- messageFormat: z.enum(["host", "session"]).optional(),
-
/**
* Runtime configs
*/
@@ -286,7 +284,6 @@ const mountOptionsSchema = z.object({
// Lazy by default, but can be overridden by the runtime config
lazy: z.boolean().default(true),
authToken: z.string().nullish(),
- messageFormat: z.enum(["host", "session"]).optional(),
}),
)
.nullish()
@@ -367,7 +364,6 @@ function initStore(options: unknown) {
} else {
store.set(runtimeConfigAtom, {
...DEFAULT_RUNTIME_CONFIG,
- messageFormat: parsedOptions.data.messageFormat,
lazy: false,
serverToken: parsedOptions.data.serverToken,
});
diff --git a/marimo/_server/api/endpoints/assets.py b/marimo/_server/api/endpoints/assets.py
index 54a4f3131e..f3ede11e16 100644
--- a/marimo/_server/api/endpoints/assets.py
+++ b/marimo/_server/api/endpoints/assets.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import hashlib
import re
from pathlib import Path
-from typing import TYPE_CHECKING, Literal, TypedDict
+from typing import TYPE_CHECKING, TypedDict
from urllib.parse import urlencode
from starlette.authentication import has_required_scope, requires
@@ -50,7 +50,6 @@ from marimo._utils.paths import (
if TYPE_CHECKING:
from starlette.requests import Request
- from marimo._server.host.context import HostContext
LOGGER = _loggers.marimo_logger()
@@ -417,15 +416,6 @@ async def index(request: Request) -> Response:
except ValueError:
pass # Keep absolute if not under directory
- context: HostContext | None = getattr(
- request.app.state, "host_context", None
- )
- message_format: Literal["host", "session"] = (
- "host"
- if context is not None and context.bridge.app_sessions is None
- else "session"
- )
-
html = notebook_page_template(
html=html,
base_url=app_state.base_url,
@@ -438,7 +428,6 @@ async def index(request: Request) -> Response:
lsp_workspace=lsp_workspace,
mode=app_state.mode,
notebook_snapshot=notebook_snapshot,
- message_format=message_format,
runtime_config=[{"url": app_state.remote_url}]
if app_state.remote_url
else None,
diff --git a/marimo/_templates.py b/marimo/_templates.py
index 19e83ea135..bd15c83b32 100644
--- a/marimo/_templates.py
+++ b/marimo/_templates.py
@@ -107,7 +107,6 @@ def _get_mount_config(
session_snapshot: NotebookSessionV1 | None = None,
notebook_snapshot: NotebookV1 | None = None,
runtime_config: list[dict[str, Any]] | None = None,
- message_format: Literal["host", "session"] | None = None,
layout: LayoutConfig | None = None,
) -> str:
"""
@@ -146,12 +145,6 @@ def _get_mount_config(
"hostEnabled": mode == "edit",
}
)
- stream_format = (
- ',\n "messageFormat": ' + json_script(message_format)
- if message_format is not None
- else ""
- )
-
return """{{
"filename": {filename},
"cwd": {cwd},
@@ -166,13 +159,12 @@ def _get_mount_config(
"view": {view},
"notebook": {notebook},
"session": {session},
- "runtimeConfig": {runtime_config}{stream_format},
+ "runtimeConfig": {runtime_config},
"pairConfig": {pair_config}
}}
""".format(
**{k: json_script(v) for k, v in options.items()},
pair_config=pair_config,
- stream_format=stream_format,
).strip()
@@ -306,7 +298,6 @@ def notebook_page_template(
session_snapshot: NotebookSessionV1 | None = None,
notebook_snapshot: NotebookV1 | None = None,
runtime_config: list[dict[str, Any]] | None = None,
- message_format: Literal["host", "session"] | None = None,
asset_url: str | None = None,
html_head: str | None = None,
execute_opengraph_generators: bool = False,
@@ -350,7 +341,6 @@ def notebook_page_template(
config_overrides=config_overrides,
app_config=app_config,
runtime_config=runtime_config,
- message_format=message_format,
notebook_snapshot=notebook_snapshot,
session_snapshot=session_snapshot,
),
diff --git a/packages/client/src/__tests__/reducer.test.ts b/packages/client/src/__tests__/reducer.test.ts
index e2fe709876..3a4c47ddbf 100644
--- a/packages/client/src/__tests__/reducer.test.ts
+++ b/packages/client/src/__tests__/reducer.test.ts
@@ -93,7 +93,7 @@ describe("notebook reducer", () => {
const resetEvents = fixtureEvents("events-reset.sse");
const afterReset = reducer.reduce(live, resetEvents[0]);
- expect(afterReset).toEqual({ ...reducer.initial, notebookId: "n1" });
+ expect(afterReset).toEqual(reducer.initial);
expect(replay(reducer, resetEvents, live).phase).toBe("live");
});
@@ -137,7 +137,11 @@ describe("notebook reducer", () => {
id: "100",
data: { id: "n1", time },
});
- expect(removed).toMatchObject({ phase: "live", notebookId: "n1" });
+ expect(removed).toMatchObject({
+ phase: "live",
+ notebookId: "n1",
+ notebook: null,
+ });
expect(removed.resources).toBe(reducer.initial.resources);
});
diff --git a/packages/client/src/reducer.ts b/packages/client/src/reducer.ts
index bdcac0e6df..b6d6fc04ef 100644
--- a/packages/client/src/reducer.ts
+++ b/packages/client/src/reducer.ts
@@ -59,9 +59,11 @@ export interface ReducerState<States> {
/**
* The notebook the stream describes.
*
- * Retained across `reset`.
+ * Cleared on `reset`: session brokering may select a new notebook.
*/
readonly notebookId: Protocol.NotebookIdOutput | null;
+ /** Latest notebook metadata, cleared on reset or removal. */
+ readonly notebook: Protocol.NotebookOutput | null;
/** The state of each resource by name. */
readonly resources: States;
}
@@ -122,6 +124,7 @@ export function createReducer<States extends object>(
const initial: ReducerState<States> = {
phase: "snapshot",
notebookId: null,
+ notebook: null,
resources: initialResources,
};
@@ -139,9 +142,9 @@ export function createReducer<States extends object>(
}
function clear(state: ReducerState<States>): ReducerState<States> {
- return state.resources === initialResources
+ return state.resources === initialResources && state.notebook === null
? state
- : { ...state, resources: initialResources };
+ : { ...state, notebook: null, resources: initialResources };
}
function fanOut(
@@ -177,13 +180,16 @@ export function createReducer<States extends object>(
reduce(state, event) {
switch (event.event) {
case "reset":
- return { ...initial, notebookId: state.notebookId };
+ return initial;
case "ready":
// Handlers see the phase that ended, so a snapshot's ready differs
// from one that ends a replay.
return { ...fanOut(state, event), phase: "live" };
case "notebook":
- return identify(state, event.data.notebook.id);
+ return {
+ ...identify(state, event.data.notebook.id),
+ notebook: event.data.notebook,
+ };
case "host":
case "project":
case "project.removed":
diff --git a/tests/_server/api/endpoints/test_assets.py b/tests/_server/api/endpoints/test_assets.py
index 7b8fa42adc..ee46d43cdb 100644
--- a/tests/_server/api/endpoints/test_assets.py
+++ b/tests/_server/api/endpoints/test_assets.py
@@ -984,7 +984,7 @@ def test_serve_static_allowed_files(client: TestClient) -> None:
@pytest.mark.parametrize("remote_url", [None, "https://remote.example"])
@pytest.mark.parametrize("cataloged", [True, False])
-def test_index_selects_stream_format_without_provisioning_a_notebook(
+def test_index_does_not_provision_a_notebook(
client: TestClient, remote_url: str | None, cataloged: bool
) -> None:
state = AppState.from_app(cast(Any, client.app))
@@ -1001,7 +1001,6 @@ def test_index_selects_stream_format_without_provisioning_a_notebook(
response = client.get("/", headers=token_header())
assert response.status_code == 200
config = parse_mount_config(response.text)
- assert config["messageFormat"] == "host"
assert "notebookId" not in config
assert bridge.host.notebooks == initial_notebooks
assert not state.session_manager.sessions