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
Route session connections through the host stream (#11365)
Trevor Manzc84e2f35f925
diff --git a/frontend/src/__tests__/mount.test.ts b/frontend/src/__tests__/mount.test.tsindex a708d9fc9e..328210f8b3 100644--- a/frontend/src/__tests__/mount.test.ts+++ b/frontend/src/__tests__/mount.test.ts@@ -102,23 +102,18 @@ 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", () => {+ it("uses the remote runtime's framing instead of the page's", () => {mount({...baseOptions,- notebookId: "nb_local",+ messageFormat: "host",runtimeConfig: [- { url: "https://remote.example", notebookId: "nb_remote" },+ { url: "https://remote.example", messageFormat: "session" },],},mockElement,);- expect(store.get(runtimeConfigAtom).notebookId).toBe("nb_remote");+ expect(store.get(runtimeConfigAtom).messageFormat).toBe("session");});it("should set connection to CONNECTING when runtimeConfig has lazy=false", () => {diff --git a/frontend/src/core/runtime/__tests__/runtime.test.ts b/frontend/src/core/runtime/__tests__/runtime.test.tsindex 0ca285380c..ad42a012c1 100644--- a/frontend/src/core/runtime/__tests__/runtime.test.ts+++ b/frontend/src/core/runtime/__tests__/runtime.test.ts@@ -2,11 +2,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { Mocks } from "@/__mocks__/common";-import {- generateSessionId,- isSessionId,- type SessionId,-} from "@/core/kernel/session";+import type { SessionId } from "@/core/kernel/session";import { Logger } from "@/utils/Logger";import { RuntimeManager } from "../runtime";import type { RuntimeConfig } from "../types";@@ -55,39 +51,25 @@ 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: "notebook,document,cell,attachment,marimo",- session_id: sessionId,- access_token: "test-token",- },- });- } finally {- window.history.replaceState({}, "", original);- }- });+ 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);const sessionId = "1234" as SessionId;@@ -257,21 +239,6 @@ describe("RuntimeManager", () => {});describe("getSseURL", () => {- 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 the// Authorization header; a token in the URL would leak into@@ -781,7 +748,7 @@ describe("RuntimeManager", () => {);});- it("should throw when creating WebSocket URLs from blob URLs", () => {+ it("warns when creating WebSocket URLs from blob URLs", () => {const runtime = new RuntimeManager({url: "blob:https://example.com/12345678-1234-1234-1234-123456789abc",lazy: true,diff --git a/frontend/src/core/runtime/runtime.ts b/frontend/src/core/runtime/runtime.tsindex 05713eb86b..3d6833f501 100644--- a/frontend/src/core/runtime/runtime.ts+++ b/frontend/src/core/runtime/runtime.ts@@ -3,7 +3,6 @@import { Deferred } from "@/utils/Deferred";import { Logger } from "@/utils/Logger";import { KnownQueryParams } from "../constants";-import { NOTEBOOK_EVENT_TYPES } from "../host/events";import { isIslands } from "../islands/utils";import { getSessionId, type SessionId } from "../kernel/session";import { isStaticNotebook } from "../static/static-state";@@ -155,15 +154,11 @@ export class RuntimeManager {*/public getWsURL(sessionId: SessionId): URL {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", NOTEBOOK_EVENT_TYPES.join(","));+ const url = this.formatWsURL("/ws", searchParams);+ if (this.config.messageFormat === "host") {+ url.searchParams.set("message_format", "host");+ } else {+ url.searchParams.delete("message_format");}return url;}@@ -175,13 +170,16 @@ export class RuntimeManager {* (see `headers()`) instead of the URL.*/public getSseURL(sessionId: SessionId): URL {- // TODO: Migrate editor SSE to the host event stream. Until then, host- // state such as attachments is unavailable on this legacy connection.const url = this.formatHttpURL({path: "/sse",searchParams: this.getSessionSearchParams(sessionId),restrictToKnownQueryParams: false,});+ if (this.config.messageFormat === "host") {+ url.searchParams.set("message_format", "host");+ } else {+ url.searchParams.delete("message_format");+ }// 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.tsindex 178df51d90..e6ae39490d 100644--- a/frontend/src/core/runtime/types.ts+++ b/frontend/src/core/runtime/types.ts@@ -1,8 +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;+ /** 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/transports/__tests__/sse.test.ts b/frontend/src/core/websocket/transports/__tests__/sse.test.tsindex c4392ff462..afb890fb0c 100644--- a/frontend/src/core/websocket/transports/__tests__/sse.test.ts+++ b/frontend/src/core/websocket/transports/__tests__/sse.test.ts@@ -90,6 +90,23 @@ describe("SseTransport", () => {expect(messages[1].data).toBe("line1\nline2");});+ it("preserves host event names and cursors without carrying IDs into snapshots", async () => {+ const { stream, push } = createControllableStream();+ fetchMock.mockResolvedValueOnce(sseResponse(stream));+ transport.reconnect();+ await vi.waitFor(() => expect(opens).toHaveLength(1));++ push("id: cursor-1\nevent: rea");+ push("dy\ndata: {}\n\n: keep-alive\n\nevent: reset\ndata: {}\n\n");+ push('event: marimo\ndata: {"marimo":\ndata: {"op":"reconnected"}}\n\n');+ await vi.waitFor(() => expect(messages).toHaveLength(3));+ expect(messages.map((message) => JSON.parse(message.data))).toEqual([+ { event: "ready", id: "cursor-1", data: {} },+ { event: "reset", data: {} },+ { event: "marimo", data: { marimo: { op: "reconnected" } } },+ ]);+ });+it("ignores keep-alive comments", async () => {const { stream, push } = createControllableStream();fetchMock.mockResolvedValueOnce(sseResponse(stream));diff --git a/frontend/src/core/websocket/transports/sse.ts b/frontend/src/core/websocket/transports/sse.tsindex f1aaff3056..aba9556371 100644--- a/frontend/src/core/websocket/transports/sse.ts+++ b/frontend/src/core/websocket/transports/sse.ts@@ -218,16 +218,20 @@ export class SseTransport implements IConnectionTransport {const decoder = new TextDecoder();let buffer = "";let eventName: string | null = null;+ let eventId: string | null = null;let dataLines: string[] = [];const dispatch = (): ServerClose | null => {if (dataLines.length === 0) {eventName = null;+ eventId = null;return null;}const data = dataLines.join("\n");const name = eventName;+ const id = eventId;eventName = null;+ eventId = null;dataLines = [];if (name === "close") {return parseServerClose(data);@@ -236,9 +240,15 @@ export class SseTransport implements IConnectionTransport {// (rather than on open, so a server that accepts and immediately// closes cannot retry forever).this.retryCount = 0;+ // Normalize SSE fields into the same envelope as host WebSockets.+ // Leave the payload text intact for the client's JSON decoder.+ const envelope =+ name === null+ ? data+ : `{"event":${JSON.stringify(name)},"data":${data}${id === null ? "" : `,"id":${JSON.stringify(id)}`}}`;this.subscriptions.notify("message",- new MessageEvent("message", { data }),+ new MessageEvent("message", { data: envelope }),);return null;};@@ -284,8 +294,10 @@ export class SseTransport implements IConnectionTransport {dataLines.push(fieldValue);} else if (field === "event") {eventName = fieldValue;+ } else if (field === "id") {+ eventId = fieldValue;}- // `id` and `retry` fields are unused.+ // The host client owns the cursor; `retry` does not override our policy.}if (cursor > 0) {buffer = buffer.slice(cursor);diff --git a/frontend/src/core/websocket/useNotebookSession.tsx b/frontend/src/core/websocket/useNotebookSession.tsxindex 040d7dce40..d9c370fb63 100644--- a/frontend/src/core/websocket/useNotebookSession.tsx+++ b/frontend/src/core/websocket/useNotebookSession.tsx@@ -135,7 +135,7 @@ export function useNotebookSession(opts: {const setStableSessionId = useSetAtom(stableSessionIdAtom);const setCapabilities = useSetAtom(capabilitiesAtom);const runtimeManager = useRuntimeManager();- const { notebookId } = useAtomValue(runtimeConfigAtom);+ const { messageFormat = "session" } = useAtomValue(runtimeConfigAtom);const transportType = useAtomValue(connectionTransportTypeAtom);const setCacheInfo = useSetAtom(cacheInfoAtom);const setKernelStartupError = useSetAtom(kernelStartupErrorAtom);@@ -414,8 +414,7 @@ export function useNotebookSession(opts: {sessionId,static: isStaticNotebook(),transportType,- messageFormat:- notebookId && transportType === "websocket" ? "host" : "session",+ messageFormat,url: () =>transportType === "sse"? runtimeManager.getSseURL(sessionId).toString()diff --git a/frontend/src/mount.tsx b/frontend/src/mount.tsxindex f95561747d..32835d4b34 100644--- a/frontend/src/mount.tsx+++ b/frontend/src/mount.tsx@@ -274,7 +274,7 @@ const mountOptionsSchema = z.object({.transform((val) => val as api.Notebook["NotebookV1"]),]),- notebookId: z.string().optional(),+ messageFormat: z.enum(["host", "session"]).optional(),/*** Runtime configs@@ -286,7 +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(),+ messageFormat: z.enum(["host", "session"]).optional(),}),).nullish()@@ -367,7 +367,7 @@ function initStore(options: unknown) {} else {store.set(runtimeConfigAtom, {...DEFAULT_RUNTIME_CONFIG,- notebookId: parsedOptions.data.notebookId,+ messageFormat: parsedOptions.data.messageFormat,lazy: false,serverToken: parsedOptions.data.serverToken,});diff --git a/marimo/_runtime/params.py b/marimo/_runtime/params.pyindex b5df7bb331..c0741c003f 100644--- a/marimo/_runtime/params.py+++ b/marimo/_runtime/params.py@@ -33,7 +33,14 @@ if TYPE_CHECKING:class QueryParams(State[SerializedQueryParams]):"""Query parameters for a marimo app."""- IGNORED_KEYS = {"access_token", "refresh_token", "session_id"}+ IGNORED_KEYS = {+ "access_token",+ "refresh_token",+ "session_id",+ "cursor",+ "message_format",+ "types",+ }def __init__(self,diff --git a/marimo/_server/api/endpoints/assets.py b/marimo/_server/api/endpoints/assets.pyindex 232985d495..54a4f3131e 100644--- a/marimo/_server/api/endpoints/assets.py+++ b/marimo/_server/api/endpoints/assets.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport hashlibimport refrom pathlib import Path-from typing import TYPE_CHECKING, TypedDict+from typing import TYPE_CHECKING, Literal, TypedDictfrom urllib.parse import urlencodefrom starlette.authentication import has_required_scope, requires@@ -417,21 +417,14 @@ async def index(request: Request) -> Response:except ValueError:pass # Keep absolute if not under directory- notebook_id = Nonecontext: HostContext | None = getattr(request.app.state, "host_context", None)- if (- context is not None- and context.bridge.app_sessions is 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+ 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,@@ -445,7 +438,7 @@ async def index(request: Request) -> Response:lsp_workspace=lsp_workspace,mode=app_state.mode,notebook_snapshot=notebook_snapshot,- notebook_id=notebook_id,+ message_format=message_format,runtime_config=[{"url": app_state.remote_url}]if app_state.remote_urlelse None,diff --git a/marimo/_server/api/endpoints/home.py b/marimo/_server/api/endpoints/home.pyindex d055634202..2437c22bc4 100644--- a/marimo/_server/api/endpoints/home.py+++ b/marimo/_server/api/endpoints/home.py@@ -14,6 +14,7 @@ from marimo import _loggersfrom marimo._server.api.deps import AppStatefrom marimo._server.api.utils import parse_requestfrom marimo._server.files.directory_scanner import DirectoryScanner+from marimo._server.host.lifespan import ensure_hostfrom marimo._server.models.home import (MarimoFile,OpenTutorialRequest,@@ -297,6 +298,8 @@ async def tutorial(app_state.session_manager.workspace.register_allowed_path(path.absolute_name)+ context = await ensure_host(request.app)+ context.bridge.index.register_open_notebook(path.absolute_name)return MarimoFile(name=os.path.basename(path.absolute_name),diff --git a/marimo/_server/api/endpoints/ws/notification_filter.py b/marimo/_server/api/endpoints/ws/notification_filter.pynew file mode 100644index 0000000000..23944e79e0--- /dev/null+++ b/marimo/_server/api/endpoints/ws/notification_filter.py@@ -0,0 +1,46 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++from marimo import _loggers+from marimo._messaging.notification import (+ CompletionResultNotification,+ FocusCellNotification,+)++LOGGER = _loggers.marimo_logger()++# Operations that are only sent in kiosk mode+KIOSK_ONLY_OPERATIONS = {+ FocusCellNotification.name,+}++# Operations that are excluded from kiosk mode+KIOSK_EXCLUDED_OPERATIONS = {+ CompletionResultNotification.name,+}+++def should_filter_operation(op: str, *, is_kiosk: bool) -> bool:+ """Determine if operation should be filtered based on kiosk mode.++ Args:+ op: Operation name to check+ is_kiosk: Whether the connection is in kiosk (viewer) mode++ Returns:+ True if the operation should be filtered (not sent), False+ otherwise.+ """+ if op in KIOSK_ONLY_OPERATIONS and not is_kiosk:+ LOGGER.debug(+ "Ignoring operation %s, not in kiosk mode",+ op,+ )+ return True+ if op in KIOSK_EXCLUDED_OPERATIONS and is_kiosk:+ LOGGER.debug(+ "Ignoring operation %s, in kiosk mode",+ op,+ )+ return True+ return Falsediff --git a/marimo/_server/api/endpoints/ws/session_handler.py b/marimo/_server/api/endpoints/ws/session_handler.pyindex 7796180074..d4bf6e0488 100644--- a/marimo/_server/api/endpoints/ws/session_handler.py+++ b/marimo/_server/api/endpoints/ws/session_handler.py@@ -14,23 +14,16 @@ from marimo._config.settings import GLOBAL_SETTINGSfrom marimo._messaging.notification import (AlertNotification,BannerNotification,- EnvironmentOperationNotification,- EnvironmentStateNotification,NotificationMessage,ReconnectedNotification,- StartupProgressNotification,)from marimo._messaging.serde import (- deserialize_kernel_notification_name,serialize_kernel_message,)from marimo._server.api.endpoints.ws.ws_kernel_ready import (build_kernel_ready,is_rtc_available,)-from marimo._server.api.endpoints.ws.ws_message_loop import (- prepare_wire_message,-)from marimo._server.api.endpoints.ws.ws_session_connector import (SessionConnector,is_viewer_connection,@@ -42,7 +35,7 @@ from marimo._types.ids import ConsumerIdfrom marimo._utils.asyncio_utils import cancel_and_waitif TYPE_CHECKING:- from collections.abc import AsyncGenerator, AsyncIterator+ from collections.abc import AsyncIteratorfrom starlette.requests import HTTPConnection@@ -70,13 +63,10 @@ class SessionHandler(SessionConsumer, abc.ABC):Owns the transport-agnostic session lifecycle: connecting (new, resume,reconnect, kiosk), the kernel-ready handshake, message replay, andTTL-based session close on disconnect. Subclasses implement the small- transport surface (`_request_close`, `_is_transport_connected`,- `_cancel_message_loop`) and their own message loop that drains- `message_queue`.+ transport surface (`_request_close`, `_is_transport_connected`) and+ deliver notifications through the host stream."""- _replay_notebook_on_reconnect = False-def __init__(self,*,@@ -92,13 +82,6 @@ class SessionHandler(SessionConsumer, abc.ABC):self.status = ConnectionState.CONNECTINGself._session: Session | None = Noneself.cancel_close_handle: asyncio.TimerHandle | None = None- # Messages from the kernel are put in this queue- # to be sent to the frontend- self.message_queue: asyncio.Queue[KernelMessage] = asyncio.Queue()- # Startup precedes session attachment and its viewer filtering.- self._startup_queue: asyncio.Queue[KernelMessage | None] | None = (- asyncio.Queue()- )self._consumer_id = ConsumerId(params.session_id)@property@@ -118,10 +101,6 @@ class SessionHandler(SessionConsumer, abc.ABC):def _is_transport_connected(self) -> bool:"""Whether the transport can still deliver messages."""- @abc.abstractmethod- def _cancel_message_loop(self) -> None:- """Stop the message loop that drains `message_queue`."""-# Shared session lifecycle@asynccontextmanager@@ -170,32 +149,13 @@ class SessionHandler(SessionConsumer, abc.ABC):await cancel_and_wait(disconnected)await cancel_and_wait(startup)+ async def _prepare_session(self, session: Session) -> None:+ """Prepare a selected session before delivering its initial state."""+@abc.abstractmethodasync def _wait_for_disconnect(self) -> None:"""Notice a closed transport even while a session is starting."""- async def _startup_messages(- self, startup: asyncio.Task[tuple[Session, ConnectionType]]- ) -> AsyncGenerator[str, None]:- """Send progress before session messages, including before failure."""- queue = self._startup_queue- assert queue is not None-- def finished(- _task: asyncio.Task[tuple[Session, ConnectionType]],- ) -> None:- queue.put_nowait(None)-- startup.add_done_callback(finished)- try:- while (data := await queue.get()) is not None:- text = prepare_wire_message(data, is_kiosk=self.params.kiosk)- if text is not None:- yield text- finally:- startup.remove_done_callback(finished)- self._startup_queue = None-def _is_viewer(self, session: Session, connection_type: ConnectionType) -> bool:@@ -205,24 +165,9 @@ class SessionHandler(SessionConsumer, abc.ABC):is_main_consumer=session.room.main_consumer is self,)+ @abc.abstractmethoddef notify(self, notification: KernelMessage) -> None:- name = deserialize_kernel_notification_name(notification)- if (- self._startup_queue is not None- and self.status == ConnectionState.CONNECTING- and (- name == StartupProgressNotification.name- or self._session is None- and name- in (- EnvironmentOperationNotification.name,- EnvironmentStateNotification.name,- )- )- ):- self._startup_queue.put_nowait(notification)- else:- self.message_queue.put_nowait(notification)+ """Deliver a private session notification through the host stream."""def _serialize_and_notify(self, notification: NotificationMessage) -> None:self.notify(serialize_kernel_message(notification))@@ -313,9 +258,7 @@ class SessionHandler(SessionConsumer, abc.ABC):description="You have reconnected to an existing session.",))- self._replay_previous_session(- session, include_notebook=self._replay_notebook_on_reconnect- )+ self._replay_previous_session(session)returnself._write_kernel_ready_from_session_view(session, self.params.kiosk)@@ -361,13 +304,9 @@ class SessionHandler(SessionConsumer, abc.ABC):# Replay all operationsself._replay_previous_session(session)- def _replay_previous_session(- self, session: Session, *, include_notebook: bool = True- ) -> None:+ def _replay_previous_session(self, session: Session) -> None:"""Replay retained state to this client."""- notifications = session.session_view.snapshot_notifications(- include_notebook=include_notebook- )+ notifications = session.session_view.snapshot_notifications()LOGGER.debug("Replaying %s notifications", len(notifications))for notif in notifications:LOGGER.debug("Replaying notification %s", notif)@@ -439,8 +378,6 @@ class SessionHandler(SessionConsumer, abc.ABC):WebSocketCodes.NORMAL_CLOSE, WebSocketCloseReason.SHUTDOWN)- self._cancel_message_loop()-def connection_state(self) -> ConnectionState:return self.statusdiff --git a/marimo/_server/api/endpoints/ws/sse_handler.py b/marimo/_server/api/endpoints/ws/sse_handler.pydeleted file mode 100644index 3aa2c8c3a0..0000000000--- a/marimo/_server/api/endpoints/ws/sse_handler.py+++ /dev/null@@ -1,231 +0,0 @@-# Copyright 2026 Marimo. All rights reserved.-"""Server-sent events (SSE) transport for marimo sessions.--An experimental alternative to the `/ws` WebSocket for deployments behind-proxies or services that do not support WebSockets (enabled with-`server.transport = "sse"`). Kernel messages only flow server to client, so-an SSE stream can fully replace the WebSocket: control requests already-arrive over HTTP POST endpoints keyed by the `Marimo-Session-Id` header.--Wire protocol:--- Kernel messages are sent as unnamed SSE events whose `data:` payload is- identical to the WebSocket text frame (`{"op": ..., "data": ...}`).-- A `close` event carrying `{"code": ..., "reason": ...}` mirrors the- WebSocket close frame; the stream ends right after it. A stream that ends- without a `close` event is a transient disconnect, and clients should- reconnect.-- A `: keep-alive` comment is emitted periodically so intermediaries do not- time out the idle connection.-"""--from __future__ import annotations--import asyncio-import enum-from contextlib import aclosing-from typing import TYPE_CHECKING, Union, cast--from starlette.websockets import WebSocketDisconnect--from marimo import _loggers-from marimo._messaging.notification import KernelStartupErrorNotification-from marimo._server.api.endpoints.ws.session_handler import SessionHandler-from marimo._server.api.endpoints.ws.ws_formatter import (- serialize_notification_for_wire,-)-from marimo._server.api.endpoints.ws.ws_message_loop import (- prepare_wire_message,-)-from marimo._server.codes import WebSocketCloseReason, WebSocketCodes-from marimo._server.sse import (- HEARTBEAT_EVENT,- format_close_event,- format_sse_event,- wait_for_http_disconnect,-)-from marimo._session.managers.ipc import KernelStartupError--if TYPE_CHECKING:- from collections.abc import AsyncGenerator-- from starlette.requests import Request-- from marimo._messaging.types import KernelMessage- from marimo._server.api.endpoints.ws.ws_connection_validator import (- ConnectionParams,- )- from marimo._server.rtc.doc import LoroDocManager- from marimo._server.session_manager import SessionManager- from marimo._session.model import SessionMode--LOGGER = _loggers.marimo_logger()---class _Signal(enum.Enum):- """Control markers interleaved with kernel messages in the queue.-- Enqueuing CLOSE behind pending kernel messages means those messages- are flushed to the client before the close event is sent.- """-- CLOSE = "close"- DISCONNECT = "disconnect"- HEARTBEAT = "heartbeat"---_QueueItem = Union["KernelMessage", _Signal]---class SSESessionHandler(SessionHandler):- """SSE stream that sessions use to send messages to frontends.-- The SSE analogue of `WebSocketHandler`: connects to a session through- the shared `SessionConnector`, then streams the message queue as- server-sent events. The session connection is established lazily on- the first iteration of `stream()`, so a response that is never- consumed never attaches a consumer.- """-- def __init__(- self,- *,- request: Request,- manager: SessionManager,- params: ConnectionParams,- mode: SessionMode,- doc_manager: LoroDocManager,- heartbeat_seconds: float = 20.0,- ):- super().__init__(- manager=manager,- params=params,- mode=mode,- doc_manager=doc_manager,- )- self.request = request- self.heartbeat_seconds = heartbeat_seconds- self._close_code: int | None = None- self._close_reason: str | None = None- self._close_requested = False- self._stream_finished = False- # One queue carries both kernel messages (via the base class's- # `notify`) and control signals; the cast reconciles the base- # class's narrower type with the interleaved signals.- self._queue: asyncio.Queue[_QueueItem] = asyncio.Queue()- self.message_queue = cast("asyncio.Queue[KernelMessage]", self._queue)-- async def stream(self) -> AsyncGenerator[str, None]:- """Connect to the session and stream kernel messages as SSE.-- Connection rejections and kernel startup failures are delivered- in-band as a `close` event (after a kernel-startup-error message- when applicable), so the frontend handles every failure through- the same close-reason path as WebSocket close frames.-- Ends with a `close` event when the server closes the connection- (shutdown, takeover); ends without one on client disconnect.- """- try:- async with self._connection_lifetime(self.request) as startup:- try:- async with aclosing(- self._startup_messages(startup)- ) as messages:- async for progress in messages:- yield format_sse_event(progress)- session, connection_type = await startup- except asyncio.CancelledError:- return- except KernelStartupError as e:- LOGGER.error("Kernel startup failed: %s", e)- yield format_sse_event(- serialize_notification_for_wire(- KernelStartupErrorNotification(error=str(e))- )- )- yield format_close_event(- WebSocketCodes.UNEXPECTED_ERROR,- WebSocketCloseReason.KERNEL_STARTUP_ERROR,- )- return- except WebSocketDisconnect as e:- # SessionConnector signals connection rejections (e.g. kiosk- # not allowed) with WebSocketDisconnect regardless of- # transport.- yield format_close_event(e.code, e.reason or "")- return-- LOGGER.debug(- "Connected to session %s with type %s",- session.initialization_id,- connection_type,- )-- disconnect_task = asyncio.create_task(- self._signal_on_disconnect()- )- heartbeat_task = asyncio.create_task(self._heartbeat_loop())- self._check_status_update()- try:- while True:- item = await self._queue.get()- if item is _Signal.DISCONNECT:- return- if item is _Signal.CLOSE:- if self._close_code is not None:- yield format_close_event(- self._close_code, self._close_reason or ""- )- return- if item is _Signal.HEARTBEAT:- yield HEARTBEAT_EVENT- continue- text = prepare_wire_message(- item,- is_kiosk=self._is_viewer(session, connection_type),- )- if text is not None:- yield format_sse_event(text)- finally:- # Also runs when the client disconnects and StreamingResponse- # cancels the generator; don't await anything cancellable here.- disconnect_task.cancel()- heartbeat_task.cancel()- finally:- self._stream_finished = True-- async def _wait_for_disconnect(self) -> None:- await wait_for_http_disconnect(self.request)-- async def _signal_on_disconnect(self) -> None:- """Signal the stream loop when the client disconnects.-- This is a prompt-shutdown path, not the only cleanup path: when- the ASGI server (or Starlette itself, on ASGI spec < 2.4) reacts- to the disconnect first, the generator is cancelled and its- `finally` performs the same teardown.- """- await self._wait_for_disconnect()- self._queue.put_nowait(_Signal.DISCONNECT)-- async def _heartbeat_loop(self) -> None:- """Enqueue a keep-alive comment periodically."""- while True:- await asyncio.sleep(self.heartbeat_seconds)- self._queue.put_nowait(_Signal.HEARTBEAT)-- # Transport surface-- def _request_close(self, code: int, reason: str) -> None:- self._close_code = code- self._close_reason = reason- self._close_requested = True- self._queue.put_nowait(_Signal.CLOSE)-- def _is_transport_connected(self) -> bool:- return not self._stream_finished-- def _cancel_message_loop(self) -> None:- self._close_requested = True- self._queue.put_nowait(_Signal.CLOSE)diff --git a/marimo/_server/api/endpoints/ws/ws_formatter.py b/marimo/_server/api/endpoints/ws/ws_formatter.pydeleted file mode 100644index 2e72b707db..0000000000--- a/marimo/_server/api/endpoints/ws/ws_formatter.py+++ /dev/null@@ -1,49 +0,0 @@-# Copyright 2026 Marimo. All rights reserved.-"""Wire-format utilities for kernel messages sent to the frontend.--Wraps serialized notification data with operation metadata. The wire-format is shared by the WebSocket and SSE transports.-"""--from __future__ import annotations--from typing import TYPE_CHECKING--from marimo._messaging.serde import serialize_kernel_message--if TYPE_CHECKING:- from marimo._messaging.notification import NotificationMessage---def format_wire_message(op: str, data: bytes) -> str:- """Format a serialized message for transport to the frontend.-- Wraps serialized notification data with operation metadata.-- Args:- op: The operation name (e.g., "cell-op", "kernel-ready")- data: The serialized notification data as bytes-- Returns:- JSON string in wire format: {"op": "...", "data": ...}- """- return f'{{"op": "{op}", "data": {data.decode("utf-8")}}}'---def serialize_notification_for_wire(- notification: NotificationMessage,-) -> str:- """Serialize and format a notification for transport to the frontend.-- Combines serialization and wire formatting into a single operation.- Useful when you have a notification object and need the final wire format.-- Args:- notification: The notification to serialize and format-- Returns:- JSON string in wire format: {"op": "...", "data": ...}- """- serialized = serialize_kernel_message(notification)- op = notification.name- return format_wire_message(op, serialized)diff --git a/marimo/_server/api/endpoints/ws/ws_message_loop.py b/marimo/_server/api/endpoints/ws/ws_message_loop.pydeleted file mode 100644index cf27998d4a..0000000000--- a/marimo/_server/api/endpoints/ws/ws_message_loop.py+++ /dev/null@@ -1,151 +0,0 @@-# Copyright 2026 Marimo. All rights reserved.-from __future__ import annotations--import asyncio-from typing import TYPE_CHECKING--from starlette.websockets import WebSocketDisconnect, WebSocketState--from marimo import _loggers-from marimo._messaging.notification import (- CompletionResultNotification,- FocusCellNotification,-)-from marimo._messaging.serde import deserialize_kernel_notification_name-from marimo._messaging.types import KernelMessage-from marimo._server.api.endpoints.ws.ws_formatter import format_wire_message--if TYPE_CHECKING:- from collections.abc import Callable-- from starlette.websockets import WebSocket--LOGGER = _loggers.marimo_logger()--# Operations that are only sent in kiosk mode-KIOSK_ONLY_OPERATIONS = {- FocusCellNotification.name,-}--# Operations that are excluded from kiosk mode-KIOSK_EXCLUDED_OPERATIONS = {- CompletionResultNotification.name,-}---def should_filter_operation(op: str, *, is_kiosk: bool) -> bool:- """Determine if operation should be filtered based on kiosk mode.-- Args:- op: Operation name to check- is_kiosk: Whether the connection is in kiosk (viewer) mode-- Returns:- True if the operation should be filtered (not sent), False- otherwise.- """- if op in KIOSK_ONLY_OPERATIONS and not is_kiosk:- LOGGER.debug(- "Ignoring operation %s, not in kiosk mode",- op,- )- return True- if op in KIOSK_EXCLUDED_OPERATIONS and is_kiosk:- LOGGER.debug(- "Ignoring operation %s, in kiosk mode",- op,- )- return True- return False---def prepare_wire_message(data: KernelMessage, *, is_kiosk: bool) -> str | None:- """Filter and serialize a kernel message for the frontend.-- Shared by the WebSocket and SSE transports so both apply identical- kiosk filtering and produce identical wire payloads.-- Returns:- The wire-format text, or None if the message is filtered out or- fails to serialize.- """- op: str = deserialize_kernel_notification_name(data)-- if should_filter_operation(op, is_kiosk=is_kiosk):- return None-- try:- return format_wire_message(op, data)- except Exception as e:- LOGGER.error("Failed to deserialize message: %s", e)- LOGGER.error("Message: %s", data)- return None---class WebSocketMessageLoop:- """Handles the async message send/receive loops for WebSocket."""-- def __init__(- self,- websocket: WebSocket,- message_queue: asyncio.Queue[KernelMessage],- is_kiosk: Callable[[], bool],- on_check_status_update: Callable[[], None],- ):- self.websocket = websocket- self.message_queue = message_queue- self.is_kiosk = is_kiosk- self.on_check_status_update = on_check_status_update-- async def start(self) -> None:- """Start the message loops.-- Runs two concurrent tasks:- - listen_for_messages: Sends messages from kernel to frontend- - listen_for_disconnect: Detects when WebSocket disconnects- """- tasks = (- asyncio.create_task(self._listen_for_messages()),- asyncio.create_task(self._listen_for_disconnect()),- )- try:- done, _ = await asyncio.wait(- tasks, return_when=asyncio.FIRST_COMPLETED- )- for task in done:- task.result()- except WebSocketDisconnect:- pass- finally:- for task in tasks:- task.cancel()- await asyncio.gather(*tasks, return_exceptions=True)-- async def _listen_for_messages(self) -> None:- """Listen for messages from kernel and send to frontend."""- while True:- data = await self.message_queue.get()- text = prepare_wire_message(data, is_kiosk=self.is_kiosk())- if text is None:- continue-- # Send to WebSocket- try:- await self.websocket.send_text(text)- except RuntimeError:- # Starlette can raise a runtime error if a message is sent- # when the socket is closed. In case the disconnection- # error hasn't made its way to listen_for_disconnect, do- # the cleanup here.- if (- self.websocket.application_state- == WebSocketState.DISCONNECTED- ):- return- raise-- async def _listen_for_disconnect(self) -> None:- """Listen for WebSocket disconnect."""- self.on_check_status_update()- while True:- await self.websocket.receive_text()diff --git a/marimo/_server/api/endpoints/ws/ws_session_connector.py b/marimo/_server/api/endpoints/ws/ws_session_connector.pyindex aca0db6b6f..62bbba174b 100644--- a/marimo/_server/api/endpoints/ws/ws_session_connector.py+++ b/marimo/_server/api/endpoints/ws/ws_session_connector.py@@ -86,7 +86,7 @@ class SessionConnector:async def _connect(self) -> tuple[Session, ConnectionType]:# 1. Kiosk modeif self.params.kiosk:- return self._connect_kiosk()+ return await self._connect_kiosk()# A completed launch may still be waiting for its first connection.if self.manager.is_session_starting(@@ -97,6 +97,7 @@ class SessionConnector:# 2. Reconnect to existing session with same IDexisting_by_id = self.manager.get_session(self.params.session_id)if existing_by_id is not None:+ await self.handler._prepare_session(existing_by_id)return self._reconnect_session(existing_by_id)# 3. Connect to existing session@@ -112,6 +113,7 @@ class SessionConnector:and session_in_edit_modeand self.params.rtc_enabled):+ await self.handler._prepare_session(existing_by_file)return self._connect_rtc_session(existing_by_file)# 3b. Viewer only mode: a second connection request is auto routed as reader only@@ -120,19 +122,20 @@ class SessionConnector:and session_in_edit_modeand not initial_capabilities(existing_by_file, self.params).edit):- return self._connect_kiosk()+ return await self._connect_kiosk()# 4. Resume previous sessionresumable = self.manager.maybe_resume_session(self.params.session_id, self.params.file_key)if resumable is not None:+ await self.handler._prepare_session(resumable)return self._resume_session(resumable)# 5. Create new sessionreturn await self._create_new_session()- def _connect_kiosk(self) -> tuple[Session, ConnectionType]:+ async def _connect_kiosk(self) -> tuple[Session, ConnectionType]:"""Connect to kiosk session.Raises:@@ -168,6 +171,7 @@ class SessionConnector:)LOGGER.debug("Connecting to kiosk session")+ await self.handler._prepare_session(kiosk_session)self.handler._connect_kiosk(kiosk_session)return kiosk_session, ConnectionType.KIOSK@@ -229,6 +233,7 @@ class SessionConnector:main=True,)+ await self.handler._prepare_session(new_session)self._notify_kernel_ready(new_session)# In run mode, auto-instantiate server-side (frontend won't call it)diff --git a/marimo/_server/api/endpoints/ws_endpoint.py b/marimo/_server/api/endpoints/ws_endpoint.pyindex 77f814004a..6c073d94e1 100644--- a/marimo/_server/api/endpoints/ws_endpoint.py+++ b/marimo/_server/api/endpoints/ws_endpoint.py@@ -1,51 +1,39 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations-import asyncioimport sysfrom contextlib import aclosingfrom typing import TYPE_CHECKINGfrom starlette.responses import StreamingResponse-from starlette.websockets import WebSocket, WebSocketDisconnect, WebSocketStatefrom marimo import _loggersfrom marimo._dependencies.dependencies import DependencyManager-from marimo._messaging.notification import (- KernelStartupErrorNotification,-)from marimo._server.api.auth import validate_authfrom marimo._server.api.deps import AppState-from marimo._server.api.endpoints.ws.session_handler import SessionHandler-from marimo._server.api.endpoints.ws.sse_handler import SSESessionHandlerfrom marimo._server.api.endpoints.ws.ws_connection_validator import (ConnectionRejection,WebSocketConnectionValidator,parse_connection_params,)-from marimo._server.api.endpoints.ws.ws_formatter import (- serialize_notification_for_wire,-)-from marimo._server.api.endpoints.ws.ws_message_loop import (- WebSocketMessageLoop,-)from marimo._server.api.endpoints.ws.ws_rtc_handler import RTCWebSocketHandlerfrom marimo._server.codes import WebSocketCloseReason, WebSocketCodes+from marimo._server.host import stream_options+from marimo._server.host.lifespan import ensure_host+from marimo._server.host.session import SessionEventStreamfrom marimo._server.router import APIRouterfrom marimo._server.rtc.doc import LoroDocManagerfrom marimo._server.sse import SSE_HEADERS, format_close_event-from marimo._session.managers.ipc import KernelStartupError-from marimo._session.model import SessionModeif TYPE_CHECKING:from collections.abc import AsyncGeneratorfrom starlette.requests import Request+ from starlette.websockets import WebSocketfrom marimo._server.api.endpoints.ws.ws_connection_validator import (ConnectionParams,)- from marimo._server.session_manager import SessionManagerLOGGER = _loggers.marimo_logger()@@ -55,9 +43,6 @@ router = APIRouter()DOC_MANAGER = LoroDocManager()-# Strong refs so fire-and-forget tasks aren't GC'd mid-flight.-_background_tasks: set[asyncio.Task[None]] = set()-@router.websocket("/ws")async def websocket_endpoint(@@ -81,13 +66,36 @@ async def websocket_endpoint(if params is None:return- # Start handler- await WebSocketHandler(- websocket=websocket,- manager=app_state.session_manager,+ try:+ handler = await _session_events(websocket, params)+ except ValueError as exc:+ await websocket.close(code=1008, reason=str(exc))+ return+ await handler.start()+++async def _session_events(+ connection: WebSocket | Request, params: ConnectionParams+) -> SessionEventStream:+ message_format = connection.query_params.get("message_format", "session")+ if message_format not in ("host", "session"):+ raise ValueError("message_format must be host or session")+ cursor = stream_options.cursor(connection)+ types = stream_options.types(connection)+ if "run_id" in connection.query_params:+ raise ValueError("Session streams do not support run_id filtering")+ context = await ensure_host(connection.app)+ return SessionEventStream(+ connection,+ notebook=None,+ bridge=context.bridge,+ manager=AppState(connection).session_manager,params=params,- mode=app_state.mode,- ).start()+ doc_manager=DOC_MANAGER,+ types=types,+ cursor=cursor,+ message_format="host" if message_format == "host" else "session",+ )def _sse_response(events: AsyncGenerator[str, None]) -> StreamingResponse:@@ -114,13 +122,13 @@ def _close_only_stream(code: int, reason: str) -> StreamingResponse:async def sse_endpoint(request: Request) -> StreamingResponse:"""Experimental SSE alternative to the main `/ws` endpoint.- Enabled with `server.transport = "sse"`. Streams kernel messages as+ Enabled with `server.transport = "sse"`. Streams host events asserver-sent events; control requests flow through the regular HTTPPOST endpoints.responses:200:- description: Kernel messages as a server-sent event stream+ description: Host events as a server-sent event streamcontent:text/event-stream:schema:@@ -148,14 +156,17 @@ async def sse_endpoint(request: Request) -> StreamingResponse:# The handler connects to the session lazily, on the first iteration# of the stream. Connecting here instead would attach a consumer that# is never detached if the response body is never consumed.- handler = SSESessionHandler(- request=request,- manager=app_state.session_manager,- params=params,- mode=app_state.mode,- doc_manager=DOC_MANAGER,- )- return _sse_response(handler.stream())+ async def stream() -> AsyncGenerator[str, None]:+ try:+ handler = await _session_events(request, params)+ except ValueError as exc:+ yield format_close_event(1008, str(exc))+ return+ async with aclosing(handler.sse()) as events:+ async for event in events:+ yield event++ return _sse_response(stream())# WebSocket endpoint for LoroDoc synchronization@@ -205,138 +216,3 @@ async def ws_sync(# Handle RTC connectionhandler = RTCWebSocketHandler(websocket, file_key, DOC_MANAGER)await handler.handle()---class WebSocketHandler(SessionHandler):- """WebSocket that sessions use to send messages to frontends.-- Each new socket gets a unique session. At most one session can exist when- in edit mode (unless RTC is enabled).- """-- def __init__(- self,- *,- websocket: WebSocket,- manager: SessionManager,- params: ConnectionParams,- mode: SessionMode,- ):- super().__init__(- manager=manager,- params=params,- mode=mode,- doc_manager=DOC_MANAGER,- )- self.websocket = websocket- self.ws_future: asyncio.Task[None] | None = None-- async def start(self) -> None:- """Start the WebSocket handler.-- Accepts the connection, establishes a session, and starts the- message loop.- """- # Accept the websocket connection- await self.websocket.accept()-- LOGGER.debug(- "Websocket open request for session with id %s",- self.params.session_id,- )- LOGGER.debug("Existing sessions: %s", self.manager.sessions)-- async with self._connection_lifetime(self.websocket) as startup:- try:- async with aclosing(- self._startup_messages(startup)- ) as messages:- async for text in messages:- await self.websocket.send_text(text)- session, connection_type = await startup- except asyncio.CancelledError:- await self._safe_close(WebSocketCodes.NORMAL_CLOSE, "")- return- except KernelStartupError as e:- LOGGER.error("Kernel startup failed: %s", e)- await self._close_kernel_startup_error(str(e))- return- except WebSocketDisconnect as e:- await self._safe_close(e.code, e.reason or "")- return- LOGGER.debug(- "Connected to session %s with type %s",- session.initialization_id,- connection_type,- )-- # Start message loops- message_loop = WebSocketMessageLoop(- websocket=self.websocket,- message_queue=self.message_queue,- is_kiosk=lambda: self._is_viewer(session, connection_type),- on_check_status_update=self._check_status_update,- )-- try:- self.ws_future = asyncio.create_task(message_loop.start())- await self.ws_future- except asyncio.CancelledError:- LOGGER.debug("Websocket terminated with CancelledError")-- async def _wait_for_disconnect(self) -> None:- while True:- message = await self.websocket.receive()- if message["type"] == "websocket.disconnect":- return-- async def _safe_close(self, code: int, reason: str) -> None:- """Close the WebSocket, ignoring errors from uninitialized state.-- uvicorn never calls websockets' `connection_open()`, so internal- attributes like `transfer_data_task` are missing. Closing a- websocket in that state raises `AttributeError`. The connection- is cleaned up when the handler returns regardless.- """- if self.websocket.client_state is WebSocketState.DISCONNECTED:- # The client already closed the transport (for example, it- # navigated away while the kernel was still starting). Sending- # another close would make uvicorn raise- # "Unexpected ASGI message 'websocket.close'".- return- try:- await self.websocket.close(code, reason)- except WebSocketDisconnect:- pass- except AttributeError as e:- if "transfer_data_task" not in str(e):- raise- LOGGER.debug(- "Ignoring AttributeError during websocket close: "- "missing transfer_data_task",- exc_info=True,- )-- async def _close_kernel_startup_error(self, error_message: str) -> None:- """Send full error as message, then close the WebSocket."""- if self.websocket.application_state is WebSocketState.CONNECTED:- notification = KernelStartupErrorNotification(error=error_message)- text = serialize_notification_for_wire(notification)- await self.websocket.send_text(text)- # Then close with simple reason- await self._safe_close(- WebSocketCodes.UNEXPECTED_ERROR,- WebSocketCloseReason.KERNEL_STARTUP_ERROR,- )-- def _request_close(self, code: int, reason: str) -> None:- task = asyncio.create_task(self._safe_close(code, reason))- _background_tasks.add(task)- task.add_done_callback(_background_tasks.discard)-- def _is_transport_connected(self) -> bool:- return self.websocket.application_state is WebSocketState.CONNECTED-- def _cancel_message_loop(self) -> None:- if self.ws_future:- self.ws_future.cancel()diff --git a/marimo/_server/host/api.py b/marimo/_server/host/api.pyindex 7e9eca352d..1b383a435e 100644--- a/marimo/_server/host/api.py+++ b/marimo/_server/host/api.py@@ -10,7 +10,7 @@ from collections.abc import Awaitable, Callablefrom contextlib import contextmanagerfrom functools import wrapsfrom pathlib import Path-from typing import TYPE_CHECKING, TypeAlias, TypeVar, get_args+from typing import TYPE_CHECKING, TypeAlias, TypeVarfrom urllib.parse import quoteimport msgspec@@ -30,7 +30,6 @@ from marimo._core.errors import (NoRuntime,NotFound,)-from marimo._core.stream import event_namefrom marimo._server.api.auth import TOKEN_QUERY_PARAM, validate_authfrom marimo._server.api.deps import AppState, AppStateBasefrom marimo._server.api.endpoints.ws.ws_connection_validator import (@@ -44,10 +43,11 @@ from marimo._server.host import (ATTACHMENT_KIND,ATTACHMENT_NAME,HOST_API_PATH,+ stream_options,)from marimo._server.host.context import CachedMutation-from marimo._server.host.events import serialize_event-from marimo._server.host.websocket import EditorEventSocket+from marimo._server.host.events import serialize_event, serialize_sse_event+from marimo._server.host.session import SessionEventStreamfrom marimo._server.sse import SSE_HEADERSfrom marimo._server.tokens import AuthToken@@ -81,10 +81,6 @@ _ATTACHMENT_HEADERS = {PING = b": ping\n\n"PING_SECONDS = 15.0-OBJECT_TYPES = frozenset(get_args(get_args(protocol.ObjectType)[0])) | {- "marimo"-}-"""Values the `types` stream filter accepts."""_TITLES = {"invalid-request": "Invalid request",@@ -538,7 +534,7 @@ async def _editor_events_ws(websocket: WebSocket) -> None:code=1008, reason="Session notebook does not match")return- await EditorEventSocket(+ await SessionEventStream(websocket,notebook=notebook,bridge=bridge,@@ -623,32 +619,17 @@ async def _notebook_events_ws(websocket: WebSocket) -> None:def _cursor(request: HTTPConnection) -> str | Response | None:- raw = request.headers.get("Last-Event-ID")- if request.scope["type"] == "websocket":- query = request.query_params.get("cursor")- if query is not None:- if raw is not None and raw != query:- return problem(400, "invalid-request", "Conflicting cursors")- raw = query- if raw == "":- return problem(400, "invalid-request", "Last-Event-ID is empty")- # Cursors are opaque; one the host did not issue resets the stream.- return raw+ try:+ return stream_options.cursor(request)+ except ValueError as exc:+ return problem(400, "invalid-request", str(exc))def _types(request: HTTPConnection) -> set[str] | Response | None:- asked = request.query_params.get("types")- if not asked:- return None- types = {kind for kind in asked.split(",") if kind}- unknown = types - OBJECT_TYPES- if unknown:- return problem(- 400,- "invalid-request",- f"types has no kind named {', '.join(sorted(unknown))}",- )- return types+ try:+ return stream_options.types(request)+ except ValueError as exc:+ return problem(400, "invalid-request", str(exc))def _attachment_problem(error: msgspec.ValidationError) -> str:@@ -775,13 +756,7 @@ def _stream(def _frame(event: RoutedEvent) -> bytes:"""Encode an event as an SSE frame."""- lines = []- if event.event.id is not msgspec.UNSET:- lines.append(f"id: {event.event.id}")- lines.append(f"event: {event_name(event.event)}")- data = msgspec.json.encode(event.event.data)- lines.append(f"data: {data.decode()}")- return ("\n".join(lines) + "\n\n").encode()+ return serialize_sse_event(event).encode()# ---- notebooks -----------------------------------------------------------------diff --git a/marimo/_server/host/backend.py b/marimo/_server/host/backend.pyindex ce0d3247e0..42a4496664 100644--- a/marimo/_server/host/backend.py+++ b/marimo/_server/host/backend.py@@ -8,6 +8,8 @@ from collections.abc import Callablefrom dataclasses import dataclass, fieldfrom typing import TYPE_CHECKING+import msgspec+from marimo import _loggersfrom marimo._core import backend as be, protocolfrom marimo._messaging.notification import (@@ -25,7 +27,7 @@ from marimo._server.host.events import notification_eventfrom marimo._server.host.translate import RunTranslatorfrom marimo._server.scratchpad import snapshot_for_scratchpadfrom marimo._session.consumer import SessionConsumer-from marimo._session.model import ConnectionState+from marimo._session.model import ConnectionState, SessionModefrom marimo._session.requests import InstantiateNotebookRequestfrom marimo._session.types import KernelStatefrom marimo._types.ids import ConsumerId, SessionId@@ -366,6 +368,19 @@ class SessionBackend(SessionConsumer):)self._translators[run_id] = translatorself._observe(be.Scheduled(translator.run_id))+ # Run kernels omit source from native notifications. App documents are+ # immutable, so recover the submitted source for host revision hashes.+ # Keep the native message private and unchanged in the shared log.+ if (+ isinstance(message, ExecutionNotification)+ and message.phase == "planned"+ and message.code is None+ and self._manager.mode is SessionMode.RUN+ and self.session is not None+ ):+ cell = self.session.document.get(message.cell_id)+ if cell is not None:+ message = msgspec.structs.replace(message, code=cell.code)for out in translator.feed(message):self._observe(out)if translator.completed:diff --git a/marimo/_server/host/bridge.py b/marimo/_server/host/bridge.pyindex b5c4299336..7baaf52c39 100644--- a/marimo/_server/host/bridge.py+++ b/marimo/_server/host/bridge.py@@ -6,7 +6,6 @@ from __future__ import annotationsimport asyncioimport copyfrom dataclasses import dataclass-from pathlib import Pathfrom typing import TYPE_CHECKING, Anyfrom marimo import _loggers@@ -34,9 +33,11 @@ from marimo._session.notebook.storage import rename_no_replacefrom marimo._utils.generated_with import (contents_differ_excluding_generated_with,)+from marimo._utils.http import HTTPException, HTTPStatusif TYPE_CHECKING:from collections.abc import Mapping, Sequence+ from pathlib import Pathfrom marimo._config.manager import MarimoConfigManagerfrom marimo._core.backend import Message@@ -749,6 +750,12 @@ class SessionBridge(SessionEventListener):if path is Noneelse self.index.ensure(path))+ if notebook is None and path is not None:+ try:+ notebook = self.index.register_open_notebook(path)+ except HTTPException as exc:+ if exc.status_code != HTTPStatus.NOT_FOUND:+ raiseif notebook is None:LOGGER.debug("Not publishing session for %s", path)return None@@ -803,8 +810,4 @@ class SessionBridge(SessionEventListener):# Add notebooks to the catalog when first saved.await self.adopt(session)return- if self.index.moved(notebook.id, path) is None:- # An initially empty workspace has no project root. Keep the- # session notebook until workspace discovery can include its file.-- self.index.rename(notebook.id, Path(path).stem)+ self.index.moved(notebook.id, path)diff --git a/marimo/_server/host/events.py b/marimo/_server/host/events.pyindex d7b9b10ed4..1c5c121a9f 100644--- a/marimo/_server/host/events.py+++ b/marimo/_server/host/events.py@@ -6,7 +6,7 @@ from __future__ import annotationsimport msgspecfrom marimo._core import protocol-from marimo._core.stream import ExtensionEvent, RoutedEvent+from marimo._core.stream import ExtensionEvent, RoutedEvent, event_namefrom marimo._messaging.notification import NotificationMessage@@ -26,7 +26,7 @@ class MarimoEvent(ExtensionEvent, frozen=True, tag="marimo"):def notification_event(- notebook_id: protocol.NotebookId, notification: NotificationMessage+ notebook_id: protocol.NotebookId | None, notification: NotificationMessage) -> RoutedEvent:"""Wrap a notification with its notebook and optional run scope."""run_id = getattr(notification, "run_id", None)@@ -37,6 +37,37 @@ def notification_event()-def serialize_event(event: RoutedEvent) -> str:- """Encode one host event as a WebSocket frame."""- return msgspec.json.encode(event.event).decode()+def _visible_event(+ event: RoutedEvent, *, include_code: bool+) -> protocol.Event | ExtensionEvent:+ """Encode a frame using this connection's source-visibility policy.++ Project a copy at delivery, so the host retains source and revisions for+ snapshots, replay, and staleness checks regardless of the reader.+ """+ message = event.event+ if not include_code and isinstance(message, protocol.CellEvent):+ cell = msgspec.structs.replace(message.data.cell, code=None)+ data = msgspec.structs.replace(message.data, cell=cell)+ message = msgspec.structs.replace(message, data=data)+ return message+++def serialize_event(event: RoutedEvent, *, include_code: bool = True) -> str:+ """Encode a host WebSocket envelope."""+ return msgspec.json.encode(+ _visible_event(event, include_code=include_code)+ ).decode()+++def serialize_sse_event(+ event: RoutedEvent, *, include_code: bool = True+) -> str:+ """Encode the same host event using SSE fields."""+ message = _visible_event(event, include_code=include_code)+ lines = []+ if message.id is not msgspec.UNSET:+ lines.append(f"id: {message.id}")+ lines.append(f"event: {event_name(message)}")+ lines.append(f"data: {msgspec.json.encode(message.data).decode()}")+ return "\n".join(lines) + "\n\n"diff --git a/marimo/_server/host/index.py b/marimo/_server/host/index.pyindex 6b8c1e6e32..33605182ea 100644--- a/marimo/_server/host/index.py+++ b/marimo/_server/host/index.py@@ -1,5 +1,5 @@# Copyright 2026 Marimo. All rights reserved.-"""Workspace files indexed as a host project.+"""Workspace files and explicitly opened notebooks in the host catalog.Notebook IDs persist across rescans and recorded file moves."""@@ -27,7 +27,7 @@ _TRUNCATED = "The scan stopped at its depth, file count, or time limit"class WorkspaceIndex:- """A host project and its indexed notebook files."""+ """Workspace files and explicitly opened files exposed as host notebooks."""def __init__(self,@@ -41,6 +41,8 @@ class WorkspaceIndex:self._root = _root_of(workspace)self.project_id = mint(protocol.ProjectId, "proj")self._ids: dict[Path, protocol.NotebookId] = {}+ self._open_project_id: protocol.ProjectId | None = None+ self._open_files: dict[protocol.NotebookId, Path] = {}self._names: dict[protocol.NotebookId, str] = {}"""Client-selected names preserved across rescans."""self._refresh_lock = asyncio.Lock()@@ -114,6 +116,60 @@ class WorkspaceIndex:return Nonereturn self._publish(file, modified, request_id=request_id)+ def register_open_notebook(self, path: str) -> protocol.Notebook:+ """Register an authorized file, including files outside the workspace."""+ resolved = self._workspace.resolve(path)+ assert resolved is not None+ existing = self.notebook_for(resolved) or self.ensure(resolved)+ if existing is not None:+ return existing+ return self._publish_open_notebook(+ mint(protocol.NotebookId, "nb"), Path(resolved)+ )++ def _publish_open_notebook(+ self,+ notebook_id: protocol.NotebookId,+ file: Path,+ *,+ request_id: str | None = None,+ ) -> protocol.Notebook:+ if self._open_project_id is None:+ self._open_project_id = mint(protocol.ProjectId, "proj")+ self._host.update_project(+ protocol.Project(+ id=self._open_project_id,+ name="Open notebooks",+ root=None,+ status="indexed",+ message=None,+ operations=(),+ )+ )+ record = protocol.Notebook(+ id=notebook_id,+ project_id=self._open_project_id,+ path=None,+ name=self._names.get(notebook_id, file.stem),+ operations=tuple(+ op+ for op in OPERATIONS+ if op+ not in {+ "notebook.create",+ "notebook.update",+ "notebook.delete",+ }+ ),+ updated_at=None,+ )+ self._open_files[record.id] = file+ if notebook_id in self._host.notebooks:+ self._host.update_notebook(record, request_id=request_id)+ else:+ self._host.add_notebook(record, self._initialize)+ return record+def untitled(self) -> protocol.Notebook:"""Register an editor document before it has a file."""record = protocol.Notebook(@@ -133,17 +189,20 @@ class WorkspaceIndex:path: str,*,request_id: str | None = None,- ) -> protocol.Notebook | None:+ ) -> protocol.Notebook:"""Update a notebook's file path, keeping its ID.- Return `None` for a path outside the project.+ Files outside the workspace belong to the Open notebooks project."""relative = self._relative(Path(path))- if relative is None:- return Nonefor old, known in list(self._ids.items()):if known == notebook_id:del self._ids[old]+ if relative is None:+ return self._publish_open_notebook(+ notebook_id, Path(path).resolve(), request_id=request_id+ )+ self._open_files.pop(notebook_id, None)self._ids[relative] = notebook_idassert self._root is not Nonefile = self._root / relative@@ -151,7 +210,9 @@ class WorkspaceIndex:modified: float | None = file.stat().st_mtimeexcept OSError:modified = None- return self._publish(file, modified, request_id=request_id)+ record = self._publish(file, modified, request_id=request_id)+ assert record is not None+ return recorddef rename(self,@@ -178,12 +239,16 @@ class WorkspaceIndex:if known == notebook_id:del self._ids[path]self._names.pop(notebook_id, None)+ self._open_files.pop(notebook_id, None)self._host.remove_notebook(notebook_id, request_id=request_id)def notebook_for(self, path: str | None) -> protocol.Notebook | None:"""Look up a cataloged notebook by file path."""if path is None:return None+ for notebook_id, file in self._open_files.items():+ if file.resolve() == Path(path).resolve():+ return self._host.notebooks[notebook_id]relative = self._relative(Path(path))if relative is None or relative not in self._ids:return None@@ -191,6 +256,8 @@ class WorkspaceIndex:def file_of(self, notebook_id: protocol.NotebookId) -> Path | None:"""Return a notebook's absolute file path, if available."""+ if notebook_id in self._open_files:+ return self._open_files[notebook_id]record = self._host.notebooks.get(notebook_id)if record is None or record.path is None or self._root is None:return Nonediff --git a/marimo/_server/host/lifespan.py b/marimo/_server/host/lifespan.pyindex a69993020b..32134b16bd 100644--- a/marimo/_server/host/lifespan.py+++ b/marimo/_server/host/lifespan.py@@ -40,19 +40,13 @@ async def ensure_app_host(app: Starlette) -> HostContext:return context-async def host(app: Starlette) -> AsyncIterator[None]:- """Serve notebook sessions; publish local discovery only in edit mode."""+async def ensure_host(app: Starlette) -> HostContext:+ """Return the host used by session brokering and the server lifespan."""state = AppStateBase.from_app(app)if state.mode is SessionMode.RUN:- context = await ensure_app_host(app)- try:- yield- finally:- context.bridge.close()- app.state.host_context = None- return-+ return await ensure_app_host(app)+ if state.host_context is not None:+ return state.host_contextserver = state.server.configurl_host = format_url_host(server.host, server.port, route_bind_all_to_loopback=True@@ -69,10 +63,29 @@ async def host(app: Starlette) -> AsyncIterator[None]:)await bridge.open()token = secrets.token_urlsafe(32)- url = host_url(server.host, server.port, state.base_url)context = HostContext(bridge=bridge, token=token, port=server.port)app.state.host_context = context+ return context+++async def host(app: Starlette) -> AsyncIterator[None]:+ """Serve notebook sessions; publish local discovery only in edit mode."""+ state = AppStateBase.from_app(app)+ if state.mode is SessionMode.RUN:+ context = await ensure_app_host(app)+ try:+ yield+ finally:+ context.bridge.close()+ app.state.host_context = None+ return++ context = await ensure_host(app)+ server = state.server.config+ url = host_url(server.host, server.port, state.base_url)+async def maintain() -> None:while True:await asyncio.sleep(1)@@ -83,7 +96,7 @@ async def host(app: Starlette) -> AsyncIterator[None]:if url is None:LOGGER.warning("No host record: loopback cannot reach %s", server.host)else:- record = HostRecordFile(url=url, token=token)+ record = HostRecordFile(url=url, token=context.token)try:record.write()except Exception as e:@@ -96,5 +109,5 @@ async def host(app: Starlette) -> AsyncIterator[None]:await maintenanceif record is not None:record.remove()- bridge.close()+ context.bridge.close()app.state.host_context = Nonediff --git a/marimo/_server/host/session.py b/marimo/_server/host/session.pynew file mode 100644index 0000000000..6c04921d06--- /dev/null+++ b/marimo/_server/host/session.py@@ -0,0 +1,286 @@+# Copyright 2026 Marimo. All rights reserved.+"""Editor and app sessions carried by the host event stream."""++from __future__ import annotations++import asyncio+from contextlib import aclosing+from dataclasses import dataclass+from typing import TYPE_CHECKING, Literal++from starlette.websockets import WebSocket, WebSocketDisconnect, WebSocketState++from marimo._core import protocol+from marimo._core.stream import RoutedEvent+from marimo._messaging.notification import KernelStartupErrorNotification+from marimo._messaging.serde import (+ deserialize_kernel_message,+ serialize_kernel_message,+)+from marimo._server.api.endpoints.ws.notification_filter import (+ should_filter_operation,+)+from marimo._server.api.endpoints.ws.session_handler import SessionHandler+from marimo._server.api.endpoints.ws.ws_session_connector import ConnectionType+from marimo._server.codes import WebSocketCloseReason, WebSocketCodes+from marimo._server.host.events import (+ MarimoEvent,+ notification_event,+ serialize_event,+ serialize_sse_event,+)+from marimo._server.sse import (+ HEARTBEAT_EVENT,+ format_close_event,+ format_sse_event,+ wait_for_http_disconnect,+)+from marimo._session.managers.ipc import KernelStartupError+from marimo._utils.asyncio_utils import cancel_and_wait++if TYPE_CHECKING:+ from collections.abc import AsyncGenerator, Callable++ from starlette.requests import Request++ from marimo._core.notebook import Notebook+ from marimo._messaging.types import KernelMessage+ from marimo._server.api.endpoints.ws.ws_connection_validator import (+ ConnectionParams,+ )+ from marimo._server.host.bridge import SessionBridge+ from marimo._server.rtc.doc import LoroDocManager+ from marimo._server.session_manager import SessionManager+ from marimo._session.session import Session+++@dataclass(frozen=True)+class _Close:+ code: int+ reason: str+++class SessionEventStream(SessionHandler):+ """Merge host events with the session's private notification delivery."""++ def __init__(+ self,+ connection: WebSocket | Request,+ *,+ notebook: Notebook | None,+ bridge: SessionBridge,+ manager: SessionManager,+ params: ConnectionParams,+ doc_manager: LoroDocManager,+ types: set[str] | None,+ cursor: str | None,+ heartbeat_seconds: float = 20.0,+ message_format: Literal["host", "session"] = "host",+ ) -> None:+ super().__init__(+ manager=manager,+ params=params,+ mode=manager.mode,+ doc_manager=doc_manager,+ )+ self.message_format = message_format+ self.connection = connection+ self.heartbeat_seconds = heartbeat_seconds+ self._stream_finished = False+ self.notebook = notebook+ self.bridge = bridge+ self.types = types+ self.cursor = cursor+ self._attachment: protocol.Attachment | None = None+ self._unsubscribe: Callable[[], None] | None = None+ self._ready_id = 0+ self._events: asyncio.Queue[RoutedEvent | _Close | None] = (+ asyncio.Queue()+ )+ self._connection_type = (+ ConnectionType.RTC_EXISTING+ if params.rtc_enabled and not params.kiosk+ else ConnectionType.NEW+ )++ def notify(self, notification: KernelMessage) -> None:+ event = notification_event(+ self.notebook.id if self.notebook is not None else None,+ deserialize_kernel_message(notification),+ )+ if event.wanted(self.types):+ self._events.put_nowait(event)++ def _on_host_event(self, event: RoutedEvent) -> None:+ # The session delivers marimo notifications with recipient filtering,+ # including edits that must not echo to the client that sent them.+ if not isinstance(event.event, MarimoEvent) and (+ event.position is None or event.position > self._ready_id+ ):+ self._events.put_nowait(event)++ async def _prepare_session(self, session: Session) -> None:+ if self.notebook is None:+ if (+ self.cursor is not None+ and self.bridge.notebook_for_session(session) is None+ ):+ self._events.put_nowait(+ RoutedEvent(protocol.ResetEvent(data={}))+ )+ self.cursor = None+ notebook = await self.bridge.adopt(session)+ if notebook is None:+ raise WebSocketDisconnect(+ WebSocketCodes.UNEXPECTED_ERROR, "Notebook unavailable"+ )+ self._subscribe(notebook)+ else:+ await self.bridge.bind(self.notebook.id, session)++ def _subscribe(self, notebook: Notebook) -> None:+ self.notebook = notebook+ self._attachment = notebook.attach(identity=self.params.session_id)+ self._unsubscribe = self.bridge.host.subscribe(+ self._on_host_event, notebook_id=notebook.id, types=self.types+ )+ initial = self.bridge.host.events(+ self.cursor, notebook_id=notebook.id, types=self.types+ )+ self._ready_id = initial[-1].position or 0+ for event in initial:+ # Native replay must retain the session's recipient filtering.+ if not isinstance(event.event, MarimoEvent):+ self._events.put_nowait(event)++ async def stream(+ self,+ ) -> AsyncGenerator[RoutedEvent | _Close | None, None]:+ """Broker the session and deliver its host events until disconnect."""+ try:+ if self.notebook is not None:+ self._subscribe(self.notebook)+ async with self._connection_lifetime(self.connection) as startup:++ async def connect_and_listen() -> None:+ try:+ _, self._connection_type = await startup+ self._check_status_update()+ await self._wait_for_disconnect()+ except asyncio.CancelledError:+ return+ except KernelStartupError as exc:+ self._serialize_and_notify(+ KernelStartupErrorNotification(error=str(exc))+ )+ self._request_close(+ WebSocketCodes.UNEXPECTED_ERROR,+ WebSocketCloseReason.KERNEL_STARTUP_ERROR,+ )+ except WebSocketDisconnect as exc:+ self._request_close(exc.code, exc.reason or "")+ finally:+ self._events.put_nowait(None)++ listening = asyncio.create_task(connect_and_listen())+ try:+ while True:+ try:+ event = await asyncio.wait_for(+ self._events.get(), self.heartbeat_seconds+ )+ except asyncio.TimeoutError:+ yield None+ continue+ if event is None:+ await listening+ return+ if isinstance(event, _Close):+ yield event+ return+ if isinstance(event.event, MarimoEvent):+ viewer = self.params.kiosk+ if self._session is not None:+ viewer = self._is_viewer(+ self._session, self._connection_type+ )+ if should_filter_operation(+ event.event.data.marimo.name, is_kiosk=viewer+ ):+ continue+ yield event+ finally:+ await cancel_and_wait(listening)+ finally:+ self._stream_finished = True+ if self._unsubscribe is not None:+ self._unsubscribe()+ if self.notebook is not None and self._attachment is not None:+ self.notebook.detach(self._attachment.id)++ def _serialize(self, event: RoutedEvent) -> str | None:+ # Temporary wire compatibility; lifecycle and recipient filtering are+ # shared with host delivery. Remove after the frontend cutover.+ if self.message_format == "session":+ if not isinstance(event.event, MarimoEvent):+ return None+ notification = event.event.data.marimo+ data = serialize_kernel_message(notification).decode()+ return f'{{"op": "{notification.name}", "data": {data}}}'+ return serialize_event(+ event, include_code=self.manager.should_send_code_to_frontend()+ )++ async def start(self) -> None:+ """Deliver the host stream over a WebSocket."""+ websocket = self.connection+ assert isinstance(websocket, WebSocket)+ await websocket.accept()+ try:+ async with aclosing(self.stream()) as events:+ async for event in events:+ if isinstance(event, _Close):+ if (+ websocket.client_state+ is not WebSocketState.DISCONNECTED+ ):+ await websocket.close(event.code, event.reason)+ elif event is not None:+ payload = self._serialize(event)+ if payload is not None:+ await websocket.send_text(payload)+ except WebSocketDisconnect:+ pass++ async def sse(self) -> AsyncGenerator[str, None]:+ """Frame the same host envelopes as SSE, including close and heartbeat."""+ async with aclosing(self.stream()) as events:+ async for event in events:+ if isinstance(event, _Close):+ yield format_close_event(event.code, event.reason)+ elif event is None:+ yield HEARTBEAT_EVENT+ elif self.message_format == "session":+ payload = self._serialize(event)+ if payload is not None:+ yield format_sse_event(payload)+ else:+ yield serialize_sse_event(+ event,+ include_code=self.manager.should_send_code_to_frontend(),+ )++ async def _wait_for_disconnect(self) -> None:+ if isinstance(self.connection, WebSocket):+ while True:+ message = await self.connection.receive()+ if message["type"] == "websocket.disconnect":+ return+ else:+ await wait_for_http_disconnect(self.connection)++ def _request_close(self, code: int, reason: str) -> None:+ self._events.put_nowait(_Close(code, reason))++ def _is_transport_connected(self) -> bool:+ return not self._stream_finisheddiff --git a/marimo/_server/host/stream_options.py b/marimo/_server/host/stream_options.pynew file mode 100644index 0000000000..ee400031df--- /dev/null+++ b/marimo/_server/host/stream_options.py@@ -0,0 +1,40 @@+# Copyright 2026 Marimo. All rights reserved.+"""Subscription options shared by host and session stream routes."""++from __future__ import annotations++from typing import TYPE_CHECKING, get_args++from marimo._core import protocol++if TYPE_CHECKING:+ from starlette.requests import HTTPConnection++OBJECT_TYPES = frozenset(get_args(get_args(protocol.ObjectType)[0])) | {+ "marimo"+}+++def cursor(connection: HTTPConnection) -> str | None:+ raw = connection.headers.get("Last-Event-ID")+ query = connection.query_params.get("cursor")+ if query is not None:+ if raw is not None and raw != query:+ raise ValueError("Conflicting cursors")+ raw = query+ if raw == "":+ raise ValueError("Last-Event-ID is empty")+ return raw+++def types(connection: HTTPConnection) -> set[str] | None:+ asked = connection.query_params.get("types")+ if not asked:+ return None+ kinds = {kind for kind in asked.split(",") if kind}+ unknown = kinds - OBJECT_TYPES+ if unknown:+ raise ValueError(+ f"types has no kind named {', '.join(sorted(unknown))}"+ )+ return kindsdiff --git a/marimo/_server/host/websocket.py b/marimo/_server/host/websocket.pydeleted file mode 100644index 5d4ba283cc..0000000000--- a/marimo/_server/host/websocket.py+++ /dev/null@@ -1,196 +0,0 @@-# Copyright 2026 Marimo. All rights reserved.-"""Editor sessions carried by the host event socket."""--from __future__ import annotations--import asyncio-from dataclasses import dataclass-from typing import TYPE_CHECKING--from starlette.websockets import WebSocketDisconnect, WebSocketState--from marimo._messaging.notification import KernelStartupErrorNotification-from marimo._messaging.serde import deserialize_kernel_message-from marimo._server.api.endpoints.ws.session_handler import SessionHandler-from marimo._server.api.endpoints.ws.ws_message_loop import (- should_filter_operation,-)-from marimo._server.api.endpoints.ws.ws_session_connector import ConnectionType-from marimo._server.codes import WebSocketCloseReason, WebSocketCodes-from marimo._server.host.events import (- MarimoEvent,- notification_event,- serialize_event,-)-from marimo._session.managers.ipc import KernelStartupError-from marimo._utils.asyncio_utils import cancel_and_wait--if TYPE_CHECKING:- from starlette.websockets import WebSocket-- from marimo._core.notebook import Notebook- from marimo._core.stream import RoutedEvent- from marimo._messaging.types import KernelMessage- from marimo._server.api.endpoints.ws.ws_connection_validator import (- ConnectionParams,- )- from marimo._server.host.bridge import SessionBridge- from marimo._server.rtc.doc import LoroDocManager- from marimo._server.session_manager import SessionManager---@dataclass(frozen=True)-class _Close:- code: int- reason: str---class EditorEventSocket(SessionHandler):- """Merge host events with the session's private notification delivery."""-- # Shared-log replay omits native notifications to preserve recipients.- _replay_notebook_on_reconnect = True-- def __init__(- self,- websocket: WebSocket,- *,- notebook: Notebook,- bridge: SessionBridge,- manager: SessionManager,- params: ConnectionParams,- doc_manager: LoroDocManager,- types: set[str] | None,- cursor: str | None,- ) -> None:- super().__init__(- manager=manager,- params=params,- mode=manager.mode,- doc_manager=doc_manager,- )- self.websocket = websocket- self.notebook = notebook- self.bridge = bridge- self.types = types- self.cursor = cursor- self._ready_id = 0- self._events: asyncio.Queue[RoutedEvent | _Close] = asyncio.Queue()- self._connection_type = (- ConnectionType.RTC_EXISTING- if params.rtc_enabled and not params.kiosk- else ConnectionType.NEW- )-- def notify(self, notification: KernelMessage) -> None:- event = notification_event(- self.notebook.id, deserialize_kernel_message(notification)- )- if event.wanted(self.types):- self._events.put_nowait(event)-- def _on_host_event(self, event: RoutedEvent) -> None:- # The session delivers marimo notifications with recipient filtering,- # including edits that must not echo to the client that sent them.- if not isinstance(event.event, MarimoEvent) and (- event.position is None or event.position > self._ready_id- ):- self._events.put_nowait(event)-- async def start(self) -> None:- attachment = self.notebook.attach(identity=self.params.session_id)- unsubscribe = self.bridge.host.subscribe(- self._on_host_event,- notebook_id=self.notebook.id,- types=self.types,- )- try:- initial = self.bridge.host.events(- self.cursor, notebook_id=self.notebook.id, types=self.types- )- self._ready_id = initial[-1].position or 0- for event in initial:- # Session notifications must retain their recipient filtering,- # including on reconnect; only protocol records use replay.- if not isinstance(event.event, MarimoEvent):- self._events.put_nowait(event)- await self.websocket.accept()- async with self._connection_lifetime(self.websocket) as startup:- sending = asyncio.create_task(self._send_events())-- async def connect_and_listen() -> None:- try:- _, self._connection_type = await startup- except asyncio.CancelledError:- return- except KernelStartupError as exc:- self._serialize_and_notify(- KernelStartupErrorNotification(error=str(exc))- )- self._request_close(- WebSocketCodes.UNEXPECTED_ERROR,- WebSocketCloseReason.KERNEL_STARTUP_ERROR,- )- await sending- return- except WebSocketDisconnect as exc:- self._request_close(exc.code, exc.reason or "")- await sending- return- self._check_status_update()- await self._wait_for_disconnect()-- listening = asyncio.create_task(connect_and_listen())- try:- done, _ = await asyncio.wait(- (sending, listening),- return_when=asyncio.FIRST_COMPLETED,- )- for task in done:- task.result()- except WebSocketDisconnect:- pass- finally:- await cancel_and_wait(listening)- await cancel_and_wait(sending)- finally:- unsubscribe()- self.notebook.detach(attachment.id)-- async def _send_events(self) -> None:- while True:- event = await self._events.get()- if isinstance(event, _Close):- if (- self.websocket.client_state- is not WebSocketState.DISCONNECTED- ):- await self.websocket.close(event.code, event.reason)- return- if isinstance(event.event, MarimoEvent):- viewer = self.params.kiosk- if self._session is not None:- viewer = self._is_viewer(- self._session, self._connection_type- )- if should_filter_operation(- event.event.data.marimo.name, is_kiosk=viewer- ):- continue- await self.websocket.send_text(serialize_event(event))-- async def _wait_for_disconnect(self) -> None:- while True:- message = await self.websocket.receive()- if message["type"] == "websocket.disconnect":- return-- def _request_close(self, code: int, reason: str) -> None:- self._events.put_nowait(_Close(code, reason))-- def _is_transport_connected(self) -> bool:- return self.websocket.application_state is WebSocketState.CONNECTED-- def _cancel_message_loop(self) -> None:- # on_detach queues a close behind pending notifications.- passdiff --git a/marimo/_session/state/session_view.py b/marimo/_session/state/session_view.pyindex f8e8198306..ff58e6744a 100644--- a/marimo/_session/state/session_view.py+++ b/marimo/_session/state/session_view.py@@ -600,13 +600,10 @@ class SessionView:self.last_execution_time[cell_id] = time_elapsed- def snapshot_notifications(- self, *, include_notebook: bool = True- ) -> list[NotificationMessage]:+ def snapshot_notifications(self) -> list[NotificationMessage]:"""Copy retained notifications for a connecting client.- An existing client can omit notebook state and refresh only its- environment and startup status. The caller supplies kernel-ready.+ The caller supplies kernel-ready before replaying these notifications."""notifications: list[NotificationMessage] = [EnvironmentStateNotification(source=source, state=state)@@ -614,8 +611,7 @@ class SessionView:]if self.startup_progress is not None:notifications.append(self.startup_progress)- if include_notebook:- notifications.extend(self._notebook_notifications())+ notifications.extend(self._notebook_notifications())return copy.deepcopy(notifications)def _notebook_notifications(self) -> list[NotificationMessage]:diff --git a/marimo/_templates.py b/marimo/_templates.pyindex b537c35a23..19e83ea135 100644--- a/marimo/_templates.py+++ b/marimo/_templates.py@@ -107,7 +107,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,+ message_format: Literal["host", "session"] | None = None,layout: LayoutConfig | None = None,) -> str:"""@@ -146,9 +146,9 @@ def _get_mount_config("hostEnabled": mode == "edit",})- host_notebook = (- ',\n "notebookId": ' + json_script(notebook_id)- if notebook_id is not None+ stream_format = (+ ',\n "messageFormat": ' + json_script(message_format)+ if message_format is not Noneelse "")@@ -166,13 +166,13 @@ def _get_mount_config("view": {view},"notebook": {notebook},"session": {session},- "runtimeConfig": {runtime_config}{host_notebook},+ "runtimeConfig": {runtime_config}{stream_format},"pairConfig": {pair_config}}}""".format(**{k: json_script(v) for k, v in options.items()},pair_config=pair_config,- host_notebook=host_notebook,+ stream_format=stream_format,).strip()@@ -306,7 +306,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,+ message_format: Literal["host", "session"] | None = None,asset_url: str | None = None,html_head: str | None = None,execute_opengraph_generators: bool = False,@@ -350,7 +350,7 @@ def notebook_page_template(config_overrides=config_overrides,app_config=app_config,runtime_config=runtime_config,- notebook_id=notebook_id,+ message_format=message_format,notebook_snapshot=notebook_snapshot,session_snapshot=session_snapshot,),diff --git a/tests/_server/api/endpoints/test_assets.py b/tests/_server/api/endpoints/test_assets.pyindex 8f1dcf9d70..7b8fa42adc 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_supplies_the_local_host_notebook_identity(+def test_index_selects_stream_format_without_provisioning_a_notebook(client: TestClient, remote_url: str | None, cataloged: bool) -> None:state = AppState.from_app(cast(Any, client.app))@@ -1001,19 +1001,7 @@ def test_index_supplies_the_local_host_notebook_identity(response = client.get("/", headers=token_header())assert response.status_code == 200config = 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 config["messageFormat"] == "host"+ assert "notebookId" not in config+ assert bridge.host.notebooks == initial_notebooksassert not state.session_manager.sessionsdiff --git a/tests/_server/api/endpoints/test_auto_instantiate.py b/tests/_server/api/endpoints/test_auto_instantiate.pyindex 69d777e4e4..fb29ec532e 100644--- a/tests/_server/api/endpoints/test_auto_instantiate.py+++ b/tests/_server/api/endpoints/test_auto_instantiate.py@@ -9,6 +9,7 @@ from unittest.mock import MagicMock, patchfrom marimo._messaging.notification import KernelReadyNotificationfrom marimo._session.model import SessionModefrom marimo._utils.parse_dataclass import parse_raw+from tests._server.api.endpoints.ws_helpers import receive_notificationfrom tests._server.mocks import token_headerif TYPE_CHECKING:@@ -38,7 +39,7 @@ class TestAutoInstantiateEditMode:ws_url = _create_ws_url(session_id)with client.websocket_connect(ws_url) as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert data["op"] == "kernel-ready"kernel_ready = parse_raw(data["data"], KernelReadyNotification)@@ -55,7 +56,7 @@ class TestAutoInstantiateEditMode:with client.websocket_connect(ws_url) as websocket:# Wait for the session to be fully established- data = websocket.receive_json()+ data = receive_notification(websocket)assert data["op"] == "kernel-ready"# The /instantiate endpoint should work in edit mode@@ -84,7 +85,7 @@ class TestAutoInstantiateRunMode:ws_url = _create_ws_url(session_id)with client.websocket_connect(ws_url) as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert data["op"] == "kernel-ready"kernel_ready = parse_raw(data["data"], KernelReadyNotification)@@ -110,7 +111,7 @@ class TestAutoInstantiateRunMode:with client.websocket_connect(ws_url) as websocket:# Wait for the session to be fully established- data = websocket.receive_json()+ data = receive_notification(websocket)assert data["op"] == "kernel-ready"# The /instantiate endpoint should be blocked in run mode@@ -217,7 +218,7 @@ class TestInstantiateNotebookRequest:with client.websocket_connect(ws_url) as websocket:# Get the kernel-ready message- data = websocket.receive_json()+ data = receive_notification(websocket)assert data["op"] == "kernel-ready"# Send instantiate without codes (should use file codes)diff --git a/tests/_server/api/endpoints/test_document_endpoints.py b/tests/_server/api/endpoints/test_document_endpoints.pyindex 4dc784d437..c03c1c7869 100644--- a/tests/_server/api/endpoints/test_document_endpoints.py+++ b/tests/_server/api/endpoints/test_document_endpoints.py@@ -6,6 +6,7 @@ from typing import TYPE_CHECKINGfrom tests._server.api.endpoints.ws_helpers import (HEADERS as _HEADERS,assert_kernel_ready_response,+ receive_notification,)if TYPE_CHECKING:@@ -23,7 +24,7 @@ def test_create_cell_with_missing_anchor_is_appended(with client.websocket_connect("/ws?session_id=123", headers=_HEADERS) as websocket:- assert_kernel_ready_response(websocket.receive_json())+ assert_kernel_ready_response(receive_notification(websocket))response = client.post("/api/document/transaction",@@ -56,7 +57,7 @@ def test_delete_of_missing_cell_is_a_no_op(client: TestClient) -> None:with client.websocket_connect("/ws?session_id=123", headers=_HEADERS) as websocket:- assert_kernel_ready_response(websocket.receive_json())+ assert_kernel_ready_response(receive_notification(websocket))sm = client.app.state.session_managersession = next(iter(sm.sessions.values()))diff --git a/tests/_server/api/endpoints/test_editing.py b/tests/_server/api/endpoints/test_editing.pyindex 8657bc6c53..ec510ae42c 100644--- a/tests/_server/api/endpoints/test_editing.py+++ b/tests/_server/api/endpoints/test_editing.py@@ -7,7 +7,10 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom marimo._dependencies.dependencies import DependencyManager-from tests._server.api.endpoints.ws_helpers import receive_until+from tests._server.api.endpoints.ws_helpers import (+ receive_notification,+ receive_until,+)from tests._server.mocks import token_header, with_sessionHAS_FORMATTER = DependencyManager.ruff.has() or DependencyManager.black.has()@@ -197,7 +200,7 @@ def test_focus_cell_notifies_same_session_kiosk_consumer(f"/ws?session_id={SESSION_ID}&kiosk=true&access_token=fake-token",headers=auth_token,) as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert data["op"] == "kernel-ready"assert data["data"]["kiosk"] is Truediff --git a/tests/_server/api/endpoints/test_execution.py b/tests/_server/api/endpoints/test_execution.pyindex 7839662f02..999b4e6de4 100644--- a/tests/_server/api/endpoints/test_execution.py+++ b/tests/_server/api/endpoints/test_execution.py@@ -29,6 +29,7 @@ from tests._server.api.endpoints.ws_helpers import (HEADERS as WS_HEADERS,assert_kernel_ready_response,create_response,+ receive_notification,receive_until,)from tests._server.mocks import (@@ -822,12 +823,12 @@ def test_takeover_transfers_edit_without_disconnect(with client.websocket_connect("/ws?session_id=ed1", headers=WS_HEADERS) as editor:- assert_kernel_ready_response(editor.receive_json())+ assert_kernel_ready_response(receive_notification(editor))with client.websocket_connect("/ws?session_id=vw1", headers=WS_HEADERS) as viewer:assert_kernel_ready_response(- viewer.receive_json(),+ receive_notification(viewer),create_response({"kiosk": True,diff --git a/tests/_server/api/endpoints/test_file_explorer.py b/tests/_server/api/endpoints/test_file_explorer.pyindex c3564ce0b6..a640f96d19 100644--- a/tests/_server/api/endpoints/test_file_explorer.py+++ b/tests/_server/api/endpoints/test_file_explorer.py@@ -9,6 +9,7 @@ from typing import TYPE_CHECKING, castimport pytestfrom marimo._utils.platform import is_windows+from tests._server.api.endpoints.ws_helpers import receive_notificationfrom tests._server.mocks import (get_session_manager,token_header,@@ -366,7 +367,7 @@ def test_update_file_with_session(client: TestClient) -> None:"/ws?session_id=test-session&access_token=fake-token") as websocket:# Receive kernel ready message- data = websocket.receive_json()+ data = receive_notification(websocket)assert data["op"] == "kernel-ready"# Verify file watcher was attached when session was createddiff --git a/tests/_server/api/endpoints/test_files.py b/tests/_server/api/endpoints/test_files.pyindex 1d94f05b4b..8f219ecfd4 100644--- a/tests/_server/api/endpoints/test_files.py+++ b/tests/_server/api/endpoints/test_files.py@@ -13,6 +13,7 @@ import msgspecimport pytestfrom marimo._utils.platform import is_windows+from tests._server.api.endpoints.ws_helpers import receive_notificationfrom tests._server.mocks import (get_session_manager,token_header,@@ -556,7 +557,7 @@ def test_rename_propagates(variables = {}while len(variables) < 2:- data = websocket.receive_json()+ data = receive_notification(websocket)if data["op"] == "variable-values":for var in data["data"]["variables"]:variables[var["name"]] = var["value"]@@ -582,7 +583,7 @@ def test_rename_propagates(variables = {}while len(variables) < 2:- data = websocket.receive_json()+ data = receive_notification(websocket)if data["op"] == "variable-values":for var in data["data"]["variables"]:variables[var["name"]] = var["value"]diff --git a/tests/_server/api/endpoints/test_health.py b/tests/_server/api/endpoints/test_health.pyindex 0a97a3f130..47eb3ce974 100644--- a/tests/_server/api/endpoints/test_health.py+++ b/tests/_server/api/endpoints/test_health.py@@ -8,6 +8,8 @@ import pytestfrom marimo import __version__from marimo._types.ids import SessionId+from tests._server.api.endpoints.ws_helpers import receive_notification+from tests._server.host.drive import socket_snapshotfrom tests._server.mocks import (get_session_manager,token_header,@@ -76,16 +78,23 @@ def test_sessions_stable_id_survives_reconnect(client: TestClient, connection_id: str) -> None:with client.websocket_connect(- f"/ws?session_id={SESSION_ID}", headers=token_header()+ f"/ws?message_format=host&session_id={SESSION_ID}",+ headers=token_header(),) as websocket:- assert websocket.receive_json()["op"] == "kernel-ready"+ snapshot = socket_snapshot(websocket)+ notebook_id = next(+ e["data"]["notebook"]["id"]+ for e in snapshot+ if e["event"] == "notebook"+ )+ assert receive_notification(websocket)["op"] == "kernel-ready"session = get_session_manager(client).get_session(SessionId(SESSION_ID))assert session is not Noneexpected = {"session_id": session.stable_id,- "notebook_id": None,+ "notebook_id": notebook_id,"filename": session.app_file_manager.filename,"path": session.app_file_manager.path,}@@ -94,9 +103,10 @@ def test_sessions_stable_id_survives_reconnect(assert response.json() == {SESSION_ID: expected}with client.websocket_connect(- f"/ws?session_id={connection_id}", headers=token_header()+ f"/ws?message_format=host&session_id={connection_id}",+ headers=token_header(),) as websocket:- assert websocket.receive_json()["op"] == "reconnected"+ assert receive_notification(websocket)["op"] == "reconnected"response = client.get("/api/sessions", headers=token_header())assert response.status_code == 200, response.textassert response.json() == {connection_id: expected}@@ -104,9 +114,10 @@ def test_sessions_stable_id_survives_reconnect(def test_sessions_stable_id_changes_after_restart(client: TestClient) -> None:with client.websocket_connect(- f"/ws?session_id={SESSION_ID}", headers=token_header()+ f"/ws?message_format=host&session_id={SESSION_ID}",+ headers=token_header(),) as websocket:- assert websocket.receive_json()["op"] == "kernel-ready"+ assert receive_notification(websocket)["op"] == "kernel-ready"response = client.get("/api/sessions", headers=token_header())assert response.status_code == 200, response.textprevious = response.json()[SESSION_ID]@@ -118,9 +129,10 @@ def test_sessions_stable_id_changes_after_restart(client: TestClient) -> None:assert response.json() == {}with client.websocket_connect(- f"/ws?session_id={SESSION_ID}", headers=token_header()+ f"/ws?message_format=host&session_id={SESSION_ID}",+ headers=token_header(),) as websocket:- assert websocket.receive_json()["op"] == "kernel-ready"+ assert receive_notification(websocket)["op"] == "kernel-ready"response = client.get("/api/sessions", headers=token_header())assert response.status_code == 200, response.textcurrent = response.json()[SESSION_ID]diff --git a/tests/_server/api/endpoints/test_home.py b/tests/_server/api/endpoints/test_home.pyindex 6c229b62fb..bffe57a27e 100644--- a/tests/_server/api/endpoints/test_home.py+++ b/tests/_server/api/endpoints/test_home.py@@ -2,21 +2,30 @@from __future__ import annotationsimport inspect+import jsonimport osimport sysimport tempfileimport textwrapfrom pathlib import Pathfrom typing import TYPE_CHECKING+from urllib.parse import urlencodeimport pytest+from marimo._core.protocol import ProjectMessagefrom marimo._server.models.home import MarimoFilefrom marimo._server.workspace import (DirectoryWorkspace,+ EmptyWorkspace,FixedFilesWorkspace,+ SingleFileWorkspace,)from marimo._session.model import SessionMode+from marimo._utils.marimo_path import MarimoPath+from tests._server.api.endpoints.test_sse import SSETestConnection+from tests._server.host.drive import socket_snapshot+from tests._server.host.test_editor_websocket import receive_notificationfrom tests._server.mocks import get_session_manager, token_header, with_sessionif TYPE_CHECKING:@@ -593,3 +602,103 @@ def test_running_notebooks_handles_files_outside_directory(finally:session_manager.workspace = original_workspacesession.app_file_manager.filename = original_filename++[email protected]("transport", ["ws", "sse"])[email protected]("source", ["tutorial", "single-file", "empty"])+def test_open_notebook_connects_and_reconnects_to_host(+ client: TestClient, tmp_path: Path, transport: str, source: str+) -> None:+ manager = get_session_manager(client)+ root = tmp_path / "workspace"+ root.mkdir()+ if source == "tutorial":+ manager.workspace = DirectoryWorkspace(+ str(root), include_markdown=False+ )+ else:+ path = str(tmp_path / "opened.py")+ Path(path).write_text("import marimo\napp = marimo.App()\n")+ if source == "empty":+ manager.workspace = EmptyWorkspace()+ else:+ original = root / "original.py"+ original.write_text("import marimo\napp = marimo.App()\n")+ manager.workspace = SingleFileWorkspace.from_path(+ MarimoPath(str(original))+ )+ with client:+ if source == "tutorial":+ response = client.post(+ "/api/home/tutorial/open",+ headers=HEADERS,+ json={"tutorialId": "intro"},+ )+ assert response.status_code == 200, response.text+ path = response.json()["path"]+ query = urlencode(+ {+ "session_id": SESSION_ID,+ "file": path,+ "access_token": "fake-token",+ "message_format": "host",+ }+ )+ notebook = None+ for notification in ("kernel-ready", "reconnected"):+ if transport == "ws":+ with client.websocket_connect(f"/ws?{query}") as socket:+ snapshot = socket_snapshot(socket)+ ready = receive_notification(socket, notification)+ else:++ async def read_sse():+ async with SSETestConnection(+ client.app, query+ ) as connection:+ snapshot = []+ while True:+ event = await connection.next_event()+ snapshot.append(+ {+ "event": event["event"],+ "data": json.loads(event["data"]),+ }+ )+ if event["event"] == "ready":+ break+ ready = json.loads(+ (await connection.next_notification())["data"]+ )["data"]+ return snapshot, ready++ assert client.portal is not None+ snapshot, ready = client.portal.call(read_sse)+ bridge = client.app.state.host_context.bridge+ record = bridge.index.notebook_for(path)+ assert record is not None+ if notebook is None:+ notebook = record+ assert record == notebook+ [project] = [+ e.event.data.project+ for e in bridge.host.events()+ if isinstance(e.event.data, ProjectMessage)+ and e.event.data.project.id == record.project_id+ ]+ assert (project.name, project.root, record.path) == (+ "Open notebooks",+ None,+ None,+ )+ assert snapshot[0]["data"]["notebook"]["id"] == record.id+ assert ready["op"] == notification+ if notification == "kernel-ready":+ assert ready["consumer_capabilities"]["edit"] is True+ if source == "tutorial":+ assert any(+ e["event"] == "cell" and e["data"]["cell"]["code"]+ for e in snapshot+ )+ assert client.portal is not None+ client.portal.call(bridge.index.refresh_async)diff --git a/tests/_server/api/endpoints/test_kiosk.py b/tests/_server/api/endpoints/test_kiosk.pyindex 650216c8bd..5b23fa84c5 100644--- a/tests/_server/api/endpoints/test_kiosk.py+++ b/tests/_server/api/endpoints/test_kiosk.py@@ -7,6 +7,7 @@ from tests._server.api.endpoints.ws_helpers import (HEADERS as _HEADERS,assert_kernel_ready_response,create_response,+ receive_notification,receive_until,)@@ -25,14 +26,14 @@ async def test_connect_kiosk_with_session(client: TestClient) -> None:with client.websocket_connect("/ws?session_id=123", headers=_HEADERS) as websocket:- editor_ready = websocket.receive_json()+ editor_ready = receive_notification(websocket)assert_kernel_ready_response(editor_ready)# Connect in kiosk modewith client.websocket_connect("/ws?session_id=456&kiosk=true", headers=_HEADERS) as other_websocket:- data = other_websocket.receive_json()+ data = receive_notification(other_websocket)assert_kernel_ready_response(data,create_response(@@ -49,7 +50,8 @@ async def test_connect_kiosk_with_session(client: TestClient) -> None:for _ in range(2):assert (- other_websocket.receive_json()["op"] == "environment-state"+ receive_notification(other_websocket)["op"]+ == "environment-state")# Send document transaction to reorder cells@@ -68,7 +70,7 @@ async def test_connect_kiosk_with_session(client: TestClient) -> None:assert response.status_code == 200, response.text# Assert kiosk session received the document transaction- data = other_websocket.receive_json()+ data = receive_notification(other_websocket)assert data["op"] == "notebook-document-transaction"# A full save replaces the canonical document. Viewers receive@@ -121,12 +123,12 @@ def test_second_edit_connection_joins_as_viewer(client: TestClient) -> None:with client.websocket_connect("/ws?session_id=ed1", headers=_HEADERS) as editor:- assert_kernel_ready_response(editor.receive_json())+ assert_kernel_ready_response(receive_notification(editor))with client.websocket_connect("/ws?session_id=vw1", headers=_HEADERS) as viewer:- data = viewer.receive_json()+ data = receive_notification(viewer)assert_kernel_ready_response(data,create_response(@@ -144,7 +146,7 @@ def test_second_edit_connection_joins_as_viewer(client: TestClient) -> None:def test_takeover_ping_pong_preserves_membership(client: TestClient) -> None:with client.websocket_connect("/ws?session_id=a", headers=_HEADERS) as ta:- assert_kernel_ready_response(ta.receive_json())+ assert_kernel_ready_response(receive_notification(ta))with client.websocket_connect("/ws?session_id=b", headers=_HEADERS) as tb:@@ -171,7 +173,7 @@ def test_takeover_ping_pong_preserves_membership(client: TestClient) -> None:def test_third_viewer_survives_takeover(client: TestClient) -> None:with client.websocket_connect("/ws?session_id=a", headers=_HEADERS) as ta:- assert_kernel_ready_response(ta.receive_json())+ assert_kernel_ready_response(receive_notification(ta))with client.websocket_connect("/ws?session_id=b", headers=_HEADERS) as tb:@@ -205,7 +207,7 @@ def test_third_viewer_survives_takeover(client: TestClient) -> None:def test_capabilities_changed_is_not_recorded(client: TestClient) -> None:with client.websocket_connect("/ws?session_id=a", headers=_HEADERS) as ta:- assert_kernel_ready_response(ta.receive_json())+ assert_kernel_ready_response(receive_notification(ta))with client.websocket_connect("/ws?session_id=b", headers=_HEADERS) as tb:@@ -228,13 +230,13 @@ def test_refresh_resumes_as_editor(client: TestClient) -> None:with client.websocket_connect("/ws?session_id=ed1", headers=_HEADERS) as editor:- assert_kernel_ready_response(editor.receive_json())+ assert_kernel_ready_response(receive_notification(editor))# editor socket closed on block exit -> session is orphanedwith client.websocket_connect("/ws?session_id=ed2", headers=_HEADERS) as refreshed:- assert refreshed.receive_json() == {+ assert receive_notification(refreshed) == {"op": "reconnected","data": {"op": "reconnected"},}diff --git a/tests/_server/api/endpoints/test_notification_filter.py b/tests/_server/api/endpoints/test_notification_filter.pynew file mode 100644index 0000000000..ecee71a9ca--- /dev/null+++ b/tests/_server/api/endpoints/test_notification_filter.py@@ -0,0 +1,24 @@+# Copyright 2026 Marimo. All rights reserved.+from marimo._messaging.notification import (+ CompletionResultNotification,+ FocusCellNotification,+)+from marimo._server.api.endpoints.ws.notification_filter import (+ should_filter_operation,+)+++def test_editor_filters_kiosk_only_and_keeps_completions() -> None:+ assert should_filter_operation(FocusCellNotification.name, is_kiosk=False)+ assert not should_filter_operation(+ CompletionResultNotification.name, is_kiosk=False+ )+++def test_viewer_keeps_kiosk_only_and_filters_completions() -> None:+ assert not should_filter_operation(+ FocusCellNotification.name, is_kiosk=True+ )+ assert should_filter_operation(+ CompletionResultNotification.name, is_kiosk=True+ )diff --git a/tests/_server/api/endpoints/test_resume_session.py b/tests/_server/api/endpoints/test_resume_session.pyindex 6cc8077180..cbc4985dc2 100644--- a/tests/_server/api/endpoints/test_resume_session.py+++ b/tests/_server/api/endpoints/test_resume_session.py@@ -23,7 +23,6 @@ from marimo._messaging.notification import (OperationSucceeded,)from marimo._messaging.serde import serialize_kernel_message-from marimo._server.api.endpoints.ws.ws_formatter import format_wire_messagefrom marimo._server.workspace import DirectoryWorkspacefrom marimo._session import Sessionfrom marimo._types.ids import SessionId@@ -32,6 +31,7 @@ from tests._server.api.endpoints.ws_helpers import (assert_kernel_ready_response,create_response,headers,+ receive_notification,)from tests._server.mocks import get_session_manager, workspace_scope@@ -51,7 +51,7 @@ def _create_ws_url(session_id: str) -> str:def test_refresh_session(client: TestClient) -> None:with client.websocket_connect(_create_ws_url("123")) as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)print(data)assert_kernel_ready_response(data, create_response({}))@@ -71,10 +71,10 @@ def test_refresh_session(client: TestClient) -> None:# We should resume the current sessionwith client.websocket_connect(_create_ws_url("456")) as websocket:# First message is the kernel reconnected- data = websocket.receive_json()+ data = receive_notification(websocket)assert data == {"op": "reconnected", "data": {"op": "reconnected"}}# Resume the session- data = websocket.receive_json()+ data = receive_notification(websocket)assert_kernel_ready_response(data,create_response(@@ -103,10 +103,10 @@ def test_refresh_session(client: TestClient) -> None:# We should not resume the current session with the new valueswith client.websocket_connect(_create_ws_url("789")) as websocket:# First message is the kernel reconnected- data = websocket.receive_json()+ data = receive_notification(websocket)assert data == {"op": "reconnected", "data": {"op": "reconnected"}}# Resume the session- data = websocket.receive_json()+ data = receive_notification(websocket)assert_kernel_ready_response(data,create_response(@@ -151,7 +151,7 @@ def test_refresh_resumes_directory_workspace_session(with client.websocket_connect("/ws?session_id=dir1&file=example.py&access_token=fake-token") as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert data["op"] == "kernel-ready"assert data["data"]["resumed"] is False@@ -159,9 +159,9 @@ def test_refresh_resumes_directory_workspace_session(with client.websocket_connect("/ws?session_id=dir2&file=example.py&access_token=fake-token") as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert data == {"op": "reconnected", "data": {"op": "reconnected"}}- data = websocket.receive_json()+ data = receive_notification(websocket)assert data["op"] == "kernel-ready"assert data["data"]["resumed"] is True@@ -177,7 +177,7 @@ def test_save_session(client: TestClient) -> None:.filename)with client.websocket_connect(_create_ws_url("123")) as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert_kernel_ready_response(data, create_response({}))# Send save requestclient.post(@@ -211,10 +211,10 @@ def test_save_session(client: TestClient) -> None:# We should resume the current sessionwith client.websocket_connect(_create_ws_url("456")) as websocket:# First message is the kernel reconnected- data = websocket.receive_json()+ data = receive_notification(websocket)assert data == {"op": "reconnected", "data": {"op": "reconnected"}}# Resume the session- data = websocket.receive_json()+ data = receive_notification(websocket)assert_kernel_ready_response(data,create_response(@@ -251,7 +251,7 @@ def test_save_session(client: TestClient) -> None:def test_save_config(client: TestClient) -> None:with client.websocket_connect(_create_ws_url("123")) as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert_kernel_ready_response(data, create_response({}))# Send save requestclient.post(@@ -277,7 +277,7 @@ def test_save_config(client: TestClient) -> None:def test_restart_session(client: TestClient) -> None:with client.websocket_connect(_create_ws_url("123")) as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert_kernel_ready_response(data, create_response({}))# Restart the session@@ -295,7 +295,7 @@ def test_restart_session(client: TestClient) -> None:# We start a new sessionwith client.websocket_connect(_create_ws_url("456")) as websocket:# First message is the kernel reconnected- data = websocket.receive_json()+ data = receive_notification(websocket)assert_kernel_ready_response(data,create_response({}),@@ -314,10 +314,10 @@ def test_resume_session_after_file_change(client: TestClient) -> None:# directly, so no watcher is needed.with client.websocket_connect(_create_ws_url("123")) as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert_kernel_ready_response(data, create_response({}))for op in ("environment-state", "environment-state"):- assert websocket.receive_json()["op"] == op+ assert receive_notification(websocket)["op"] == opsession = get_session(client, SessionId("123"))assert session@@ -337,14 +337,15 @@ def test_resume_session_after_file_change(client: TestClient) -> None:with open(filename, "w") as f:f.write(new_content)- # Directly trigger the file change handler (synchronous) instead- # of relying on the async file watcher, which is inherently racy.- result = session_manager._file_change_coordinator._handle_file_change_locked(- os.path.abspath(filename), session+ # Trigger the change on the server loop, without racing a watcher.+ result = websocket.portal.call(+ session_manager._file_change_coordinator._handle_file_change_locked,+ os.path.abspath(filename),+ session,)assert result.handled- data = websocket.receive_json()+ data = receive_notification(websocket)assert data["op"] == "notebook-document-transaction"tx = data["data"]["transaction"]# Transaction should contain the new cell and reorder.@@ -356,15 +357,15 @@ def test_resume_session_after_file_change(client: TestClient) -> None:# Resume session with new ID (simulates refresh)with client.websocket_connect(_create_ws_url("456")) as websocket:# First message is the kernel reconnected- data = websocket.receive_json()+ data = receive_notification(websocket)assert data == {"op": "reconnected", "data": {"op": "reconnected"}}# Check for KernelReady message- data = websocket.receive_json()+ data = receive_notification(websocket)assert parse_raw(data["data"], KernelReadyNotification)# Banner notification (session replay)- data = websocket.receive_json()+ data = receive_notification(websocket)assert data["op"] == "banner"@@ -394,9 +395,9 @@ def test_environment_restored_after_disconnect() -> None:with client:with client.websocket_connect(_create_ws_url("123")) as websocket:- assert_kernel_ready_response(websocket.receive_json())+ assert_kernel_ready_response(receive_notification(websocket))for source in ("kernel", "server"):- assert websocket.receive_json() == {+ assert receive_notification(websocket) == {"op": "environment-state","data": {"op": "environment-state",@@ -461,18 +462,16 @@ def test_environment_restored_after_disconnect(with client.websocket_connect(_create_ws_url(connection_id)) as websocket:- assert websocket.receive_json()["op"] == "reconnected"+ assert receive_notification(websocket)["op"] == "reconnected"if connection_id != "123":- assert websocket.receive_json()["op"] == "kernel-ready"- assert websocket.receive_json()["op"] == "banner"+ assert receive_notification(websocket)["op"] == "kernel-ready"+ assert receive_notification(websocket)["op"] == "banner"else:- assert websocket.receive_json()["op"] == "alert"- assert websocket.receive_json() == json.loads(- format_wire_message(- expected.name, serialize_kernel_message(expected)- )+ assert receive_notification(websocket)["op"] == "alert"+ assert receive_notification(websocket)["data"] == json.loads(+ serialize_kernel_message(expected))- assert websocket.receive_json()["data"] == {+ assert receive_notification(websocket)["data"] == {"op": "environment-state","source": "server","state": {"restart_required": False, "operations": []},diff --git a/tests/_server/api/endpoints/test_sse.py b/tests/_server/api/endpoints/test_sse.pyindex 7bef2f8de8..67a371c6c0 100644--- a/tests/_server/api/endpoints/test_sse.py+++ b/tests/_server/api/endpoints/test_sse.py@@ -20,13 +20,13 @@ from marimo._messaging.notification import (StartupProgressNotification,)from marimo._messaging.serde import serialize_kernel_message-from marimo._server.api.endpoints.ws.sse_handler import SSESessionHandlerfrom marimo._server.api.endpoints.ws.ws_connection_validator import (ConnectionParams,)from marimo._server.api.endpoints.ws.ws_session_connector import (ConnectionType,)+from marimo._server.host.session import SessionEventStreamfrom marimo._server.sse import format_close_event, format_sse_eventfrom marimo._session.managers.ipc import KernelStartupErrorfrom marimo._session.model import ConnectionState, SessionMode@@ -109,6 +109,21 @@ class SSETestConnection:"""The next SSE record: {"event": ..., "data": ...} or a comment."""return await asyncio.wait_for(self._events.get(), timeout)+ async def next_notification(self) -> dict[str, str]:+ """Skip host model events when asserting session lifecycle notifications."""+ while True:+ record = await self.next_event()+ if record["event"] in ("close", "comment", "message"):+ return record+ if record["event"] == "marimo":+ notification = json.loads(record["data"])["marimo"]+ return {+ "event": "message",+ "data": json.dumps(+ {"op": notification["op"], "data": notification}+ ),+ }+def has_pending_events(self) -> bool:return not self._events.empty()@@ -134,18 +149,25 @@ class SSETestConnection:def _parse_record(record: str) -> dict[str, str]:event = "message"+ event_id = Nonedata_lines: list[str] = []comments: list[str] = []for line in record.split("\n"):if line.startswith(":"):comments.append(line[1:].strip())+ elif line.startswith("id:"):+ event_id = line[len("id:") :].strip()elif line.startswith("event:"):event = line[len("event:") :].strip()elif line.startswith("data:"):data_lines.append(line[len("data:") :].removeprefix(" "))if comments and not data_lines:return {"event": "comment", "data": "\n".join(comments)}- return {"event": event, "data": "\n".join(data_lines)}+ return {+ "event": event,+ "data": "\n".join(data_lines),+ **({"id": event_id} if event_id is not None else {}),+ }def _connect(@@ -159,13 +181,14 @@ def _connect(async def _expect_close(connection: SSETestConnection, code: int, reason: str) -> None:- event = await connection.next_event()+ event = await connection.next_notification()assert event["event"] == "close"assert json.loads(event["data"]) == {"code": code, "reason": reason}-async def test_sse_kernel_ready(client: TestClient) -> None:- async with _connect(client) as connection:[email protected]("format_query", ["", "&message_format=session"])+async def test_sse_kernel_ready(client: TestClient, format_query: str) -> None:+ async with _connect(client, SSE_QUERY + format_query) as connection:event = await connection.next_event()assert connection.status == 200assert connection.headers["content-type"].startswith(@@ -196,7 +219,7 @@ async def test_sse_authenticates_with_bearer_header("session_id=123",headers={"Authorization": "Bearer fake-token"},) as connection:- event = await connection.next_event()+ event = await connection.next_notification()assert json.loads(event["data"])["op"] == "kernel-ready"@@ -258,7 +281,7 @@ async def test_sse_allows_unauthenticated_when_auth_disabled(# Trusted environments (e.g. --no-token) disable marimo's own authclient.app.state.enable_auth = Falseasync with _connect(client, "session_id=123") as connection:- event = await connection.next_event()+ event = await connection.next_notification()assert json.loads(event["data"])["op"] == "kernel-ready"@@ -276,7 +299,7 @@ async def test_sse_hides_code_when_include_code_false(session_manager.mode = SessionMode.RUNsession_manager.include_code = Falseasync with _connect(client) as connection:- event = await connection.next_event()+ event = await connection.next_notification()message = json.loads(event["data"])assert message["op"] == "kernel-ready"assert message["data"]["codes"] == [""] # hidden@@ -286,12 +309,12 @@ async def test_sse_hides_code_when_include_code_false(async def test_sse_kernel_startup_error(client: TestClient) -> None:with patch.object(- SSESessionHandler,+ SessionEventStream,"_connect_session",side_effect=KernelStartupError("boom"),):async with _connect(client) as connection:- event = await connection.next_event()+ event = await connection.next_notification()message = json.loads(event["data"])assert message["op"] == "kernel-startup-error"assert message["data"]["error"] == "boom"@@ -340,7 +363,7 @@ async def test_sandbox_progress_during_preparation(manager.ttl_seconds = 0async with _connect(client) as connection:- event = await connection.next_event()+ event = await connection.next_notification()assert json.loads(event["data"]) == {"op": "startup-progress","data": {@@ -350,7 +373,7 @@ async def test_sandbox_progress_during_preparation("log_mode": "replace",},}- running = json.loads((await connection.next_event())["data"])+ running = json.loads((await connection.next_notification())["data"])assert running["op"] == "environment-operation"assert running["data"]["action"] == "prepare"assert running["data"]["status"] == {"kind": "running"}@@ -361,13 +384,15 @@ async def test_sandbox_progress_during_preparation(await asyncio.wait_for(cleaned_up.wait(), timeout=5)else:release.set()- completed = json.loads((await connection.next_event())["data"])+ completed = json.loads(+ (await connection.next_notification())["data"]+ )assert (completed["data"]["operation_id"]== running["data"]["operation_id"])assert completed["data"]["status"] == {"kind": "succeeded"}- event = await connection.next_event()+ event = await connection.next_notification()assert json.loads(event["data"]) == {"op": "startup-progress","data": {@@ -377,7 +402,7 @@ async def test_sandbox_progress_during_preparation("log_mode": "replace",},}- event = await connection.next_event()+ event = await connection.next_notification()message = json.loads(event["data"])if outcome == "ready":assert_kernel_ready_response(message)@@ -401,13 +426,13 @@ async def test_sse_kiosk_without_session(client: TestClient) -> None:async def test_sse_disconnect_and_reconnect(client: TestClient) -> None:async with _connect(client) as connection:- event = await connection.next_event()+ event = await connection.next_notification()assert json.loads(event["data"])["op"] == "kernel-ready"# Reconnect with the same session idasync with _connect(client) as connection:- event = await connection.next_event()+ event = await connection.next_notification()assert json.loads(event["data"])["op"] == "reconnected"- event = await connection.next_event()+ event = await connection.next_notification()assert json.loads(event["data"])["op"] == "alert"@@ -415,10 +440,10 @@ async def test_sse_second_connection_joins_as_viewer(client: TestClient,) -> None:async with _connect(client) as connection:- event = await connection.next_event()+ event = await connection.next_notification()assert json.loads(event["data"])["op"] == "kernel-ready"async with _connect(client, OTHER_SSE_QUERY) as viewer:- event = await viewer.next_event()+ event = await viewer.next_notification()message = json.loads(event["data"])assert message["op"] == "kernel-ready"assert_kernel_ready_response(@@ -427,17 +452,20 @@ async def test_sse_second_connection_joins_as_viewer(async def test_sse_heartbeat(client: TestClient) -> None:- with_heartbeat = partial(SSESessionHandler, heartbeat_seconds=0.01)+ with_heartbeat = partial(SessionEventStream, heartbeat_seconds=0.01)with patch(- "marimo._server.api.endpoints.ws_endpoint.SSESessionHandler",+ "marimo._server.api.endpoints.ws_endpoint.SessionEventStream",with_heartbeat,):async with _connect(client) as connection:- event = await connection.next_event()+ while True:+ event = await connection.next_notification()+ if event["event"] != "comment":+ breakassert json.loads(event["data"])["op"] == "kernel-ready"# Drain until the first heartbeat comment arrivesfor _ in range(20):- event = await connection.next_event()+ event = await connection.next_notification()if event["event"] == "comment":breakassert event == {"event": "comment", "data": "keep-alive"}@@ -448,7 +476,7 @@ async def test_sse_heartbeat(client: TestClient) -> None:def _make_handler(request: MagicMock, *, mode: SessionMode = SessionMode.RUN-) -> SSESessionHandler:+) -> SessionEventStream:params = ConnectionParams(session_id=SessionId("s1"),file_key="test.py",@@ -456,11 +484,14 @@ def _make_handler(auto_instantiate=False,rtc_enabled=False,)- handler = SSESessionHandler(- request=request,- manager=MagicMock(),+ handler = SessionEventStream(+ connection=request,+ notebook=None,+ bridge=MagicMock(),+ types=None,+ cursor=None,+ manager=MagicMock(mode=mode),params=params,- mode=mode,doc_manager=MagicMock(),heartbeat_seconds=60,)@@ -497,15 +528,15 @@ async def test_stream_sends_messages_and_close_event() -> None:request._receive = _never_receive()handler = _make_handler(request)- stream = handler.stream()+ stream = handler.sse()handler.notify(serialize_kernel_message(AlertNotification(title="hello", description="world")))first = await asyncio.wait_for(stream.__anext__(), timeout=10)- assert first.startswith("data: ")- assert json.loads(first[len("data: ") :].strip())["op"] == "alert"+ assert first.startswith("event: marimo\n")+ assert json.loads(_parse_record(first)["data"])["marimo"]["op"] == "alert"# Detaching from the session requests a SHUTDOWN closehandler.on_detach()@@ -522,7 +553,7 @@ async def test_stream_does_not_connect_until_iterated() -> None:request._receive = _never_receive()handler = _make_handler(request)- stream = handler.stream()+ stream = handler.sse()await asyncio.sleep(0)handler._connect_session.assert_not_called()@@ -543,7 +574,7 @@ async def test_disconnect_during_startup_progress_detaches_session() -> None:))- stream = handler.stream()+ stream = handler.sse()assert "startup-progress" in await anext(stream)await asyncio.sleep(0) # Complete attachment while the yield is suspended.await stream.aclose()@@ -571,10 +602,16 @@ async def test_stream_flushes_pending_messages_before_close() -> None:)handler.on_detach()- events = [event async for event in handler.stream()]+ events = [event async for event in handler.sse()]assert len(events) == 3- assert json.loads(events[0][len("data: ") :])["data"]["title"] == "one"- assert json.loads(events[1][len("data: ") :])["data"]["title"] == "two"+ assert (+ json.loads(_parse_record(events[0])["data"])["marimo"]["title"]+ == "one"+ )+ assert (+ json.loads(_parse_record(events[1])["data"])["marimo"]["title"]+ == "two"+ )assert events[2] == format_close_event(1000, "MARIMO_SHUTDOWN")@@ -589,7 +626,7 @@ async def test_stream_ends_on_client_disconnect() -> None:handler.manager.get_session.return_value = Nonehandler.manager.ttl_seconds = None- events = [event async for event in handler.stream()]+ events = [event async for event in handler.sse()]assert events == []assert handler.connection_state() == ConnectionState.CLOSED@@ -618,12 +655,12 @@ async def test_check_status_update_runs_off_the_event_loop(# Returns immediately, while the check is still running on a threadhandler._check_status_update()assert await asyncio.wait_for(asyncio.to_thread(started.wait, 10), 20)- assert handler.message_queue.empty()+ assert handler._events.empty()# Once the check completes, the alert is delivered onto the queuerelease.set()- message = await asyncio.wait_for(handler.message_queue.get(), timeout=10)- assert b"Update available" in bytes(message)+ message = await asyncio.wait_for(handler._events.get(), timeout=10)+ assert "Update available" in message.event.data.marimo.titleasync def test_stream_heartbeat_without_messages() -> None:@@ -632,7 +669,7 @@ async def test_stream_heartbeat_without_messages() -> None:handler = _make_handler(request)handler.heartbeat_seconds = 0.01- stream = handler.stream()+ stream = handler.sse()first = await asyncio.wait_for(stream.__anext__(), timeout=10)assert first == ": keep-alive\n\n"handler._request_close(1000, "MARIMO_SHUTDOWN")@@ -657,3 +694,64 @@ def test_format_close_event() -> None:assert format_close_event(1000, "MARIMO_SHUTDOWN") == ('event: close\ndata: {"code": 1000, "reason": "MARIMO_SHUTDOWN"}\n\n')++[email protected]("mode", [SessionMode.EDIT, SessionMode.RUN])+async def test_sse_host_snapshot_and_cursor_replay(+ client: TestClient, mode: SessionMode+) -> None:+ manager = get_session_manager(client)+ manager.mode = mode+ manager.include_code = False+ query = (+ SSE_QUERY + "&message_format=host&types=notebook,cell,custom,marimo"+ )+ async with _connect(client, query) as connection:+ snapshot = []+ while True:+ record = await connection.next_event()+ snapshot.append(record)+ if record["event"] == "ready":+ cursor = record["id"]+ break+ cells = [+ json.loads(r["data"])["cell"]+ for r in snapshot+ if r["event"] == "cell"+ ]+ assert cells+ assert cells[0]["code"] == (+ None if mode == SessionMode.RUN else "import marimo as mo"+ )+ # Finish the session handshake before disconnecting.+ await connection.next_notification()+ context = client.app.state.host_context+ session = manager.get_session(SessionId("123"))+ assert session is not None+ notebook = context.bridge.notebook_for_session(session)+ assert notebook is not None+ notebook.emit("test.missed", {"value": 1})+ async with _connect(+ client, query, {"Last-Event-ID": cursor}+ ) as connection:+ first = await connection.next_event()+ assert first["event"] == "custom"+ assert json.loads(first["data"])["custom"]["data"] == {"value": 1}+ assert (await connection.next_event())["event"] == "ready"+ async with _connect(client, query + "&cursor=stale") as connection:+ assert (await connection.next_event())["event"] == "reset"+ assert (await connection.next_event())["event"] == "notebook"+++ "options",+ ["cursor=", "types=invalid", "run_id=unknown", "message_format=invalid"],+)+async def test_sse_rejects_invalid_subscription_before_startup(+ client: TestClient, options: str+) -> None:+ async with _connect(client, SSE_QUERY + "&" + options) as connection:+ record = await connection.next_event()+ assert record["event"] == "close"+ assert json.loads(record["data"])["code"] == 1008+ assert not get_session_manager(client).sessionsdiff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.pyindex 4e72a50af9..b7df000101 100644--- a/tests/_server/api/endpoints/test_ws.py+++ b/tests/_server/api/endpoints/test_ws.py@@ -8,7 +8,7 @@ from typing import TYPE_CHECKING, Anyfrom unittest.mock import AsyncMock, MagicMock, patchimport pytest-from starlette.websockets import WebSocketDisconnect, WebSocketState+from starlette.websockets import WebSocket, WebSocketDisconnectfrom marimo._config.config import ExperimentalConfigfrom marimo._config.manager import MarimoConfigManager@@ -23,8 +23,8 @@ from marimo._server.api.endpoints.ws.ws_connection_validator import (ConnectionParams,)from marimo._server.api.endpoints.ws.ws_session_connector import ConnectionType-from marimo._server.api.endpoints.ws_endpoint import WebSocketHandlerfrom marimo._server.codes import WebSocketCodes+from marimo._server.host.session import SessionEventStreamfrom marimo._server.session_manager import SessionManagerfrom marimo._session.model import ConnectionState, SessionModefrom marimo._types.ids import SessionId@@ -35,6 +35,7 @@ from tests._server.api.endpoints.ws_helpers import (assert_parse_ready_response,create_response,headers,+ receive_notification,receive_until,)from tests._server.conftest import get_kernel_tasks, get_user_config_manager@@ -54,47 +55,19 @@ WS_URL = _create_ws_url("123")OTHER_WS_URL = _create_ws_url("456")-def test_ws(client: TestClient) -> None:- with client.websocket_connect(WS_URL) as websocket:[email protected]("format_query", ["", "&message_format=session"])+def test_ws(client: TestClient, format_query: str) -> None:+ with client.websocket_connect(WS_URL + format_query) as websocket:+ # Legacy clients must see their notification first, with no host frames.data = websocket.receive_json()assert_kernel_ready_response(data)[email protected]("client_state", list(WebSocketState))-async def test_safe_close_skips_a_client_that_already_disconnected(- client_state: WebSocketState,-) -> None:- websocket = MagicMock()- websocket.close = AsyncMock()- websocket.client_state = client_state- handler = WebSocketHandler(- websocket=websocket,- manager=MagicMock(),- params=ConnectionParams(- session_id=SessionId("s1"),- file_key="test.py",- kiosk=False,- auto_instantiate=False,- rtc_enabled=False,- ),- mode=SessionMode.RUN,- )-- await handler._safe_close(WebSocketCodes.NORMAL_CLOSE, "")-- if client_state is WebSocketState.DISCONNECTED:- # Closing again would make uvicorn raise- # "Unexpected ASGI message 'websocket.close'".- websocket.close.assert_not_awaited()- else:- websocket.close.assert_awaited_once()--@pytest.mark.parametrize("failure", ["disconnect", "cancel"])async def test_failed_startup_progress_delivery_detaches_session(failure: str,) -> None:- websocket = MagicMock()+ websocket = MagicMock(spec=WebSocket)websocket.accept = AsyncMock()websocket.close = AsyncMock()sending = asyncio.Event()@@ -107,14 +80,24 @@ async def test_failed_startup_progress_delivery_detaches_session(await asyncio.Event().wait()websocket.send_text = send- manager = MagicMock()++ async def receive() -> None:+ await asyncio.Event().wait()++ websocket.receive = receive+ manager = MagicMock(mode=SessionMode.RUN)session = manager.get_session.return_valuesession.ttl_seconds = 120session.disconnect_consumer.side_effect = lambda consumer: (consumer.on_detach())- handler = WebSocketHandler(- websocket=websocket,+ handler = SessionEventStream(+ connection=websocket,+ notebook=None,+ bridge=MagicMock(),+ doc_manager=MagicMock(),+ types=None,+ cursor=None,manager=manager,params=ConnectionParams(session_id=SessionId("s1"),@@ -123,7 +106,6 @@ async def test_failed_startup_progress_delivery_detaches_session(auto_instantiate=False,rtc_enabled=False,),- mode=SessionMode.RUN,)async def connect(_connection: Any) -> tuple[Any, ConnectionType]:@@ -145,7 +127,10 @@ async def test_failed_startup_progress_delivery_detaches_session(await asyncio.wait_for(sending.wait(), timeout=5)if failure == "cancel":task.cancel()- await asyncio.wait_for(task, timeout=5)+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(task, timeout=5)+ else:+ await asyncio.wait_for(task, timeout=5)session.disconnect_consumer.assert_called_once_with(handler)assert handler.connection_state() == ConnectionState.CLOSED@@ -161,35 +146,35 @@ def test_without_session(client: TestClient) -> None:def test_disconnect_and_reconnect(client: TestClient) -> None:with client.websocket_connect(WS_URL) as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert_kernel_ready_response(data)# Connect by the same session idwith client.websocket_connect(WS_URL) as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert data == {"op": "reconnected", "data": {"op": "reconnected"}}- data = websocket.receive_json()+ data = receive_notification(websocket)assert data["op"] == "alert"def test_disconnect_then_reconnect_then_refresh(client: TestClient) -> None:manager = get_session_manager(client)with client.websocket_connect(WS_URL) as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert_kernel_ready_response(data)stable_id = manager.sessions[SessionId("123")].stable_idwebsocket.close()# Connect by the same session idwith client.websocket_connect(WS_URL) as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert data == {"op": "reconnected", "data": {"op": "reconnected"}}- data = websocket.receive_json()+ data = receive_notification(websocket)assert data["op"] == "alert"assert manager.sessions[SessionId("123")].stable_id == stable_id# New connection with a new browser ID (simulates refresh)with client.websocket_connect(OTHER_WS_URL) as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert data == {"op": "reconnected", "data": {"op": "reconnected"}}- data = websocket.receive_json()+ data = receive_notification(websocket)assert_kernel_ready_response(data, create_response({"resumed": True}))assert manager.sessions[SessionId("456")].stable_id == stable_id@@ -204,7 +189,7 @@ def test_completed_startup_is_restored_on_reconnect_and_refresh(log_mode="append",)with client.websocket_connect(WS_URL) as websocket:- assert_kernel_ready_response(websocket.receive_json())+ assert_kernel_ready_response(receive_notification(websocket))view = manager.sessions[SessionId("123")].session_viewview.add_notification(EnvironmentOperationNotification(@@ -222,8 +207,8 @@ def test_completed_startup_is_restored_on_reconnect_and_refresh(for url in (WS_URL, OTHER_WS_URL):with client.websocket_connect(url) as websocket:- assert websocket.receive_json()["op"] == "reconnected"- message = websocket.receive_json()+ assert receive_notification(websocket)["op"] == "reconnected"+ message = receive_notification(websocket)if url == OTHER_WS_URL:assert_kernel_ready_response(message, create_response({"resumed": True})@@ -252,11 +237,11 @@ def test_allows_multiple_connections_with_other_sessions() -> None:with rtc_enabled(get_user_config_manager(client)):with client.websocket_connect(WS_URL) as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert_kernel_ready_response(data)# Should allow second connectionwith client.websocket_connect(OTHER_WS_URL) as other_websocket:- data = other_websocket.receive_json()+ data = receive_notification(other_websocket)assert_kernel_ready_response(data, create_response({"resumed": True}))@@ -266,12 +251,12 @@ def test_second_connection_with_other_session_joins_as_viewer(client: TestClient,) -> None:with client.websocket_connect(WS_URL) as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert_kernel_ready_response(data)# A second EDIT connection is not refused; auto-routes to a viewer.with client.websocket_connect(OTHER_WS_URL) as other_websocket:assert_kernel_ready_response(- other_websocket.receive_json(),+ receive_notification(other_websocket),create_response({"kiosk": True, "resumed": True}),)@@ -285,11 +270,11 @@ def test_allows_multiple_connections_with_same_file(ws_1 = WS_URLws_2 = _create_ws_url("456")with client.websocket_connect(ws_1) as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert_parse_ready_response(data)# Should allow second connectionwith client.websocket_connect(ws_2) as other_websocket:- data = other_websocket.receive_json()+ data = receive_notification(other_websocket)assert_parse_ready_response(data)@@ -300,12 +285,12 @@ def test_second_connection_with_same_file_joins_as_viewer(ws_1 = f"{WS_URL}&file={temp_marimo_file}"ws_2 = f"{OTHER_WS_URL}&file={temp_marimo_file}"with client.websocket_connect(ws_1) as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert_parse_ready_response(data)# A second EDIT connection is not refused; auto-routes to a viewer.with client.websocket_connect(ws_2) as other_websocket:viewer = parse_raw(- other_websocket.receive_json()["data"],+ receive_notification(other_websocket)["data"],KernelReadyNotification,)assert viewer.kiosk is True@@ -322,7 +307,7 @@ def test_file_watcher_calls_reload(client: TestClient) -> None:)session_manager.watch = Truewith client.websocket_connect(WS_URL) as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert_kernel_ready_response(data)filename = session_manager.workspace.get_unique_file_key()assert filename@@ -345,7 +330,7 @@ async def test_query_params(client: TestClient) -> None:with client.websocket_connect(f"{WS_URL}&foo=1&bar=2&bar=3&baz=4") as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert_kernel_ready_response(data)session = get_session_manager(client).get_session("123")@@ -362,7 +347,7 @@ async def test_connect_kiosk_without_session(client: TestClient) -> None:with client.websocket_connect("/ws?session_id=123&kiosk=true&access_token=fake-token") as websocket:- websocket.receive_json()+ receive_notification(websocket)raise AssertionError()assert exc_info.value.code == WebSocketCodes.NORMAL_CLOSEassert exc_info.value.reason == "MARIMO_NO_SESSION"@@ -371,14 +356,14 @@ async def test_connect_kiosk_without_session(client: TestClient) -> None:async def test_connect_kiosk_with_session(client: TestClient) -> None:# Create the first sessionwith client.websocket_connect(WS_URL) as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert_kernel_ready_response(data)# Connect by the same session id in kiosk modewith client.websocket_connect(f"{WS_URL}&kiosk=true") as other_websocket:- data = other_websocket.receive_json()+ data = receive_notification(other_websocket)assert_kernel_ready_response(data, create_response({"kiosk": True, "resumed": True}))@@ -391,7 +376,7 @@ async def test_cannot_connect_kiosk_with_run_session(session_manager = get_session_manager(client)session_manager.mode = SessionMode.RUNwith client.websocket_connect(WS_URL) as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert_kernel_ready_response(data)# Connect by the same session id in kiosk mode@@ -399,7 +384,7 @@ async def test_cannot_connect_kiosk_with_run_session(with client.websocket_connect(f"{WS_URL}&kiosk=true") as other_websocket:- data = other_websocket.receive_json()+ data = receive_notification(other_websocket)raise AssertionError()assert exc_info.value.code == WebSocketCodes.FORBIDDENassert exc_info.value.reason == "MARIMO_KIOSK_NOT_ALLOWED"@@ -423,7 +408,7 @@ async def test_kernel_ready_sends_names_but_not_code_when_include_code_false(session_manager.mode = SessionMode.RUNsession_manager.include_code = Falsewith client.websocket_connect(WS_URL) as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert_kernel_ready_response(data,create_response(@@ -448,13 +433,13 @@ async def test_connects_to_existing_session_with_same_file(with rtc_enabled(get_user_config_manager(client)):with client.websocket_connect(ws_1) as websocket1:- data = websocket1.receive_json()+ data = receive_notification(websocket1)assert_parse_ready_response(data)for op in ("environment-state","environment-state",):- assert websocket1.receive_json()["op"] == op+ assert receive_notification(websocket1)["op"] == op# Instantiate the sessionclient.post(@@ -476,22 +461,21 @@ async def test_connects_to_existing_session_with_same_file(# which happens before the consumer joins the room. The ready# message is sent after the join, so it is the earliest point at# which the room membership is observable.- data2 = websocket2.receive_json()+ data2 = receive_notification(websocket2)assert_parse_ready_response(data2)for op in ("environment-state","environment-state",):- assert websocket2.receive_json()["op"] == op+ assert receive_notification(websocket2)["op"] == opassert data2["data"]["resumed"] is True# Check in the same roomsession_manager = get_session_manager(client)assert len(session_manager.sessions) == 1- assert (- session_manager.sessions[SessionId("123")].room.size == 2- )+ room = session_manager.sessions[SessionId("123")].room+ assert {"123", "456"} <= set(room.consumers)messages2 = flush_messages(websocket2, at_least=3)# This can/may change if implementation changes, but this is a snapshot to@@ -508,7 +492,7 @@ def flush_messages(# So we just keep calling receive_json until we get at least the number of messages we expectmessages: list[dict[str, Any]] = []while len(messages) < at_least:- messages.append(websocket.receive_json())+ messages.append(receive_notification(websocket))return messages@@ -563,7 +547,7 @@ def test_ws_with_valid_authentication(client: TestClient) -> None:"""Test that WebSocket connections work with valid authentication."""# Connect with proper authentication headerswith client.websocket_connect(WS_URL, headers=HEADERS) as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert_kernel_ready_response(data)# Clean up@@ -578,7 +562,7 @@ async def test_session_resumption(client: TestClient) -> None:"""Test that session resumption restores state and replays operations."""# Create a session and instantiate itwith client.websocket_connect(WS_URL) as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert_kernel_ready_response(data)# Instantiate to generate some operations@@ -596,10 +580,10 @@ async def test_session_resumption(client: TestClient) -> None:# Resume with new session ID (simulates browser refresh)with client.websocket_connect(OTHER_WS_URL) as websocket:# Should receive reconnected + resumed state- reconnect_msg = websocket.receive_json()+ reconnect_msg = receive_notification(websocket)assert reconnect_msg["op"] == "reconnected"- kernel_ready_msg = websocket.receive_json()+ kernel_ready_msg = receive_notification(websocket)assert kernel_ready_msg["op"] == "kernel-ready"# Verify resumed flag is True@@ -622,7 +606,7 @@ async def test_reconnection_cancels_close_handle(client: TestClient) -> None:session_manager.mode = SessionMode.RUNwith client.websocket_connect(WS_URL) as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert_kernel_ready_response(data)# Close the websocket@@ -633,7 +617,7 @@ async def test_reconnection_cancels_close_handle(client: TestClient) -> None:# Reconnect immediately (before TTL expires)with client.websocket_connect(WS_URL) as new_websocket:- data = new_websocket.receive_json()+ data = receive_notification(new_websocket)# Should get reconnected messageassert data["op"] == "reconnected"@@ -698,14 +682,14 @@ async def test_ttl_close_does_not_kill_session_owned_by_new_consumer(ws_a.__enter__()a_disconnected = Falsetry:- assert_kernel_ready_response(ws_a.receive_json())+ assert_kernel_ready_response(receive_notification(ws_a))assert session_manager.get_session("123") is not None# Step 2: Consumer A disconnects under the patch so its TTL close is# captured instead of scheduled. The patch stays active until the# server loop has processed the disconnect.with patch(- "marimo._server.api.endpoints.ws_endpoint.asyncio.get_running_loop",+ "marimo._server.api.endpoints.ws.session_handler.asyncio.get_running_loop",lambda: _CaptureCloseLoop(real_get_running_loop()),):a_disconnected = True@@ -718,7 +702,7 @@ async def test_ttl_close_does_not_kill_session_owned_by_new_consumer(# Step 3: Consumer B takes over the same sessionwith client.websocket_connect(WS_URL) as ws_b:- data = ws_b.receive_json()+ data = receive_notification(ws_b)assert data["op"] == "reconnected", (f"Expected reconnected, got {data.get('op')}")@@ -763,7 +747,7 @@ def test_session_ttl_expiration(session_manager.ttl_seconds = manager_ttlwith client.websocket_connect(WS_URL) as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert_kernel_ready_response(data)session = session_manager.get_session("123")@@ -808,7 +792,7 @@ async def test_edit_mode_without_session_ttl_no_delayed_cleanup(assert session_manager.ttl_seconds is Nonewith client.websocket_connect(WS_URL) as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert_kernel_ready_response(data)session = session_manager.get_session("123")@@ -866,7 +850,7 @@ async def test_rtc_config_with_loro_unavailable(client: TestClient) -> None:):# Connection should succeed without errorswith client.websocket_connect(WS_URL) as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert_kernel_ready_response(data)@@ -880,16 +864,16 @@ async def test_rapid_reconnection_cancels_ttl_cleanup() -> None:"""Test that rapid reconnection cancels the TTL cleanup timer."""with client.websocket_connect(WS_URL) as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert_kernel_ready_response(data)# Disconnect and immediately reconnect (before TTL expires)await asyncio.sleep(0.1)with client.websocket_connect(WS_URL) as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert data["op"] == "reconnected"- data = websocket.receive_json()+ data = receive_notification(websocket)assert data["op"] == "alert"@@ -897,7 +881,7 @@ async def test_multiple_rapid_reconnections(client: TestClient) -> None:"""Test multiple rapid connect/disconnect cycles don't break session."""for i in range(5):with client.websocket_connect(WS_URL) as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)if i == 0:assert_kernel_ready_response(data)else:@@ -907,7 +891,7 @@ async def test_multiple_rapid_reconnections(client: TestClient) -> None:async def test_websocket_message_queue_delivery(client: TestClient) -> None:"""Test that kernel messages are queued and delivered."""with client.websocket_connect(WS_URL) as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)assert_kernel_ready_response(data)client.post(@@ -920,15 +904,19 @@ async def test_websocket_message_queue_delivery(client: TestClient) -> None:assert len(messages) >= 1[email protected]("app_host", [False, True])def test_disconnect_expires_pending_startup(- client: TestClient, monkeypatch: pytest.MonkeyPatch+ client: TestClient, monkeypatch: pytest.MonkeyPatch, app_host: bool) -> None:import asyncioimport threadingfrom marimo._session.session import SessionImpl- get_session_manager(client).ttl_seconds = 0+ manager = get_session_manager(client)+ manager.ttl_seconds = 0+ if app_host:+ manager.mode = SessionMode.RUNstarted = threading.Event()cleaned_up = threading.Event()@@ -941,7 +929,8 @@ def test_disconnect_expires_pending_startup(cleaned_up.set()monkeypatch.setattr(SessionImpl, "create", create)- with client.websocket_connect(WS_URL) as websocket:+ url = WS_URL+ with client.websocket_connect(url) as websocket:assert started.wait(timeout=5)websocket.close()# Stay in the client context: its teardown cancels the server task,@@ -969,7 +958,7 @@ def test_sandbox_progress_before_preparation_failure(get_session_manager(client).sandbox = Truewith client.websocket_connect(WS_URL) as websocket:- assert websocket.receive_json() == {+ assert receive_notification(websocket) == {"op": "startup-progress","data": {"op": "startup-progress",@@ -978,23 +967,23 @@ def test_sandbox_progress_before_preparation_failure("log_mode": "replace",},}- running = websocket.receive_json()+ running = receive_notification(websocket)assert running["op"] == "environment-operation"assert running["data"]["action"] == "prepare"assert running["data"]["status"] == {"kind": "running"}assert not get_session_manager(client).sessionswebsocket.portal.call(release.set)- failed = websocket.receive_json()+ failed = receive_notification(websocket)assert failed["op"] == "environment-operation"assert (failed["data"]["operation_id"] == running["data"]["operation_id"])assert failed["data"]["status"]["kind"] == "failed"- error = websocket.receive_json()+ error = receive_notification(websocket)assert error["op"] == "kernel-startup-error"assert "Could not resolve dependencies" in error["data"]["error"]with pytest.raises(WebSocketDisconnect) as closed:- websocket.receive_json()+ receive_notification(websocket)assert closed.value.reason == "MARIMO_KERNEL_STARTUP_ERROR"@@ -1032,16 +1021,16 @@ def test_refresh_observes_existing_sandbox_preparation(# Keep one server loop alive across both browser connections.with client:with client.websocket_connect(WS_URL) as first:- assert first.receive_json() == expected- running = first.receive_json()- output = first.receive_json()+ assert receive_notification(first) == expected+ running = receive_notification(first)+ output = receive_notification(first)assert output["data"]["logs"] == {"environment": "Resolving dependencies\n"}first.close()with client.websocket_connect(replacement_url) as refreshed:- assert refreshed.receive_json() == expected- snapshot = refreshed.receive_json()+ assert receive_notification(refreshed) == expected+ snapshot = receive_notification(refreshed)assert snapshot == {"op": "environment-state","data": {@@ -1066,17 +1055,20 @@ def test_refresh_observes_existing_sandbox_preparation(},},}- assert refreshed.receive_json()["data"]["source"] == "server"+ assert (+ receive_notification(refreshed)["data"]["source"]+ == "server"+ )assert launches == 1assert not manager.sessionsrefreshed.portal.call(release.set)- failed = refreshed.receive_json()+ failed = receive_notification(refreshed)assert failed["data"]["status"]["kind"] == "failed"- error = refreshed.receive_json()+ error = receive_notification(refreshed)assert error["op"] == "kernel-startup-error"assert ("Could not resolve dependencies" in error["data"]["error"])with pytest.raises(WebSocketDisconnect) as closed:- refreshed.receive_json()+ receive_notification(refreshed)assert closed.value.reason == "MARIMO_KERNEL_STARTUP_ERROR"diff --git a/tests/_server/api/endpoints/test_ws_message_loop.py b/tests/_server/api/endpoints/test_ws_message_loop.pydeleted file mode 100644index 928dbe4bf5..0000000000--- a/tests/_server/api/endpoints/test_ws_message_loop.py+++ /dev/null@@ -1,46 +0,0 @@-# Copyright 2026 Marimo. All rights reserved.-from __future__ import annotations--import json--from marimo._messaging.notification import (- AlertNotification,- CompletionResultNotification,- FocusCellNotification,-)-from marimo._messaging.serde import serialize_kernel_message-from marimo._server.api.endpoints.ws.ws_message_loop import (- prepare_wire_message,-)-from marimo._types.ids import CellId_t, RequestId--FOCUS_CELL = serialize_kernel_message(- FocusCellNotification(cell_id=CellId_t("Hbol"))-)-COMPLETION_RESULT = serialize_kernel_message(- CompletionResultNotification(- completion_id=RequestId("1"), prefix_length=0, options=[]- )-)-ALERT = serialize_kernel_message(- AlertNotification(title="title", description="description")-)---def test_editor_filters_kiosk_only_and_keeps_completions() -> None:- assert prepare_wire_message(FOCUS_CELL, is_kiosk=False) is None- assert prepare_wire_message(COMPLETION_RESULT, is_kiosk=False) is not None---def test_viewer_keeps_kiosk_only_and_filters_completions() -> None:- assert prepare_wire_message(FOCUS_CELL, is_kiosk=True) is not None- assert prepare_wire_message(COMPLETION_RESULT, is_kiosk=True) is None---def test_wire_format() -> None:- text = prepare_wire_message(ALERT, is_kiosk=False)- assert text is not None- message = json.loads(text)- assert message["op"] == "alert"- assert message["data"]["title"] == "title"- assert message["data"]["description"] == "description"diff --git a/tests/_server/api/endpoints/test_ws_rtc.py b/tests/_server/api/endpoints/test_ws_rtc.pyindex 73b4796e1f..0a52fdcaf7 100644--- a/tests/_server/api/endpoints/test_ws_rtc.py+++ b/tests/_server/api/endpoints/test_ws_rtc.py@@ -13,6 +13,7 @@ from tests._server.api.endpoints.ws_helpers import (assert_kernel_ready_response,assert_parse_ready_response,create_response,+ receive_notification,)from tests._server.conftest import get_user_config_managerfrom tests._server.mocks import get_session_manager@@ -69,9 +70,9 @@ async def test_loro_sync(client: TestClient) -> None:client.websocket_connect(ws_2) as websocket2,):# Verify both websockets received kernel ready messages- data1 = websocket1.receive_json()+ data1 = receive_notification(websocket1)assert_kernel_ready_response(data1)- data2 = websocket2.receive_json()+ data2 = receive_notification(websocket2)assert_parse_ready_response(data2)# Connect first client to sync websocket@@ -112,7 +113,7 @@ async def test_loro_cleanup_on_session_close(rtc_enabled(get_user_config_manager(client)),client.websocket_connect(ws_1) as websocket,):- data = websocket.receive_json()+ data = receive_notification(websocket)assert_kernel_ready_response(data)# Connect to cell websocket@@ -153,7 +154,7 @@ async def test_loro_persistence(client: TestClient) -> None:rtc_enabled(get_user_config_manager(client)),client.websocket_connect(ws_1) as websocket,):- data = websocket.receive_json()+ data = receive_notification(websocket)assert_kernel_ready_response(data)with client.websocket_connect(ws_1_sync) as cell_ws1:@@ -175,7 +176,7 @@ async def test_loro_persistence(client: TestClient) -> None:rtc_enabled(get_user_config_manager(client)),client.websocket_connect(ws_2) as websocket,):- data = websocket.receive_json()+ data = receive_notification(websocket)assert_kernel_ready_response(data, create_response({"resumed": True}))with client.websocket_connect(ws_2_sync) as cell_ws2:@@ -216,7 +217,7 @@ async def test_rtc_degrades_without_loro(client: TestClient) -> None:with client.websocket_connect("/ws?session_id=123&access_token=fake-token") as websocket:- data = websocket.receive_json()+ data = receive_notification(websocket)# Should still get kernel ready, but without RTC initializedassert_kernel_ready_response(data)@@ -269,7 +270,7 @@ async def test_ws_sync_cleanup_on_main_disconnect(client: TestClient) -> None:with rtc_enabled(get_user_config_manager(client)):with client.websocket_connect(ws_1) as main_websocket:- data = main_websocket.receive_json()+ data = receive_notification(main_websocket)assert_kernel_ready_response(data)# Connect to sync endpointdiff --git a/tests/_server/api/endpoints/ws/test_ws_formatter.py b/tests/_server/api/endpoints/ws/test_ws_formatter.pydeleted file mode 100644index c8d0e4c5fa..0000000000--- a/tests/_server/api/endpoints/ws/test_ws_formatter.py+++ /dev/null@@ -1,148 +0,0 @@-# Copyright 2026 Marimo. All rights reserved.-from __future__ import annotations--import json--from marimo._messaging.notification import (- AlertNotification,- KernelStartupErrorNotification,-)-from marimo._server.api.endpoints.ws.ws_formatter import (- format_wire_message,- serialize_notification_for_wire,-)---class TestFormatWireMessage:- """Tests for format_wire_message function."""-- def test_basic_formatting(self) -> None:- """Test basic wire message formatting."""- op = "test-op"- data = b'{"key": "value"}'- result = format_wire_message(op, data)-- parsed = json.loads(result)- assert parsed["op"] == "test-op"- assert parsed["data"] == {"key": "value"}-- def test_with_nested_data(self) -> None:- """Test formatting with nested JSON data."""- op = "cell-op"- data = b'{"cell_id": "abc123", "output": {"type": "text", "data": "hello"}}'- result = format_wire_message(op, data)-- parsed = json.loads(result)- assert parsed["op"] == "cell-op"- assert parsed["data"]["cell_id"] == "abc123"- assert parsed["data"]["output"]["type"] == "text"-- def test_with_special_characters_in_data(self) -> None:- """Test formatting with special characters in data."""- op = "alert"- data = b'{"message": "Hello\\nWorld\\twith\\ttabs"}'- result = format_wire_message(op, data)-- parsed = json.loads(result)- assert parsed["op"] == "alert"- assert parsed["data"]["message"] == "Hello\nWorld\twith\ttabs"-- def test_with_unicode_data(self) -> None:- """Test formatting with unicode characters."""- op = "notification"- data = '{"text": "Hello 世界 🌍"}'.encode()- result = format_wire_message(op, data)-- parsed = json.loads(result)- assert parsed["op"] == "notification"- assert parsed["data"]["text"] == "Hello 世界 🌍"-- def test_with_empty_object(self) -> None:- """Test formatting with empty object data."""- op = "empty"- data = b"{}"- result = format_wire_message(op, data)-- parsed = json.loads(result)- assert parsed["op"] == "empty"- assert parsed["data"] == {}---class TestSerializeNotificationForWebsocket:- """Tests for serialize_notification_for_wire function."""-- def test_kernel_startup_error_notification(self) -> None:- """Test serializing KernelStartupErrorNotification."""- notification = KernelStartupErrorNotification(- error="Failed to start kernel: module not found"- )- result = serialize_notification_for_wire(notification)-- parsed = json.loads(result)- assert parsed["op"] == "kernel-startup-error"- assert (- parsed["data"]["error"]- == "Failed to start kernel: module not found"- )-- def test_alert_notification(self) -> None:- """Test serializing AlertNotification."""- notification = AlertNotification(- title="Test Alert",- description="This is a test alert message",- )- result = serialize_notification_for_wire(notification)-- parsed = json.loads(result)- assert parsed["op"] == "alert"- assert parsed["data"]["title"] == "Test Alert"- assert parsed["data"]["description"] == "This is a test alert message"-- def test_alert_notification_with_variant(self) -> None:- """Test serializing AlertNotification with danger variant."""- notification = AlertNotification(- title="Error",- description="Something went wrong",- variant="danger",- )- result = serialize_notification_for_wire(notification)-- parsed = json.loads(result)- assert parsed["op"] == "alert"- assert parsed["data"]["variant"] == "danger"-- def test_produces_valid_json(self) -> None:- """Test that output is always valid JSON."""- notification = KernelStartupErrorNotification(- error='Error with "quotes" and special chars: <>&'- )- result = serialize_notification_for_wire(notification)-- # Should not raise- parsed = json.loads(result)- assert "op" in parsed- assert "data" in parsed---class TestIntegration:- """Integration tests for the ws_formatter module."""-- def test_roundtrip_matches_expected_wire_format(self) -> None:- """Test that the wire format matches what the frontend expects.-- The frontend expects messages in the format:- {"op": "operation-name", "data": {...notification fields...}}- """- notification = KernelStartupErrorNotification(error="test error")- result = serialize_notification_for_wire(notification)-- parsed = json.loads(result)-- # Verify structure matches expected wire format- assert set(parsed.keys()) == {"op", "data"}- assert isinstance(parsed["op"], str)- assert isinstance(parsed["data"], dict)-- # Verify op matches notification name- assert parsed["op"] == notification.name- assert parsed["op"] == "kernel-startup-error"diff --git a/tests/_server/api/endpoints/ws_helpers.py b/tests/_server/api/endpoints/ws_helpers.pyindex 5d586e20cb..76d5a1910e 100644--- a/tests/_server/api/endpoints/ws_helpers.py+++ b/tests/_server/api/endpoints/ws_helpers.py@@ -16,9 +16,21 @@ if TYPE_CHECKING:from starlette.testclient import WebSocketTestSession+def receive_notification(websocket: WebSocketTestSession) -> dict[str, Any]:+ """Read a private session notification from the host event stream."""+ while True:+ event = websocket.receive_json()+ if "op" in event:+ return event+ assert "event" in event+ if event["event"] == "marimo":+ notification = event["data"]["marimo"]+ return {"op": notification["op"], "data": notification}++def receive_until(op: str, websocket: WebSocketTestSession) -> dict[str, Any]:while True:- data = websocket.receive_json()+ data = receive_notification(websocket)if data["op"] == op:return datadiff --git a/tests/_server/host/test_app_websocket.py b/tests/_server/host/test_app_websocket.pynew file mode 100644index 0000000000..316e718e99--- /dev/null+++ b/tests/_server/host/test_app_websocket.py@@ -0,0 +1,236 @@+# Copyright 2026 Marimo. All rights reserved.+"""App behavior on the host-framed session transport."""++from __future__ import annotations++import asyncio+from typing import TYPE_CHECKING++import msgspec+import pytest+from starlette.websockets import WebSocketDisconnect++from marimo._core import protocol+from marimo._server.codes import WebSocketCodes+from marimo._server.host.bridge import SessionBridge+from marimo._server.host.context import HostContext+from marimo._server.host.events import serialize_event+from marimo._session.model import SessionMode+from marimo._types.ids import SessionId+from tests._server.host.drive import socket_snapshot+from tests._server.host.test_editor_websocket import receive_notification+from tests._server.mocks import get_session_manager++if TYPE_CHECKING:+ from collections.abc import Iterator++ from starlette.testclient import TestClient+++def app_host(client: TestClient) -> Iterator[SessionBridge]:+ manager = get_session_manager(client)+ manager.mode = SessionMode.RUN+ manager.include_code = False+ bridge = SessionBridge(manager)+ client.app.state.host_context = HostContext(+ bridge=bridge, token="", port=0+ )+ with client:+ assert client.portal is not None+ client.portal.call(bridge.open)+ try:+ yield bridge+ finally:+ client.portal.call(bridge.close)+++def url(session_id: str) -> str:+ return f"/ws?message_format=host&session_id={session_id}&access_token=fake-token"++[email protected]("include_code", [False, True])+def test_app_executes_with_hidden_source_and_retained_hashes(+ client: TestClient, app_host: SessionBridge, include_code: bool+) -> None:+ get_session_manager(client).include_code = include_code+ with client.websocket_connect(url("alice") + "&color=blue") as ws:+ snapshot = socket_snapshot(ws)+ ready = receive_notification(ws, "kernel-ready")+ assert ready["auto_instantiated"] is True+ assert ready["codes"] == (+ ["import marimo as mo"] if include_code else [""]+ )+ cell = next(+ e["data"]["cell"] for e in snapshot if e["event"] == "cell"+ )+ assert cell["code"] == (+ "import marimo as mo" if include_code else None+ )+ manager = get_session_manager(client)+ session = manager.get_session(SessionId("alice"))+ assert session is not None+ assert session._kernel_manager.app_metadata.query_params == {+ "color": "blue"+ }+ notebook = app_host.notebook_for_session(session)+ assert notebook is not None+ source = next(iter(notebook.document))+ assert source.code == "import marimo as mo"+ assert (cell["code_hash"], cell["etag"]) == (+ source.code_hash,+ source.etag,+ )+ # Delivery never mutates the host event, even when readers differ.+ event = next(+ e+ for e in app_host.host.events(notebook_id=notebook.id)+ if isinstance(e.event, protocol.CellEvent)+ )+ hidden = msgspec.json.decode(+ serialize_event(event, include_code=False)+ )+ visible = msgspec.json.decode(+ serialize_event(event, include_code=True)+ )+ assert hidden["data"]["cell"] == {+ **visible["data"]["cell"],+ "code": None,+ }+ assert event.event.data.cell.code == source.code+ executions = []+ while True:+ event = ws.receive_json()+ if event["event"] == "execution":+ executions.append(event["data"]["execution"])+ if (+ event["event"] == "run"+ and event["data"]["run"]["status"] == "completed"+ ):+ break+ assert executions+ assert executions[-1]["code_hash"] == cell["code_hash"]+ assert executions[-1]["status"] == "completed"+++def test_app_visitors_are_isolated_and_reconnect_retains_identity(+ client: TestClient, app_host: SessionBridge+) -> None:+ manager = get_session_manager(client)+ with client.websocket_connect(url("alice")) as alice:+ a = socket_snapshot(alice)+ receive_notification(alice, "kernel-ready")+ alice_id = next(+ e["data"]["notebook"]["id"] for e in a if e["event"] == "notebook"+ )+ original = manager.get_session(SessionId("alice"))+ with client.websocket_connect(url("bob")) as bob:+ b = socket_snapshot(bob)+ receive_notification(bob, "kernel-ready")+ bob_id = next(+ e["data"]["notebook"]["id"]+ for e in b+ if e["event"] == "notebook"+ )+ assert alice_id != bob_id+ assert original is not manager.get_session(SessionId("bob"))+ assert all(+ record.path is None and record.operations == ()+ for record in app_host.host.notebooks.values()+ )+ with client.websocket_connect(url("alice")) as reconnected:+ snapshot = socket_snapshot(reconnected)+ receive_notification(reconnected, "reconnected")+ assert manager.get_session(SessionId("alice")) is original+ assert (+ next(+ e["data"]["notebook"]["id"]+ for e in snapshot+ if e["event"] == "notebook"+ )+ == alice_id+ )+++def test_app_host_keeps_authentication(+ client: TestClient, app_host: SessionBridge+) -> None:+ with pytest.raises(WebSocketDisconnect) as exc:+ with client.websocket_connect(+ "/ws?message_format=host&session_id=alice"+ ):+ pass+ assert exc.value.code == WebSocketCodes.UNAUTHORIZED+ assert not app_host.host.notebooks+ assert not get_session_manager(client).sessions+++def test_app_host_is_removed_when_session_expires(+ client: TestClient, app_host: SessionBridge+) -> None:+ manager = get_session_manager(client)+ with client.websocket_connect(url("alice")) as ws:+ cursor = socket_snapshot(ws)[-1]["id"]+ receive_notification(ws, "kernel-ready")+ session = manager.get_session(SessionId("alice"))+ assert session is not None+ session.ttl_seconds = 0.01+ notebook = app_host.notebook_for_session(session)+ assert notebook is not None+ removed = asyncio.Event()+ unsubscribe = app_host.host.subscribe(+ lambda _: removed.set(), types={"notebook"}+ )+ ws.close()++ async def expired() -> None:+ await asyncio.wait_for(removed.wait(), timeout=5)+ assert not manager.sessions+ assert not app_host.host.notebooks++ ws.portal.call(expired)+ unsubscribe()+ with client.websocket_connect(url("alice") + f"&cursor={cursor}") as ws:+ snapshot = socket_snapshot(ws)+ assert snapshot[0]["event"] == "reset"+ assert (+ next(+ e["data"]["notebook"]["id"]+ for e in snapshot+ if e["event"] == "notebook"+ )+ != notebook.id+ )++[email protected]("stale", [False, True])+def test_app_session_replays_host_events_or_resets_stale_cursor(+ client: TestClient, app_host: SessionBridge, stale: bool+) -> None:+ endpoint = url("alice") + "&types=notebook,cell,custom,marimo"+ with client.websocket_connect(endpoint) as ws:+ snapshot = socket_snapshot(ws)+ cursor = snapshot[-1]["id"]+ receive_notification(ws, "kernel-ready")+ session = get_session_manager(client).get_session(SessionId("alice"))+ assert session is not None+ notebook = app_host.notebook_for_session(session)+ assert notebook is not None+ assert client.portal is not None+ client.portal.call(notebook.emit, "test.missed", {"value": 1})+ if stale:+ cursor = "expired-host-cursor"+ with client.websocket_connect(endpoint + f"&cursor={cursor}") as ws:+ opening = socket_snapshot(ws)+ if stale:+ assert opening[0]["event"] == "reset"+ assert any(e["event"] == "notebook" for e in opening)+ cells = [+ e["data"]["cell"] for e in opening if e["event"] == "cell"+ ]+ assert cells+ assert all(c["code"] is None for c in cells)+ else:+ assert [e["event"] for e in opening] == ["custom", "ready"]+ assert opening[0]["data"]["custom"]["data"] == {"value": 1}+ receive_notification(ws, "reconnected")diff --git a/tests/_server/host/test_editor_websocket.py b/tests/_server/host/test_editor_websocket.pyindex fb7c839565..335c0a73f3 100644--- a/tests/_server/host/test_editor_websocket.py+++ b/tests/_server/host/test_editor_websocket.py@@ -51,7 +51,7 @@ def editor_host(client: TestClient) -> Iterator[SessionBridge]:def socket_url(bridge: SessionBridge, session_id: str = "s1") -> str:(notebook_id,) = bridge.host.notebooks- return f"{HOST_API_PATH}/notebooks/{notebook_id}/events/ws?session_id={session_id}&access_token=fake-token"+ return f"{HOST_API_PATH}/notebooks/{notebook_id}/events/ws?message_format=host&session_id={session_id}&access_token=fake-token"def receive_notification(@@ -415,10 +415,16 @@ def test_invalid_event_types_are_rejected_before_starting_a_session(assert not get_session_manager(client).sessions[email protected]("session_route", [False, True])def test_editor_resumes_host_events_without_replaying_private_notifications(- client: TestClient, editor_host: SessionBridge+ client: TestClient, editor_host: SessionBridge, session_route: bool) -> None:- url = f"{socket_url(editor_host)}&types=marimo,custom"+ endpoint = (+ "/ws?message_format=host&session_id=s1&access_token=fake-token"+ if session_route+ else socket_url(editor_host)+ )+ url = f"{endpoint}&types=marimo,custom"with client.websocket_connect(url) as socket:cursor = socket_snapshot(socket)[-1]["id"]receive_notification(socket, "kernel-ready")@@ -458,3 +464,49 @@ def test_an_empty_cursor_is_rejected_before_starting_a_session(pytest.fail("Invalid cursor was accepted")assert (exc.value.code, exc.value.reason) == (1008, "Invalid event cursor")assert not get_session_manager(client).sessions+++def test_untitled_editor_bootstraps_and_reconnects_with_host_events(+ client: TestClient,+) -> None:+ from marimo._server.workspace import EmptyWorkspace++ manager = get_session_manager(client)+ manager.workspace = EmptyWorkspace()+ bridge = SessionBridge(manager)+ client.app.state.host_context = HostContext(+ bridge=bridge, token="host-token", port=1234+ )+ url = "/ws?message_format=host&session_id=new&access_token=fake-token"+ with client:+ assert client.portal is not None+ client.portal.call(bridge.open)+ try:+ with client.websocket_connect(url) as ws:+ snapshot = socket_snapshot(ws)+ ready = receive_notification(ws, "kernel-ready")+ notebook_id = next(+ e["data"]["notebook"]["id"]+ for e in snapshot+ if e["event"] == "notebook"+ )+ response = client.post(+ "/api/kernel/run",+ headers=headers("new"),+ json={"cellIds": ready["cell_ids"], "codes": ["x = 42"]},+ )+ assert response.status_code == 200+ receive_notification(ws, "completed-run")+ with client.websocket_connect(url) as ws:+ snapshot = socket_snapshot(ws)+ receive_notification(ws, "reconnected")+ assert (+ next(+ e["data"]["notebook"]["id"]+ for e in snapshot+ if e["event"] == "notebook"+ )+ == notebook_id+ )+ finally:+ client.portal.call(bridge.close)diff --git a/tests/_server/host/test_host_index.py b/tests/_server/host/test_host_index.pyindex 00e49274ad..44d7dea6f4 100644--- a/tests/_server/host/test_host_index.py+++ b/tests/_server/host/test_host_index.py@@ -15,7 +15,8 @@ from marimo._core.protocol import ProjectMessagefrom marimo._core.stream import RoutedEventfrom marimo._server.host.index import WorkspaceIndexfrom marimo._server.models.home import MarimoFile-from marimo._server.workspace import FixedFilesWorkspace+from marimo._server.workspace import DirectoryWorkspace, FixedFilesWorkspace+from marimo._utils.http import HTTPExceptionfrom tests._core.conftest import (ScriptedBackend,make_notebook,@@ -163,3 +164,126 @@ async def test_deleted_file_keeps_its_runtime_until_stopped(assert dict(host.notebooks) == {}assert runtime is not Noneassert backend.calls == [("stop", runtime.id)]+++def test_open_notebooks_survive_rescans_and_move_into_workspace(+ tmp_path: Path,+) -> None:+ root = tmp_path / "workspace"+ root.mkdir()+ tutorials = tmp_path / "tutorials"+ tutorials.mkdir()+ file = tutorials / "intro.py"+ file.write_text("import marimo\n")+ ws = DirectoryWorkspace(str(root), include_markdown=False)+ host = Host(operations=[])+ index = WorkspaceIndex(host, ws, make_notebook)+ index.refresh()+ assert [+ e.event.data.project.name+ for e in host.events()+ if isinstance(e.event.data, ProjectMessage)+ ] == ["workspace"]++ with pytest.raises(HTTPException):+ index.register_open_notebook(str(file))+ ws.register_temp_dir(str(tutorials))+ assert index.ensure(str(file)) is None+ record = index.register_open_notebook(str(file))+ [project] = [+ e.event.data.project+ for e in host.events()+ if isinstance(e.event.data, ProjectMessage)+ and e.event.data.project.id == record.project_id+ ]+ assert (project.name, project.root, project.operations) == (+ "Open notebooks",+ None,+ (),+ )+ assert (record.name, record.path) == ("intro", None)+ assert "notebook.edit" in record.operations+ assert "notebook.save" in record.operations+ assert "notebook.delete" not in record.operations++ index.refresh()+ assert index.register_open_notebook(str(file)) == record+ assert index.file_of(record.id) == file+ another = tutorials / "other.py"+ another.write_text("import marimo\n")+ assert index.register_open_notebook(str(another)).project_id == project.id++ renamed = tutorials / "renamed.py"+ file.rename(renamed)+ moved = index.moved(record.id, str(renamed))+ assert moved == replace(record, name="renamed")+ assert index.notebook_for(str(file)) is None+ assert index.notebook_for(str(renamed)) == moved++ saved = root / "saved.py"+ renamed.rename(saved)+ moved = index.moved(record.id, str(saved))+ assert moved is not None+ assert (moved.id, moved.project_id, moved.path) == (+ record.id,+ index.project_id,+ "saved.py",+ )+ index.refresh()+ assert index.notebook_for(str(saved)) == moved+ assert index.notebook_for(str(renamed)) is None+ assert index.file_of(record.id) == saved+++def test_register_open_notebook_keeps_workspace_files_in_the_workspace(+ tmp_path: Path,+) -> None:+ host = Host(operations=[])+ index = WorkspaceIndex(host, workspace(tmp_path, "a.py"), make_notebook)+ index.refresh()+ record = index.register_open_notebook(str(tmp_path / "a.py"))+ assert (record.project_id, record.path) == (index.project_id, "a.py")+ assert [+ e.event.data.project.id+ for e in host.events()+ if isinstance(e.event.data, ProjectMessage)+ ] == [index.project_id]++[email protected]("untitled", [False, True])+def test_saving_outside_the_workspace_preserves_identity(+ tmp_path: Path, untitled: bool+) -> None:+ root = tmp_path / "workspace"+ root.mkdir()+ original = root / "a.py"+ original.write_text("import marimo\napp = marimo.App()\n")+ host = Host(operations=[])+ index = WorkspaceIndex(+ host,+ DirectoryWorkspace(str(root), include_markdown=False),+ make_notebook,+ )+ index.refresh()+ record = (+ index.untitled() if untitled else index.notebook_for(str(original))+ )+ assert record is not None+ saved = tmp_path / "saved.py"+ if untitled:+ saved.write_text("import marimo\n")+ else:+ original.rename(saved)+ moved = index.moved(record.id, str(saved))+ index.refresh()+ assert (moved.id, moved.name, moved.path) == (record.id, "saved", None)+ assert [+ e.event.data.project.name+ for e in host.events()+ if isinstance(e.event.data, ProjectMessage)+ and e.event.data.project.id == moved.project_id+ ] == ["Open notebooks"]+ assert index.notebook_for(str(saved)) == moved+ assert index.file_of(record.id) == saved+ if not untitled:+ assert index.notebook_for(str(original)) is Nonediff --git a/tests/_server/mocks.py b/tests/_server/mocks.pyindex 2f5f5d946f..6552c84ebf 100644--- a/tests/_server/mocks.py+++ b/tests/_server/mocks.py@@ -144,7 +144,11 @@ def with_session(with client.websocket_connect(f"/ws?session_id={session_id}", headers=headers) as websocket:- data = websocket.receive_text()+ from tests._server.api.endpoints.ws_helpers import (+ receive_until,+ )++ data = receive_until("kernel-ready", websocket)assert dataif "temp_marimo_file" in func.__code__.co_varnames:func(@@ -181,7 +185,11 @@ def with_websocket_session(with client.websocket_connect(f"/ws?session_id={session_id}", headers=headers) as websocket:- data = websocket.receive_text()+ from tests._server.api.endpoints.ws_helpers import (+ receive_until,+ )++ data = receive_until("kernel-ready", websocket)assert datafunc(client, websocket)@@ -218,7 +226,11 @@ def with_read_session(with client.websocket_connect(f"/ws?session_id={session_id}", headers=headers) as websocket:- data = websocket.receive_text()+ from tests._server.api.endpoints.ws_helpers import (+ receive_until,+ )++ data = receive_until("kernel-ready", websocket)assert data# Just change the mode here, otherwise our tests will run,# in threadsdiff --git a/tests/_server/test_asgi.py b/tests/_server/test_asgi.pyindex 9791447190..e306cfadaa 100644--- a/tests/_server/test_asgi.py+++ b/tests/_server/test_asgi.py@@ -67,6 +67,55 @@ class TestASGIAppBuilder(unittest.TestCase):# Restore __main__ in case a kernel thread modified itsys.modules["__main__"] = self._saved_main+ def test_mounted_apps_have_independent_host_notebooks(self) -> None:+ from tests._server.host.drive import socket_snapshot+ from tests._server.host.test_editor_websocket import (+ receive_notification,+ )++ builder = create_asgi_app(quiet=True)+ app = (+ builder.with_app(path="/one", root=self.app1)+ .with_app(path="/two", root=self.app2)+ .build()+ )+ managers = [+ child.state.session_manager+ for child in builder._app_cache.values()+ ]+ with TestClient(app) as client:+ try:+ with (+ client.websocket_connect(+ "/one/ws?message_format=host&session_id=visitor"+ ) as one,+ client.websocket_connect(+ "/two/ws?message_format=host&session_id=visitor"+ ) as two,+ ):+ snapshots = [socket_snapshot(ws) for ws in (one, two)]+ for ws in (one, two):+ receive_notification(ws, "kernel-ready")+ ids = [+ next(+ e["data"]["notebook"]["id"]+ for e in events+ if e["event"] == "notebook"+ )+ for events in snapshots+ ]+ assert ids[0] != ids[1]+ for events in snapshots:+ assert all(+ e["data"]["cell"]["code"] is None+ for e in events+ if e["event"] == "cell"+ )+ finally:+ assert client.portal is not None+ for manager in managers:+ client.portal.call(join_kernel_thread_tasks, manager)+def test_create_asgi_app(self) -> None:builder = create_asgi_app(quiet=True, include_code=True)assert isinstance(builder, ASGIAppBuilder)@@ -423,7 +472,9 @@ class TestASGIAppBuilder(unittest.TestCase):assert "http" in invoked_for# WebSocket should also have user/meta in scope.- with client.websocket_connect("/ws?session_id=test123") as ws:+ with client.websocket_connect(+ "/ws?message_format=host&session_id=test123"+ ) as ws:data = ws.receive_text()assert data # kernel-ready messagefinally:diff --git a/tests/_server/test_session_manager.py b/tests/_server/test_session_manager.pyindex 57c81f6994..c9d90299b2 100644--- a/tests/_server/test_session_manager.py+++ b/tests/_server/test_session_manager.py@@ -4,7 +4,7 @@ import asyncioimport sysfrom textwrap import dedentfrom typing import TYPE_CHECKING-from unittest.mock import MagicMock, Mock+from unittest.mock import AsyncMock, MagicMock, Mockimport pytest@@ -625,7 +625,7 @@ async def test_connections_share_starting_notebook(def connector(sid: str) -> SessionConnector:return SessionConnector(manager=session_manager,- handler=MagicMock(),+ handler=MagicMock(_prepare_session=AsyncMock()),params=ConnectionParams(session_id=SessionId(sid),file_key=NEW_FILE,@@ -716,7 +716,7 @@ async def test_refresh_reuses_pending_startup(monkeypatch.setattr(SessionImpl, "create", create)def connector(sid: str) -> SessionConnector:- handler = MagicMock(consumer_id=sid)+ handler = MagicMock(consumer_id=sid, _prepare_session=AsyncMock())return SessionConnector(manager=session_manager,handler=handler,diff --git a/tests/_session/state/test_session_view.py b/tests/_session/state/test_session_view.pyindex 33927364b8..135b047c2a 100644--- a/tests/_session/state/test_session_view.py+++ b/tests/_session/state/test_session_view.py@@ -2434,9 +2434,8 @@ def test_preparation_remains_available_after_package_changes(][email protected]("include_notebook", [False, True])def test_snapshot_notifications_preserve_replay_order(- session_view: SessionView, include_notebook: bool+ session_view: SessionView,) -> None:progress = StartupProgressNotification(phase="starting-kernel", logs="Ready\n", log_mode="replace"@@ -2458,9 +2457,7 @@ def test_snapshot_notifications_preserve_replay_order(for notification in (cell, model, progress):session_view.add_notification(notification)- notifications = session_view.snapshot_notifications(- include_notebook=include_notebook- )+ notifications = session_view.snapshot_notifications()assert notifications == [EnvironmentStateNotification(source="kernel",@@ -2471,7 +2468,8 @@ def test_snapshot_notifications_preserve_replay_order(state=EnvironmentState(restart_required=False, operations=[]),),progress,- *([model, cell] if include_notebook else []),+ model,+ cell,]captured = msgspec.json.encode(notifications)session_view.update_cell_outputs({cell_id: ("text/plain", "new output")})@@ -2482,10 +2480,5 @@ def test_snapshot_notifications_preserve_replay_order()assert msgspec.json.encode(notifications) == capturedassert (- msgspec.json.encode(- session_view.snapshot_notifications(- include_notebook=include_notebook- )- )- != captured+ msgspec.json.encode(session_view.snapshot_notifications()) != captured)diff --git a/tests/_session/test_notification_ordering.py b/tests/_session/test_notification_ordering.pyindex 40e6980ceb..d8e9619b09 100644--- a/tests/_session/test_notification_ordering.py+++ b/tests/_session/test_notification_ordering.py@@ -19,14 +19,13 @@ from marimo._messaging.notification import (OperationRunning,)from marimo._messaging.serde import (- deserialize_kernel_message,serialize_kernel_message,)from marimo._messaging.types import KernelMessagefrom marimo._server.api.endpoints.ws.ws_connection_validator import (ConnectionParams,)-from marimo._server.api.endpoints.ws_endpoint import WebSocketHandler+from marimo._server.host.session import SessionEventStreamfrom marimo._session.consumer import SessionConsumerfrom marimo._session.extensions.extensions import (NotificationListenerExtension,@@ -164,9 +163,14 @@ async def test_reconnect_snapshot_precedes_a_queued_live_update(session, consumer = session_and_consumersession.disconnect_consumer(consumer)session.notify(_progress("Before\n"), from_consumer_id=None)- handler = WebSocketHandler(- websocket=MagicMock(),- manager=MagicMock(),+ handler = SessionEventStream(+ connection=MagicMock(),+ notebook=None,+ bridge=MagicMock(),+ doc_manager=MagicMock(),+ types=None,+ cursor=None,+ manager=MagicMock(mode=SessionMode.EDIT),params=ConnectionParams(session_id=SessionId("reconnected"),file_key="notebook.py",@@ -174,7 +178,6 @@ async def test_reconnect_snapshot_precedes_a_queued_live_update(auto_instantiate=False,rtc_enabled=False,),- mode=SessionMode.EDIT,)asyncio.get_running_loop().call_soon(lambda: session.notify(_progress("After\n"), from_consumer_id=None)@@ -183,10 +186,8 @@ async def test_reconnect_snapshot_precedes_a_queued_live_update(await asyncio.sleep(0)messages = []- while not handler.message_queue.empty():- messages.append(- deserialize_kernel_message(handler.message_queue.get_nowait())- )+ while not handler._events.empty():+ messages.append(handler._events.get_nowait().event.data.marimo)assert [messagefor message in messages