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
feat: experimental SSE transport for the kernel connection (MARIMO_SERVER_TRANSPORT) (#10119)
Myles Scolnick431225046281
diff --git a/docs/guides/configuration/index.md b/docs/guides/configuration/index.mdindex 351beddd93..fe91a9e401 100644--- a/docs/guides/configuration/index.md+++ b/docs/guides/configuration/index.md@@ -125,6 +125,7 @@ marimo supports the following environment variables for advanced configuration:| `MARIMO_SKIP_UPDATE_CHECK` | If set to "1", marimo will skip checking for updates when starting. | Not set || `MARIMO_SQL_DEFAULT_LIMIT` | Default limit for SQL query results. If not set, no limit is applied. | Not set || `MARIMO_SESSION_COOKIE_SECURE` | If set to `true`/`1`, marks the session cookie as `Secure` so browsers only send it over HTTPS. Enable when serving marimo behind TLS. | `false` |+| `MARIMO_SERVER_TRANSPORT` | Experimental. The transport for streaming kernel messages to the browser: `websocket` or `sse`. Use `sse` when deploying behind proxies or services that do not support WebSockets. | `websocket` |### Tipsdiff --git a/docs/guides/deploying/index.md b/docs/guides/deploying/index.mdindex 17f71f5779..7dfc47bc11 100644--- a/docs/guides/deploying/index.md+++ b/docs/guides/deploying/index.md@@ -53,6 +53,31 @@ If you would like to deploy your application at a subpath, you can set the `--bamarimo run app.py --base-url /subpath```+### Deploying without WebSockets (experimental)++marimo streams kernel messages to the browser over a WebSocket by default.+Some proxies and hosting services handle WebSockets poorly or not at all; for+these deployments, you can switch the kernel connection to server-sent+events (SSE) over plain HTTP with the `MARIMO_SERVER_TRANSPORT` environment+variable:++```bash+MARIMO_SERVER_TRANSPORT=sse marimo run app.py+```++This setting is experimental. Keep in mind:++- The terminal and language servers (LSP) in `marimo edit` still require+ WebSockets and are unaffected by this setting.+- Real-time collaboration (`rtc_v2`) requires WebSockets and is disabled+ when using SSE.+- Make sure proxies do not buffer the `/sse` endpoint's+ `text/event-stream` responses (marimo sends `Cache-Control: no-transform`+ and `X-Accel-Buffering: no` headers, and a keep-alive comment every 20+ seconds).+- Browsers cap concurrent HTTP/1.1 connections per origin (typically 6), so+ prefer serving over HTTP/2 when many notebook tabs may be open at once.+### Including code in your applicationBy default, `marimo run` does not send your notebook's source code todiff --git a/frontend/src/core/config/__tests__/config-schema.test.ts b/frontend/src/core/config/__tests__/config-schema.test.tsindex 40fc953f4e..f6cd4151a0 100644--- a/frontend/src/core/config/__tests__/config-schema.test.ts+++ b/frontend/src/core/config/__tests__/config-schema.test.ts@@ -4,6 +4,7 @@ import { createStore } from "jotai";import { expect, test } from "vitest";import {configOverridesAtom,+ connectionTransportTypeAtom,resolvedMarimoConfigAtom,userConfigAtom,} from "../config";@@ -296,3 +297,19 @@ test("resolvedMarimoConfigAtom overrides correctly and does not mutate the origiformatting: { line_length: 79 },});});++test("connectionTransportTypeAtom defaults to websocket", () => {+ const store = createStore();+ store.set(userConfigAtom, defaultUserConfig());+ expect(store.get(connectionTransportTypeAtom)).toBe("websocket");+});++test("connectionTransportTypeAtom reads server.transport", () => {+ const store = createStore();+ const config = defaultUserConfig();+ store.set(userConfigAtom, {+ ...config,+ server: { ...config.server, transport: "sse" },+ });+ expect(store.get(connectionTransportTypeAtom)).toBe("sse");+});diff --git a/frontend/src/core/config/config-schema.ts b/frontend/src/core/config/config-schema.tsindex a9dba1c12e..65412488a4 100644--- a/frontend/src/core/config/config-schema.ts+++ b/frontend/src/core/config/config-schema.ts@@ -203,6 +203,7 @@ export const UserConfigSchema = zserver: z.looseObject({disable_file_downloads: z.boolean().optional(),+ transport: z.enum(["websocket", "sse"]).optional(),}).prefault(() => ({})),diagnostics: zdiff --git a/frontend/src/core/config/config.ts b/frontend/src/core/config/config.tsindex 54c6ecc427..e1c9e753d0 100644--- a/frontend/src/core/config/config.ts+++ b/frontend/src/core/config/config.ts@@ -44,6 +44,16 @@ export const autoSaveConfigAtom = atom((get) => {return get(resolvedMarimoConfigAtom).save;});+/**+ * The transport used to stream kernel messages from the server.+ * Experimental; configured via `server.transport`.+ */+export const connectionTransportTypeAtom = atom<"websocket" | "sse">((get) => {+ return get(resolvedMarimoConfigAtom).server.transport === "sse"+ ? "sse"+ : "websocket";+});+export const aiAtom = atom((get) => {return get(resolvedMarimoConfigAtom).ai;});diff --git a/frontend/src/core/runtime/__tests__/runtime.test.ts b/frontend/src/core/runtime/__tests__/runtime.test.tsindex c28e727382..b9aac6d55b 100644--- a/frontend/src/core/runtime/__tests__/runtime.test.ts+++ b/frontend/src/core/runtime/__tests__/runtime.test.ts@@ -154,6 +154,51 @@ describe("RuntimeManager", () => {});});+ describe("getSseURL", () => {+ it("should return an http(s) URL with the session ID", () => {+ const runtime = new RuntimeManager(mockConfig);+ const url = runtime.getSseURL("1234" as SessionId);++ expect(url.protocol).toBe("https:");+ expect(url.pathname).toBe("/sse");+ expect(url.searchParams.get("session_id")).toBe("1234");+ });++ it("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+ // proxy and server logs.+ const runtime = new RuntimeManager(+ {+ url: "https://sandbox.example.com",+ lazy: true,+ authToken: "my-secret-token",+ },+ true,+ );+ const url = runtime.getSseURL("s_123" as SessionId);++ expect(url.searchParams.get("access_token")).toBeNull();+ expect(url.toString()).not.toContain("my-secret-token");+ });++ it("should strip an access_token forwarded from the page URL", () => {+ // The page URL can briefly carry access_token before auth cleanup+ // removes it; it must not be forwarded to /sse.+ const original = window.location.href;+ window.history.pushState({}, "", "/?access_token=page-token&foo=bar");+ try {+ const runtime = new RuntimeManager(mockConfig);+ const url = runtime.getSseURL("s_123" as SessionId);++ expect(url.searchParams.get("access_token")).toBeNull();+ expect(url.searchParams.get("foo")).toBe("bar");+ } finally {+ window.history.pushState({}, "", original);+ }+ });+ });+describe("getWsSyncURL", () => {it("should return WebSocket Sync URL", () => {const runtime = new RuntimeManager(mockConfig);diff --git a/frontend/src/core/runtime/runtime.ts b/frontend/src/core/runtime/runtime.tsindex 87ef9d4e2a..211570f6af 100644--- a/frontend/src/core/runtime/runtime.ts+++ b/frontend/src/core/runtime/runtime.ts@@ -107,9 +107,10 @@ export class RuntimeManager {}/**- * The WebSocket URL of the runtime.+ * Search params for a session connection: the base URL's params, merged+ * with the current page's, plus the session id.*/- getWsURL(sessionId: SessionId): URL {+ private getSessionSearchParams(sessionId: SessionId): URLSearchParams {const baseUrl = new URL(this.config.url);const searchParams = new URLSearchParams(baseUrl.search);@@ -123,27 +124,40 @@ export class RuntimeManager {});searchParams.set(KnownQueryParams.sessionId, sessionId);- return this.formatWsURL("/ws", searchParams);+ return searchParams;}/**- * The WebSocket Sync URL of the runtime, for real-time updates.+ * The WebSocket URL of the runtime.*/- getWsSyncURL(sessionId: SessionId): URL {- const baseUrl = new URL(this.config.url);- const searchParams = new URLSearchParams(baseUrl.search);+ getWsURL(sessionId: SessionId): URL {+ return this.formatWsURL("/ws", this.getSessionSearchParams(sessionId));+ }- // Merge in current page's query parameters- const currentParams = new URLSearchParams(window.location.search);- currentParams.forEach((value, key) => {- // Don't override base URL params- if (!searchParams.has(key)) {- searchParams.set(key, value);- }+ /**+ * The SSE URL of the runtime; the http(s) alternative to `getWsURL`+ * when `server.transport` is `"sse"`. Unlike WebSockets, SSE requests+ * can send headers, so auth travels in the Authorization header+ * (see `headers()`) instead of the URL.+ */+ getSseURL(sessionId: SessionId): URL {+ const url = this.formatHttpURL({+ path: "/sse",+ searchParams: this.getSessionSearchParams(sessionId),+ restrictToKnownQueryParams: false,});+ // 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.+ url.searchParams.delete(KnownQueryParams.accessToken);+ return url;+ }- searchParams.set(KnownQueryParams.sessionId, sessionId);- return this.formatWsURL("/ws_sync", searchParams);+ /**+ * The WebSocket Sync URL of the runtime, for real-time updates.+ */+ getWsSyncURL(sessionId: SessionId): URL {+ return this.formatWsURL("/ws_sync", this.getSessionSearchParams(sessionId));}/**diff --git a/frontend/src/core/websocket/__tests__/useMarimoKernelConnection.test.ts b/frontend/src/core/websocket/__tests__/useMarimoKernelConnection.test.tsindex af9cc99d61..86234a8616 100644--- a/frontend/src/core/websocket/__tests__/useMarimoKernelConnection.test.ts+++ b/frontend/src/core/websocket/__tests__/useMarimoKernelConnection.test.ts@@ -36,6 +36,10 @@ describe("classifyCloseEvent", () => {"MARIMO_NO_SESSION_ID","MARIMO_NO_SESSION","MARIMO_SHUTDOWN",+ // Delivered as in-band close events by the SSE transport; must be+ // terminal or a rejected client would reconnect forever.+ "MARIMO_UNAUTHORIZED",+ "MARIMO_KIOSK_NOT_ALLOWED",])("%s → terminal with KERNEL_DISCONNECTED, closes transport", (reason) => {const decision = classify(reason);expect(decision.kind).toBe("terminal");diff --git a/frontend/src/core/websocket/__tests__/useWebSocket.test.ts b/frontend/src/core/websocket/__tests__/useWebSocket.test.tsnew file mode 100644index 0000000000..2065cec5ae--- /dev/null+++ b/frontend/src/core/websocket/__tests__/useWebSocket.test.ts@@ -0,0 +1,49 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { afterEach, describe, expect, it, vi } from "vitest";+import { BasicTransport } from "../transports/basic";+import { SseTransport } from "../transports/sse";+import { WsTransport } from "../transports/ws";+import { createConnectionTransport } from "../useWebSocket";++vi.mock("../../wasm/utils", () => ({+ isWasm: () => false,+}));++describe("createConnectionTransport", () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ const options = {+ url: () => "http://localhost/ws",+ headers: () => ({}),+ };++ it("uses BasicTransport for static notebooks", () => {+ const transport = createConnectionTransport({+ ...options,+ static: true,+ transportType: "websocket",+ });+ expect(transport).toBeInstanceOf(BasicTransport);+ });++ it("uses WsTransport by default", () => {+ const transport = createConnectionTransport({+ ...options,+ static: false,+ transportType: "websocket",+ });+ expect(transport).toBeInstanceOf(WsTransport);+ });++ it("uses SseTransport when the transport type is sse", () => {+ const transport = createConnectionTransport({+ ...options,+ static: false,+ transportType: "sse",+ });+ expect(transport).toBeInstanceOf(SseTransport);+ });+});diff --git a/frontend/src/core/websocket/transports/__tests__/sse.test.ts b/frontend/src/core/websocket/transports/__tests__/sse.test.tsnew file mode 100644index 0000000000..208ce62b4b--- /dev/null+++ b/frontend/src/core/websocket/transports/__tests__/sse.test.ts@@ -0,0 +1,338 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { SseTransport } from "../sse";+import { MAX_RETRIES, TRANSPORT_EXHAUSTED_REASON } from "../ws";++const encoder = new TextEncoder();++function createControllableStream() {+ let controller!: ReadableStreamDefaultController<Uint8Array>;+ const stream = new ReadableStream<Uint8Array>({+ start(c) {+ controller = c;+ },+ });+ return {+ stream,+ push: (text: string) => controller.enqueue(encoder.encode(text)),+ end: () => controller.close(),+ };+}++function sseResponse(body: ReadableStream<Uint8Array> | null, status = 200) {+ return {+ ok: status >= 200 && status < 300,+ status,+ body,+ } as Response;+}++describe("SseTransport", () => {+ let transport: SseTransport;+ let fetchMock: ReturnType<typeof vi.fn>;+ let opens: Event[];+ let messages: MessageEvent[];+ let closes: CloseEvent[];+ let errors: Event[];++ beforeEach(() => {+ fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);+ transport = new SseTransport(() => "http://example.invalid/sse");+ opens = [];+ messages = [];+ closes = [];+ errors = [];+ transport.addEventListener("open", (e) => opens.push(e));+ transport.addEventListener("message", (e) => messages.push(e));+ transport.addEventListener("close", (e) => closes.push(e));+ transport.addEventListener("error", (e) => errors.push(e));+ });++ afterEach(() => {+ transport.close();+ vi.unstubAllGlobals();+ vi.useRealTimers();+ });++ it("starts closed and connects on reconnect()", async () => {+ expect(transport.readyState).toBe(WebSocket.CLOSED);+ const { stream } = createControllableStream();+ fetchMock.mockResolvedValueOnce(sseResponse(stream));++ transport.reconnect();+ expect(transport.readyState).toBe(WebSocket.CONNECTING);+ await vi.waitFor(() => expect(opens).toHaveLength(1));+ expect(transport.readyState).toBe(WebSocket.OPEN);+ expect(fetchMock).toHaveBeenCalledWith(+ "http://example.invalid/sse",+ expect.objectContaining({+ headers: { Accept: "text/event-stream" },+ }),+ );+ });++ it("dispatches message events, joining multi-line data", async () => {+ const { stream, push } = createControllableStream();+ fetchMock.mockResolvedValueOnce(sseResponse(stream));+ transport.reconnect();+ await vi.waitFor(() => expect(opens).toHaveLength(1));++ push('data: {"op": "alert"}\n\n');+ await vi.waitFor(() => expect(messages).toHaveLength(1));+ expect(messages[0].data).toBe('{"op": "alert"}');++ // Multi-line data and records split across chunks+ push("data: line1\nda");+ push("ta: line2\n\n");+ await vi.waitFor(() => expect(messages).toHaveLength(2));+ expect(messages[1].data).toBe("line1\nline2");+ });++ it("ignores keep-alive comments", async () => {+ const { stream, push } = createControllableStream();+ fetchMock.mockResolvedValueOnce(sseResponse(stream));+ transport.reconnect();+ await vi.waitFor(() => expect(opens).toHaveLength(1));++ push(": keep-alive\n\n");+ push("data: after\n\n");+ await vi.waitFor(() => expect(messages).toHaveLength(1));+ expect(messages[0].data).toBe("after");+ });++ it("surfaces a server close event with its code and reason", async () => {+ const { stream, push } = createControllableStream();+ fetchMock.mockResolvedValueOnce(sseResponse(stream));+ transport.reconnect();+ await vi.waitFor(() => expect(opens).toHaveLength(1));++ // Stop retrying when the consumer treats the close as terminal,+ // mirroring useMarimoKernelConnection's terminal path.+ transport.addEventListener("close", () => transport.close());+ push('event: close\ndata: {"code": 1000, "reason": "MARIMO_SHUTDOWN"}\n\n');+ await vi.waitFor(() => expect(closes).toHaveLength(1));+ expect(closes[0].code).toBe(1000);+ expect(closes[0].reason).toBe("MARIMO_SHUTDOWN");+ expect(closes[0].wasClean).toBe(true);+ expect(transport.readyState).toBe(WebSocket.CLOSED);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it("emits an empty-reason close and retries when the stream ends", async () => {+ vi.useFakeTimers();+ const first = createControllableStream();+ fetchMock.mockResolvedValueOnce(sseResponse(first.stream));+ transport.reconnect();+ await vi.waitFor(() => expect(opens).toHaveLength(1));++ first.end();+ await vi.waitFor(() => expect(closes).toHaveLength(1));+ expect(closes[0].reason).toBe("");+ expect(closes[0].wasClean).toBe(false);++ // A retry is scheduled and reconnects+ const second = createControllableStream();+ fetchMock.mockResolvedValueOnce(sseResponse(second.stream));+ await vi.advanceTimersByTimeAsync(10_000);+ await vi.waitFor(() => expect(opens).toHaveLength(2));+ });++ it("does not stack its own retry when the consumer reconnects in onClose", async () => {+ vi.useFakeTimers();+ const first = createControllableStream();+ const second = createControllableStream();+ fetchMock+ .mockResolvedValueOnce(sseResponse(first.stream))+ .mockResolvedValueOnce(sseResponse(second.stream));+ // Mirror useMarimoKernelConnection's retry path: reconnect()+ // synchronously from inside the close handler.+ transport.addEventListener("close", () => transport.reconnect());++ transport.reconnect();+ await vi.waitFor(() => expect(opens).toHaveLength(1));++ first.end();+ await vi.waitFor(() => expect(opens).toHaveLength(2));++ // The superseded run must not schedule a second connection on top of+ // the consumer's reconnect.+ await vi.advanceTimersByTimeAsync(60_000);+ expect(fetchMock).toHaveBeenCalledTimes(2);++ // The consumer-driven connection is healthy+ second.push("data: alive\n\n");+ await vi.waitFor(() => expect(messages).toHaveLength(1));+ expect(transport.readyState).toBe(WebSocket.OPEN);+ });++ it("exhausts the retry budget when the server closes every connection", async () => {+ vi.useFakeTimers();+ // A server that accepts, immediately sends a close event, and never+ // delivers a message must not be retried forever.+ fetchMock.mockImplementation(() => {+ const { stream, push } = createControllableStream();+ push('event: close\ndata: {"code": 3000, "reason": "MARIMO_X"}\n\n');+ return Promise.resolve(sseResponse(stream));+ });++ transport.reconnect();+ for (let i = 0; i < MAX_RETRIES; i++) {+ await vi.advanceTimersByTimeAsync(15_000);+ }++ expect(closes.length).toBe(MAX_RETRIES);+ expect(closes.at(-1)?.reason).toBe(TRANSPORT_EXHAUSTED_REASON);+ const fetchCallsWhenExhausted = fetchMock.mock.calls.length;+ await vi.advanceTimersByTimeAsync(60_000);+ expect(fetchMock.mock.calls.length).toBe(fetchCallsWhenExhausted);+ });++ it("a delivered message resets the retry budget", async () => {+ vi.useFakeTimers();+ const first = createControllableStream();+ fetchMock.mockResolvedValueOnce(sseResponse(first.stream));+ transport.reconnect();+ await vi.waitFor(() => expect(opens).toHaveLength(1));+ first.push("data: healthy\n\n");+ await vi.waitFor(() => expect(messages).toHaveLength(1));++ first.end();+ await vi.waitFor(() => expect(closes).toHaveLength(1));+ // Budget was reset by the message, so this close is retry #1, not+ // an exhaustion.+ expect(closes[0].reason).toBe("");+ });++ it("gives up with TRANSPORT_EXHAUSTED_REASON after MAX_RETRIES failures", async () => {+ vi.useFakeTimers();+ fetchMock.mockRejectedValue(new Error("connection refused"));++ transport.reconnect();+ for (let i = 0; i < MAX_RETRIES; i++) {+ await vi.advanceTimersByTimeAsync(15_000);+ }++ expect(closes.length).toBe(MAX_RETRIES);+ expect(closes.at(-1)?.reason).toBe(TRANSPORT_EXHAUSTED_REASON);+ expect(errors.length).toBe(MAX_RETRIES);+ const fetchCallsWhenExhausted = fetchMock.mock.calls.length;++ // No further retries once exhausted+ await vi.advanceTimersByTimeAsync(60_000);+ expect(fetchMock.mock.calls.length).toBe(fetchCallsWhenExhausted);++ // A manual reconnect() resets the budget+ const { stream } = createControllableStream();+ fetchMock.mockResolvedValueOnce(sseResponse(stream));+ transport.reconnect();+ await vi.waitFor(() => expect(opens).toHaveLength(1));+ });++ it("close() aborts the connection and cancels retries", async () => {+ vi.useFakeTimers();+ const { stream } = createControllableStream();+ fetchMock.mockResolvedValueOnce(sseResponse(stream));+ transport.reconnect();+ await vi.waitFor(() => expect(opens).toHaveLength(1));++ transport.close();+ expect(transport.readyState).toBe(WebSocket.CLOSED);+ // No close event is dispatched for a user-initiated close, and no+ // retry is scheduled.+ await vi.advanceTimersByTimeAsync(60_000);+ expect(closes).toHaveLength(0);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it("treats a non-2xx response as a connection failure", async () => {+ vi.useFakeTimers();+ fetchMock.mockResolvedValueOnce(sseResponse(null, 500));+ transport.reconnect();++ await vi.waitFor(() => expect(closes).toHaveLength(1));+ expect(opens).toHaveLength(0);+ expect(errors).toHaveLength(1);+ expect(closes[0].reason).toBe("");+ });++ it("sends provided headers (auth) with the request", async () => {+ const withHeaders = new SseTransport(+ () => "http://example.invalid/sse",+ () => ({ Authorization: "Bearer token123" }),+ );+ const { stream } = createControllableStream();+ fetchMock.mockResolvedValueOnce(sseResponse(stream));+ withHeaders.reconnect();+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalled());+ withHeaders.close();++ expect(fetchMock).toHaveBeenCalledWith(+ "http://example.invalid/sse",+ expect.objectContaining({+ headers: {+ Authorization: "Bearer token123",+ Accept: "text/event-stream",+ },+ }),+ );+ });++ it("aborts a connection attempt that exceeds the timeout", async () => {+ vi.useFakeTimers();+ // fetch that only settles when aborted+ fetchMock.mockImplementation(+ (_url: string, init: RequestInit) =>+ new Promise((_, reject) => {+ init.signal?.addEventListener("abort", () =>+ reject(new Error("aborted")),+ );+ }),+ );++ transport.reconnect();+ await vi.advanceTimersByTimeAsync(11_000);+ expect(errors).toHaveLength(1);+ expect(closes).toHaveLength(1);+ expect(closes[0].reason).toBe("");+ });++ it("reconnect() mid-stream supersedes the old connection silently", async () => {+ const first = createControllableStream();+ const second = createControllableStream();+ fetchMock+ .mockResolvedValueOnce(sseResponse(first.stream))+ .mockResolvedValueOnce(sseResponse(second.stream));++ transport.reconnect();+ await vi.waitFor(() => expect(opens).toHaveLength(1));++ transport.reconnect();+ await vi.waitFor(() => expect(opens).toHaveLength(2));++ // The aborted first connection must not surface close/error events+ second.push("data: alive\n\n");+ await vi.waitFor(() => expect(messages).toHaveLength(1));+ expect(closes).toHaveLength(0);+ expect(errors).toHaveLength(0);+ });++ it("send() is a no-op", () => {+ expect(() => transport.send("data")).not.toThrow();+ });++ it("dedupes repeated addEventListener calls", async () => {+ const { stream, push } = createControllableStream();+ fetchMock.mockResolvedValueOnce(sseResponse(stream));+ const onMessage = (e: MessageEvent) => messages.push(e);+ transport.addEventListener("message", onMessage);+ transport.addEventListener("message", onMessage);+ transport.reconnect();+ await vi.waitFor(() => expect(opens).toHaveLength(1));++ push("data: once\n\n");+ // The beforeEach listener plus the deduped listener = 2 events+ await vi.waitFor(() => expect(messages).toHaveLength(2));+ });+});diff --git a/frontend/src/core/websocket/transports/sse.ts b/frontend/src/core/websocket/transports/sse.tsnew file mode 100644index 0000000000..6adb4e52f8--- /dev/null+++ b/frontend/src/core/websocket/transports/sse.ts@@ -0,0 +1,308 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { Logger } from "@/utils/Logger";+import {+ type ConnectionEvent,+ ConnectionSubscriptions,+ type ConnectionTransportCallback,+ type IConnectionTransport,+} from "./transport";+import { MAX_RETRIES, TRANSPORT_EXHAUSTED_REASON } from "./ws";++// Mirrors WsTransport/partysocket retry behavior.+const CONNECTION_TIMEOUT_MS = 10_000;+const MIN_RETRY_DELAY_MS = 1000;+const MAX_RETRY_DELAY_MS = 10_000;+const RETRY_GROWTH_FACTOR = 1.3;++// Stream ended without a server close event (transient disconnect); matches+// the WebSocket abnormal-closure code so close handling stays uniform.+const ABNORMAL_CLOSURE = 1006;++interface ServerClose {+ code: number;+ reason: string;+}++/**+ * A kernel-connection transport over server-sent events, used when+ * `server.transport` is `"sse"` (experimental).+ *+ * The kernel connection only carries messages server to client (control+ * requests go over HTTP POST), so an SSE stream can fully replace the+ * WebSocket. The server mirrors WebSocket close frames with a `close` SSE+ * event carrying `{code, reason}`; a stream that ends without one is a+ * transient disconnect.+ *+ * Uses `fetch` + stream parsing rather than `EventSource`: we need to+ * surface server close reasons, send auth headers, and match partysocket's+ * retry semantics (per-`reconnect()` retry budget, exhaustion surfaced via+ * `TRANSPORT_EXHAUSTED_REASON`), none of which `EventSource` supports.+ *+ * Like `WsTransport`, starts closed; the first `reconnect()` connects.+ * `close()` stops retrying and does not dispatch a close event.+ */+export class SseTransport implements IConnectionTransport {+ private subscriptions = new ConnectionSubscriptions();+ private urlProvider: () => string;+ private headersProvider: () => Record<string, string>;+ private abortController: AbortController | null = null;+ private retryTimer: ReturnType<typeof setTimeout> | null = null;+ private retryCount = 0;+ private userClosed = false;+ private state: WebSocket["readyState"] = WebSocket.CLOSED;++ constructor(+ urlProvider: () => string,+ headersProvider: () => Record<string, string> = () => ({}),+ ) {+ this.urlProvider = urlProvider;+ this.headersProvider = headersProvider;+ }++ get readyState(): WebSocket["readyState"] {+ return this.state;+ }++ reconnect(_code?: number, _reason?: string): void {+ this.userClosed = false;+ this.retryCount = 0;+ this.clearRetryTimer();+ this.abortController?.abort();+ this.connect();+ }++ close(): void {+ this.userClosed = true;+ this.clearRetryTimer();+ this.state = WebSocket.CLOSED;+ this.abortController?.abort();+ this.abortController = null;+ }++ send(_data: string | ArrayBuffer | Blob | ArrayBufferView): void {+ // The kernel connection is receive-only; all client requests go over+ // HTTP POST endpoints.+ Logger.warn("SseTransport does not support send(); dropping message");+ }++ addEventListener<T extends ConnectionEvent>(+ event: T,+ callback: ConnectionTransportCallback<T>,+ ): void {+ this.subscriptions.addSubscription(+ event,+ callback as ConnectionTransportCallback<ConnectionEvent>,+ );+ }++ removeEventListener<T extends ConnectionEvent>(+ event: T,+ callback: ConnectionTransportCallback<T>,+ ): void {+ this.subscriptions.removeSubscription(+ event,+ callback as ConnectionTransportCallback<ConnectionEvent>,+ );+ }++ private connect(): void {+ this.state = WebSocket.CONNECTING;+ void this.run();+ }++ private async run(): Promise<void> {+ const controller = new AbortController();+ this.abortController = controller;+ // Long timeout — the server can become slow when many notebooks are open.+ const connectTimeout = setTimeout(+ () => controller.abort(),+ CONNECTION_TIMEOUT_MS,+ );++ let serverClose: ServerClose | null = null;+ try {+ const response = await fetch(this.urlProvider(), {+ headers: {+ ...this.headersProvider(),+ Accept: "text/event-stream",+ },+ signal: controller.signal,+ });+ clearTimeout(connectTimeout);+ if (!response.ok || response.body === null) {+ throw new Error(`Unexpected SSE response: ${response.status}`);+ }++ this.state = WebSocket.OPEN;+ this.subscriptions.notify("open", new Event("open"));++ serverClose = await this.readEvents(response.body);+ } catch (error) {+ clearTimeout(connectTimeout);+ if (this.isSuperseded(controller)) {+ return;+ }+ Logger.warn("SSE connection failed", error);+ this.subscriptions.notify("error", new Event("error"));+ }++ if (this.isSuperseded(controller)) {+ return;+ }+ controller.abort();+ this.state = WebSocket.CLOSED;++ // The retry budget counts consecutive attempts without a healthy+ // stream (readEvents resets it on the first message), so a server+ // that accepts and immediately closes still exhausts the budget.+ this.retryCount += 1;+ const exhausted = this.retryCount >= MAX_RETRIES;+ this.subscriptions.notify(+ "close",+ new CloseEvent("close", {+ code: serverClose?.code ?? ABNORMAL_CLOSURE,+ // On exhaustion the reason is rewritten so the consumer stops+ // retrying, matching WsTransport.+ reason: exhausted+ ? TRANSPORT_EXHAUSTED_REASON+ : (serverClose?.reason ?? ""),+ wasClean: serverClose !== null,+ }),+ );+ // The consumer's close handler runs synchronously inside notify and+ // may have called reconnect() (starting a fresh connection) or+ // close(); re-check before scheduling our own retry so we never+ // stack a second connection on top of theirs.+ if (exhausted || this.isSuperseded(controller)) {+ return;+ }+ this.scheduleRetry();+ }++ /** Whether this run was replaced by a newer reconnect() or close(). */+ private isSuperseded(controller: AbortController): boolean {+ return this.userClosed || this.abortController !== controller;+ }++ private scheduleRetry(): void {+ this.clearRetryTimer();+ this.state = WebSocket.CONNECTING;+ const delay = Math.min(+ MIN_RETRY_DELAY_MS * RETRY_GROWTH_FACTOR ** this.retryCount,+ MAX_RETRY_DELAY_MS,+ );+ this.retryTimer = setTimeout(() => {+ this.retryTimer = null;+ this.connect();+ }, delay);+ }++ private clearRetryTimer(): void {+ if (this.retryTimer !== null) {+ clearTimeout(this.retryTimer);+ this.retryTimer = null;+ }+ }++ /**+ * Read and dispatch SSE events until the stream ends.+ *+ * Returns the server close payload if a `close` event arrives, or null+ * if the stream ends without one.+ */+ private async readEvents(+ body: ReadableStream<Uint8Array>,+ ): Promise<ServerClose | null> {+ const reader = body.getReader();+ const decoder = new TextDecoder();+ let buffer = "";+ let eventName: string | null = null;+ let dataLines: string[] = [];++ const dispatch = (): ServerClose | null => {+ if (dataLines.length === 0) {+ eventName = null;+ return null;+ }+ const data = dataLines.join("\n");+ const name = eventName;+ eventName = null;+ dataLines = [];+ if (name === "close") {+ return parseServerClose(data);+ }+ // A message means the stream is healthy: reset the retry budget+ // (rather than on open, so a server that accepts and immediately+ // closes cannot retry forever).+ this.retryCount = 0;+ this.subscriptions.notify(+ "message",+ new MessageEvent("message", { data }),+ );+ return null;+ };++ while (true) {+ const { done, value } = await reader.read();+ if (done) {+ return null;+ }+ buffer += decoder.decode(value, { stream: true });++ // Consume complete lines with a cursor; a single tail slice per+ // read keeps parsing linear even for many buffered lines.+ let cursor = 0;+ let newlineIndex = buffer.indexOf("\n", cursor);+ while (newlineIndex !== -1) {+ let line = buffer.slice(cursor, newlineIndex);+ cursor = newlineIndex + 1;+ newlineIndex = buffer.indexOf("\n", cursor);+ if (line.endsWith("\r")) {+ line = line.slice(0, -1);+ }++ if (line === "") {+ const serverClose = dispatch();+ if (serverClose !== null) {+ return serverClose;+ }+ continue;+ }+ if (line.startsWith(":")) {+ // Comment (keep-alive)+ continue;+ }++ const colonIndex = line.indexOf(":");+ const field = colonIndex === -1 ? line : line.slice(0, colonIndex);+ let fieldValue = colonIndex === -1 ? "" : line.slice(colonIndex + 1);+ if (fieldValue.startsWith(" ")) {+ fieldValue = fieldValue.slice(1);+ }+ if (field === "data") {+ dataLines.push(fieldValue);+ } else if (field === "event") {+ eventName = fieldValue;+ }+ // `id` and `retry` fields are unused.+ }+ if (cursor > 0) {+ buffer = buffer.slice(cursor);+ }+ }+ }+}++function parseServerClose(data: string): ServerClose {+ try {+ const parsed = JSON.parse(data) as Partial<ServerClose>;+ return {+ code: typeof parsed.code === "number" ? parsed.code : 1000,+ reason: typeof parsed.reason === "string" ? parsed.reason : "",+ };+ } catch {+ Logger.warn("Failed to parse SSE close event", data);+ return { code: 1000, reason: "" };+ }+}diff --git a/frontend/src/core/websocket/useMarimoKernelConnection.tsx b/frontend/src/core/websocket/useMarimoKernelConnection.tsxindex f023013ee1..28d32e6756 100644--- a/frontend/src/core/websocket/useMarimoKernelConnection.tsx+++ b/frontend/src/core/websocket/useMarimoKernelConnection.tsx@@ -1,6 +1,6 @@/* Copyright 2026 Marimo. All rights reserved. */-import { useAtom, useSetAtom } from "jotai";+import { useAtom, useAtomValue, useSetAtom } from "jotai";import { useRef } from "react";import { useErrorBoundary } from "react-error-boundary";import { toast } from "@/components/ui/use-toast";@@ -38,7 +38,7 @@ import {} from "../codemirror/cells/debugger-state";import type { CellData } from "../cells/types";import { capabilitiesAtom } from "../config/capabilities";-import { useSetAppConfig } from "../config/config";+import { connectionTransportTypeAtom, useSetAppConfig } from "../config/config";import { useDataSourceActions } from "../datasets/data-source-connections";import type { ConnectionName } from "../datasets/engines";import {@@ -84,13 +84,18 @@ const SUPPORTS_LAZY_KERNELS = true;// All MARIMO_* reasons except TRANSPORT_EXHAUSTED are emitted by the backend// (marimo/_server/api/endpoints/ws_endpoint.py and ws/*.py). Keep in sync with-// the backend literals.+// the backend literals. Over the SSE transport these arrive as in-band+// `close` events rather than WebSocket close frames, so every terminal+// reason must be classified here — an unclassified reason falls into the+// retry path.export type CloseReason =| "MARIMO_NO_FILE_KEY"| "MARIMO_NO_SESSION_ID"| "MARIMO_NO_SESSION"| "MARIMO_SHUTDOWN"| "MARIMO_KERNEL_STARTUP_ERROR"+ | "MARIMO_UNAUTHORIZED"+ | "MARIMO_KIOSK_NOT_ALLOWED"| typeof TRANSPORT_EXHAUSTED_REASON;export type CloseDecision =@@ -122,6 +127,26 @@ export function classifyCloseEvent(event: { reason?: string }): CloseDecision {},closeTransport: true,};+ case "MARIMO_UNAUTHORIZED":+ return {+ kind: "terminal",+ status: {+ state: WebSocketState.CLOSED,+ code: WebSocketClosedReason.KERNEL_DISCONNECTED,+ reason: "not authorized",+ },+ closeTransport: true,+ };+ case "MARIMO_KIOSK_NOT_ALLOWED":+ return {+ kind: "terminal",+ status: {+ state: WebSocketState.CLOSED,+ code: WebSocketClosedReason.KERNEL_DISCONNECTED,+ reason: "kiosk mode is not available for this session",+ },+ closeTransport: true,+ };case "MARIMO_KERNEL_STARTUP_ERROR":return {kind: "terminal",@@ -198,6 +223,7 @@ export function useMarimoKernelConnection(opts: {const setKioskMode = useSetAtom(kioskModeAtom);const setCapabilities = useSetAtom(capabilitiesAtom);const runtimeManager = useRuntimeManager();+ const transportType = useAtomValue(connectionTransportTypeAtom);const setCacheInfo = useSetAtom(cacheInfoAtom);const setKernelStartupError = useSetAtom(kernelStartupErrorAtom);const setDebuggerCurrentLine = useSetAtom(debuggerCurrentLineAtom);@@ -456,10 +482,19 @@ export function useMarimoKernelConnection(opts: {const ws = useConnectionTransport({static: isStaticNotebook(),+ transportType,/*** Unique URL for this session.*/- url: () => runtimeManager.getWsURL(sessionId).toString(),+ url: () =>+ transportType === "sse"+ ? runtimeManager.getSseURL(sessionId).toString()+ : runtimeManager.getWsURL(sessionId).toString(),+ /**+ * Auth headers for the SSE transport. WebSockets cannot send headers+ * and instead put the access token in the URL.+ */+ headers: () => runtimeManager.headers(),/*** Open callback. Set the connection status to open.diff --git a/frontend/src/core/websocket/useWebSocket.tsx b/frontend/src/core/websocket/useWebSocket.tsxindex 99cffc21f7..48e12823fe 100644--- a/frontend/src/core/websocket/useWebSocket.tsx+++ b/frontend/src/core/websocket/useWebSocket.tsx@@ -5,12 +5,16 @@ import { Logger } from "@/utils/Logger";import { createPyodideConnection } from "../wasm/bridge";import { isWasm } from "../wasm/utils";import { BasicTransport } from "./transports/basic";+import { SseTransport } from "./transports/sse";import { WsTransport } from "./transports/ws";import type { IConnectionTransport } from "./transports/transport";interface UseConnectionTransportOptions {url: () => string;static: boolean;+ transportType: "websocket" | "sse";+ /** Request headers for the SSE transport (auth); unused by WebSockets. */+ headers: () => Record<string, string>;waitToConnect: () => Promise<void>;onOpen: (event: WebSocketEventMap["open"]) => void;onMessage: (event: WebSocketEventMap["message"]) => void;@@ -18,8 +22,11 @@ interface UseConnectionTransportOptions {onError: (event: WebSocketEventMap["error"]) => void;}-function createConnectionTransport(- options: Pick<UseConnectionTransportOptions, "url" | "static">,+export function createConnectionTransport(+ options: Pick<+ UseConnectionTransportOptions,+ "url" | "static" | "transportType" | "headers"+ >,): IConnectionTransport {if (options.static) {return BasicTransport.empty();@@ -28,6 +35,9 @@ function createConnectionTransport(return createPyodideConnection();}// urlProvider is passed lazily; it may change after a runtime redirect.+ if (options.transportType === "sse") {+ return new SseTransport(options.url, options.headers);+ }return new WsTransport(options.url);}diff --git a/marimo/_config/config.py b/marimo/_config/config.pyindex 3696b9cb79..b795f27b9c 100644--- a/marimo/_config/config.py+++ b/marimo/_config/config.py@@ -248,11 +248,20 @@ class ServerConfig(TypedDict):inside its static assets directory.- `disable_file_downloads`: if true, the file download button will behidden in the file explorer.+ - `transport`: experimental. The transport used to stream kernel+ messages to the frontend, typically set with the+ `MARIMO_SERVER_TRANSPORT` environment variable. `"websocket"`+ (default) uses the `/ws` WebSocket endpoint; `"sse"` uses+ server-sent events over HTTP, for deployments behind proxies or+ services that do not support WebSockets. Terminal, LSP, and+ real-time collaboration still require WebSockets; RTC is disabled+ when using `"sse"`."""browser: Literal["default"] | strfollow_symlink: booldisable_file_downloads: NotRequired[bool]+ transport: NotRequired[Literal["websocket", "sse"]]@dataclassdiff --git a/marimo/_config/manager.py b/marimo/_config/manager.pyindex eadda8c281..548bd90f13 100644--- a/marimo/_config/manager.py+++ b/marimo/_config/manager.py@@ -329,12 +329,24 @@ class ProjectConfigManager(PartialMarimoConfigReader):class EnvConfigManager(PartialMarimoConfigReader):def _maybe_override_from_env(- self, key: str, path: list[str], config: PartialMarimoConfig+ self,+ key: str,+ path: list[str],+ config: PartialMarimoConfig,+ allowed_values: tuple[Any, ...] | None = None,) -> None:loaded_value = env_to_value(key)if not isinstance(loaded_value, tuple):returnvalue = loaded_value[0]+ if allowed_values is not None and value not in allowed_values:+ LOGGER.warning(+ "Ignoring invalid value %r for %s; expected one of %s",+ value,+ key,+ ", ".join(map(repr, allowed_values)),+ )+ returncurrent = cast(dict[str, Any], config)for p in path[:-1]:@@ -354,6 +366,12 @@ class EnvConfigManager(PartialMarimoConfigReader):["runtime", "auto_instantiate"],project_config,)+ self._maybe_override_from_env(+ "MARIMO_SERVER_TRANSPORT",+ ["server", "transport"],+ project_config,+ allowed_values=("websocket", "sse"),+ )if hide_secrets:return mask_secrets_partial(project_config)return project_configdiff --git a/marimo/_server/api/endpoints/execution.py b/marimo/_server/api/endpoints/execution.pyindex 0fb3591db4..2f01c17c75 100644--- a/marimo/_server/api/endpoints/execution.py+++ b/marimo/_server/api/endpoints/execution.py@@ -39,6 +39,7 @@ from marimo._server.models.models import (UpdateUIElementValuesRequest,)from marimo._server.router import APIRouter+from marimo._server.sse import wait_for_http_disconnectfrom marimo._server.uvicorn_utils import close_uvicornfrom marimo._server.workspace import MarimoFileKeyfrom marimo._session.consumer_policy import (@@ -345,15 +346,8 @@ async def execute_code(async def _watch_disconnect() -> None:"""Wait for client disconnect and interrupt the kernel."""- while True:- # request._receive is the ASGI `receive` callable. Although- # it's a private Starlette attribute, it's the standard way to- # detect disconnects and doesn't race with StreamingResponse- # (which only writes to the send channel, never reads receive).- message = await request._receive()- if message.get("type") == "http.disconnect":- session.try_interrupt()- return+ await wait_for_http_disconnect(request)+ session.try_interrupt()async def sse_generator() -> AsyncGenerator[str, None]:disconnect_task = asyncio.create_task(_watch_disconnect())@@ -390,6 +384,12 @@ async def execute_code(yield eventyield build_done_event(session, listener)+ except asyncio.CancelledError:+ # On ASGI spec < 2.4, Starlette consumes http.disconnect+ # itself and cancels this generator before _watch_disconnect+ # observes it; still interrupt the kernel on the way out.+ session.try_interrupt()+ raisefinally:await cancel_and_wait(disconnect_task)diff --git a/marimo/_server/api/endpoints/ws/session_handler.py b/marimo/_server/api/endpoints/ws/session_handler.pynew file mode 100644index 0000000000..400645b4c8--- /dev/null+++ b/marimo/_server/api/endpoints/ws/session_handler.py@@ -0,0 +1,425 @@+# Copyright 2026 Marimo. All rights reserved.+"""Transport-agnostic session handling shared by WebSocket and SSE."""++from __future__ import annotations++import abc+import asyncio+from typing import TYPE_CHECKING++from marimo import _loggers+from marimo._cli.upgrade import check_for_updates+from marimo._config.settings import GLOBAL_SETTINGS+from marimo._messaging.notification import (+ AlertNotification,+ BannerNotification,+ NotificationMessage,+ ReconnectedNotification,+)+from marimo._messaging.serde import 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_session_connector import (+ SessionConnector,+ is_viewer_connection,+)+from marimo._server.codes import WebSocketCloseReason, WebSocketCodes+from marimo._session.consumer import SessionConsumer+from marimo._session.model import ConnectionState, SessionMode+from marimo._types.ids import ConsumerId++if TYPE_CHECKING:+ from collections.abc import Callable+ from typing import Any++ from starlette.requests import HTTPConnection++ from marimo._config.cli_state import MarimoCLIState+ from marimo._messaging.types import KernelMessage+ from marimo._plugins.core.web_component import JSONType+ 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.rtc.doc import LoroDocManager+ from marimo._server.session_manager import SessionManager+ from marimo._session import Session+ from marimo._session.events import SessionEventBus+ from marimo._types.ids import CellId_t++LOGGER = _loggers.marimo_logger()+++class SessionHandler(SessionConsumer, abc.ABC):+ """Base consumer that sessions use to send messages to frontends.++ Owns the transport-agnostic session lifecycle: connecting (new, resume,+ reconnect, kiosk), the kernel-ready handshake, message replay, and+ TTL-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`.+ """++ def __init__(+ self,+ *,+ manager: SessionManager,+ params: ConnectionParams,+ mode: SessionMode,+ doc_manager: LoroDocManager,+ ):+ self.manager = manager+ self.params = params+ self.mode = mode+ self.doc_manager = doc_manager+ self.status: ConnectionState+ self.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()+ self._consumer_id = ConsumerId(params.session_id)++ @property+ def consumer_id(self) -> ConsumerId:+ return self._consumer_id++ # Transport surface, implemented per transport++ @abc.abstractmethod+ def _request_close(self, code: int, reason: str) -> None:+ """Ask the transport to close with the given code and reason.++ Must not block; called from synchronous session callbacks.+ """++ @abc.abstractmethod+ 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++ def _connect_session(+ self, connection: HTTPConnection+ ) -> tuple[Session, ConnectionType]:+ """Connect this handler to a session (new, resume, reconnect, ...).++ Raises:+ KernelStartupError: If the kernel fails to start.+ WebSocketDisconnect: If the connection is rejected; carries the+ close code and reason.+ """+ return SessionConnector(+ manager=self.manager,+ handler=self,+ params=self.params,+ connection=connection,+ ).connect()++ def _is_viewer(+ self, session: Session, connection_type: ConnectionType+ ) -> bool:+ """Whether this consumer gets read-only (kiosk) message filtering."""+ return is_viewer_connection(+ connection_type=connection_type,+ is_main_consumer=session.room.main_consumer is self,+ )++ def notify(self, notification: KernelMessage) -> None:+ self.message_queue.put_nowait(notification)++ def _serialize_and_notify(self, notification: NotificationMessage) -> None:+ self.notify(serialize_kernel_message(notification))++ def _write_kernel_ready_from_session_view(+ self, session: Session, kiosk: bool+ ) -> None:+ """Write kernel ready message using current session view state."""+ self._write_kernel_ready(+ session=session,+ resumed=True,+ ui_values=session.session_view.ui_values,+ last_executed_code=session.session_view.last_executed_code,+ last_execution_time=session.session_view.last_execution_time,+ kiosk=kiosk,+ auto_instantiated=False,+ )++ def _write_kernel_ready(+ self,+ session: Session,+ resumed: bool,+ ui_values: dict[str, JSONType],+ last_executed_code: dict[CellId_t, str],+ last_execution_time: dict[CellId_t, float],+ kiosk: bool,+ auto_instantiated: bool,+ ) -> None:+ """Communicates to the client that the kernel is ready.++ Sends cell code and other metadata to client.++ Args:+ session: Current session+ resumed: Whether this is a resumed session+ ui_values: UI element values+ last_executed_code: Last executed code for each cell+ last_execution_time: Last execution time for each cell+ kiosk: Whether this is kiosk mode+ auto_instantiated: Whether the kernel has already been instantiated+ server-side (run mode). If True, the frontend does not need+ to instantiate the app.+ """+ # Only send execution data if sending code to frontend+ should_send = self.manager.should_send_code_to_frontend()++ # RTC is only enabled if configured AND Loro is available+ effective_rtc_enabled = self.params.rtc_enabled and is_rtc_available()++ # Build kernel ready message+ kernel_ready_msg = build_kernel_ready(+ session=session,+ manager=self.manager,+ resumed=resumed,+ ui_values=ui_values,+ last_executed_code=last_executed_code if should_send else {},+ last_execution_time=last_execution_time if should_send else {},+ kiosk=kiosk,+ rtc_enabled=effective_rtc_enabled,+ file_key=self.params.file_key,+ mode=self.mode,+ doc_manager=self.doc_manager,+ auto_instantiated=auto_instantiated,+ )+ self._serialize_and_notify(kernel_ready_msg)++ def _reconnect_session(self, session: Session, replay: bool) -> None:+ """Reconnect to an existing session (kernel).++ A connection can be closed when a user's computer goes to sleep,+ spurious network issues, etc.+ """+ # Cancel previous close handle+ if self.cancel_close_handle is not None:+ self.cancel_close_handle.cancel()++ self.status = ConnectionState.OPEN+ session.connect_consumer(self, main=True)++ # Write reconnected message+ self._serialize_and_notify(ReconnectedNotification())++ # If not replaying, just send a toast+ if not replay:+ self._serialize_and_notify(+ AlertNotification(+ title="Reconnected",+ description="You have reconnected to an existing session.",+ )+ )+ return++ self._write_kernel_ready_from_session_view(session, self.params.kiosk)+ self._serialize_and_notify(+ BannerNotification(+ title="Reconnected",+ description="You have reconnected to an existing session.",+ action="restart",+ )+ )++ self._replay_previous_session(session)++ def _connect_kiosk(self, session: Session) -> None:+ """Connect to a kiosk session.++ A kiosk session is a write-ish session that is connected to a+ frontend. It can set UI elements and interact with the sidebar,+ but cannot change or execute code. This is not a permission limitation,+ but rather we don't have full multi-player support yet.++ Kiosk mode is useful when the user is using an editor (VSCode or VIM)+ that does not easily support our reactive frontend or our panels.+ The user uses VSCode or VIM to write code, and the+ marimo kiosk/frontend to visualize the output.+ """++ session.connect_consumer(self, main=False)+ self.status = ConnectionState.CONNECTING+ self._write_kernel_ready_from_session_view(session, kiosk=True)+ self.status = ConnectionState.OPEN+ self._replay_previous_session(session)++ def _connect_to_existing_session(self, session: Session) -> None:+ """Connect to an existing session and replay all messages."""+ self.status = ConnectionState.CONNECTING+ session.connect_consumer(self, main=False)++ # Write kernel ready with current state+ self._write_kernel_ready_from_session_view(session, kiosk=False)+ self.status = ConnectionState.OPEN++ # Replay all operations+ self._replay_previous_session(session)++ def _replay_previous_session(self, session: Session) -> None:+ """Replay the previous session view."""+ notifications = session.session_view.notifications+ if len(notifications) == 0:+ LOGGER.debug("No notifications to replay")+ return+ LOGGER.debug(f"Replaying {len(notifications)} notifications")+ for notif in notifications:+ LOGGER.debug("Replaying notification %s", notif)+ self._serialize_and_notify(notif)++ def _on_disconnect(+ self,+ e: Exception,+ cleanup_fn: Callable[[], Any],+ ) -> None:+ LOGGER.debug(+ "Connection closed for session %s with exception %s, type %s",+ self.params.session_id,+ str(e),+ type(e),+ )++ # Change the status+ self.status = ConnectionState.CLOSED+ # Disconnect the consumer+ session = self.manager.get_session(self.params.session_id)+ if session:+ session.disconnect_consumer(self)++ # When the connection is closed, we wait session.ttl_seconds before+ # closing the session. This prevents the session from being closed+ # during intermittent network issues.+ # In RUN mode, this always applies (sessions always have a default+ # TTL even if the manager's ttl_seconds is None).+ # In EDIT mode, this only applies when --session-ttl is explicitly set.+ should_ttl_close = (+ self.manager.ttl_seconds is not None+ or self.mode == SessionMode.RUN+ )+ if should_ttl_close:++ def _close() -> None:+ if self.status != ConnectionState.OPEN:+ # Guard: if another consumer has taken over, the session+ # is alive.+ live = self.manager.get_session(self.params.session_id)+ if (+ live is not None+ and live.connection_state() == ConnectionState.OPEN+ ):+ LOGGER.debug(+ "Session %s has active consumer, skipping TTL close",+ self.params.session_id,+ )+ return+ LOGGER.debug(+ "Closing session %s (TTL EXPIRED)",+ self.params.session_id,+ )+ # wait until TTL is expired before calling the cleanup+ # function+ cleanup_fn()+ self.manager.close_session(self.params.session_id)++ if session is not None:+ cancellation_handle = asyncio.get_running_loop().call_later(+ session.ttl_seconds, _close+ )+ self.cancel_close_handle = cancellation_handle+ else:+ _close()+ else:+ cleanup_fn()++ def on_attach(self, session: Session, event_bus: SessionEventBus) -> None:+ del session+ del event_bus+ return++ def on_detach(self) -> None:+ # If the transport is open, send a close message+ is_connected = (+ self.status == ConnectionState.OPEN+ or self.status == ConnectionState.CONNECTING+ ) and self._is_transport_connected()+ if is_connected:+ self._request_close(+ WebSocketCodes.NORMAL_CLOSE, WebSocketCloseReason.SHUTDOWN+ )++ self._cancel_message_loop()++ def connection_state(self) -> ConnectionState:+ return self.status++ def _check_status_update(self) -> None:+ # Only check for updates if we're in edit mode+ if (+ not GLOBAL_SETTINGS.CHECK_STATUS_UPDATE+ or self.mode != SessionMode.EDIT+ ):+ return++ loop = asyncio.get_running_loop()++ def on_update(current_version: str, state: MarimoCLIState) -> None:+ # Runs on the worker thread; hop back to the event loop to+ # notify (the message queue is not thread-safe).++ # Let's only toast once per marimo server+ # so we can just store this in memory.+ # We still want to check for updates (which are debounced 24 hours)+ # but don't keep toasting.+ global has_toasted+ if has_toasted:+ return++ has_toasted = True++ title = (+ f"Update available {current_version} → {state.latest_version}"+ )+ release_url = "https://github.com/marimo-team/marimo/releases"++ # Build description with notices if present+ description = f"Check out the <a class='underline' target='_blank' href='{release_url}'>latest release on GitHub.</a>"++ if state.notices:+ notices_text = (+ "<br><br><strong>Recent updates:</strong><br>"+ + "<br>".join(f"• {notice}" for notice in state.notices)+ )+ description += notices_text++ loop.call_soon_threadsafe(+ self._serialize_and_notify,+ AlertNotification(title=title, description=description),+ )++ # check_for_updates does synchronous network I/O; run it off the+ # event loop so it never delays kernel messages.+ task = asyncio.create_task(+ asyncio.to_thread(check_for_updates, on_update)+ )+ _background_tasks.add(task)+ task.add_done_callback(_background_tasks.discard)+++has_toasted = False++# Strong refs so fire-and-forget tasks aren't GC'd mid-flight.+_background_tasks: set[asyncio.Task[None]] = set()diff --git a/marimo/_server/api/endpoints/ws/sse_handler.py b/marimo/_server/api/endpoints/ws/sse_handler.pynew file mode 100644index 0000000000..eb4e923ccb--- /dev/null+++ b/marimo/_server/api/endpoints/ws/sse_handler.py@@ -0,0 +1,220 @@+# 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 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:+ session, connection_type = self._connect_session(self.request)+ 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.+ self._stream_finished = True+ disconnect_task.cancel()+ heartbeat_task.cancel()+ if not self._close_requested:+ self._on_disconnect(+ ConnectionError("SSE client disconnected"),+ lambda: None,+ )++ 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 wait_for_http_disconnect(self.request)+ 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_connection_validator.py b/marimo/_server/api/endpoints/ws/ws_connection_validator.pyindex 83f3e01478..640543d4e0 100644--- a/marimo/_server/api/endpoints/ws/ws_connection_validator.py+++ b/marimo/_server/api/endpoints/ws/ws_connection_validator.py@@ -23,7 +23,7 @@ KIOSK_QUERY_PARAM_KEY = "kiosk"@dataclassclass ConnectionParams:- """Parameters extracted from WebSocket connection request."""+ """Parameters extracted from a session connection request."""session_id: SessionIdfile_key: MarimoFileKey@@ -32,6 +32,70 @@ class ConnectionParams:rtc_enabled: bool+@dataclass+class ConnectionRejection:+ """Why a session connection request was refused.++ Carries the WebSocket close code and reason; non-websocket transports+ translate these into their own close signal.+ """++ code: WebSocketCodes+ reason: WebSocketCloseReason+++def parse_connection_params(+ app_state: AppState, *, allow_rtc: bool = True+) -> ConnectionParams | ConnectionRejection:+ """Extract and validate session connection parameters.++ Transport-agnostic: reads query params and config from the request held+ by `app_state`.++ Args:+ app_state: App state wrapping the incoming HTTP or WebSocket request.+ allow_rtc: Whether the transport supports RTC. SSE cannot carry the+ `/ws_sync` document stream, so RTC is disabled for it.+ """+ # Extract session_id+ raw_session_id = app_state.query_params(SESSION_QUERY_PARAM_KEY)+ if raw_session_id is None:+ return ConnectionRejection(+ WebSocketCodes.NORMAL_CLOSE, WebSocketCloseReason.NO_SESSION_ID+ )++ session_id = SessionId(raw_session_id)++ # Extract file_key+ file_key: MarimoFileKey | None = (+ app_state.query_params(FILE_QUERY_PARAM_KEY)+ or app_state.session_manager.workspace.get_unique_file_key()+ )++ if file_key is None:+ return ConnectionRejection(+ WebSocketCodes.NORMAL_CLOSE, WebSocketCloseReason.NO_FILE_KEY+ )++ # Extract kiosk mode+ kiosk = app_state.query_params(KIOSK_QUERY_PARAM_KEY) == "true"++ # Extract config-based parameters+ config = app_state.config_manager_at_file(file_key).get_config()+ rtc_enabled = allow_rtc and config.get("experimental", {}).get(+ "rtc_v2", False+ )+ auto_instantiate = config["runtime"]["auto_instantiate"]++ return ConnectionParams(+ session_id=session_id,+ file_key=file_key,+ kiosk=kiosk,+ auto_instantiate=auto_instantiate,+ rtc_enabled=rtc_enabled,+ )++class WebSocketConnectionValidator:"""Validates and extracts connection parameters from WebSocket requests."""@@ -57,46 +121,16 @@ class WebSocketConnectionValidator:) -> ConnectionParams | None:"""Extract and validate connection parameters.+ Closes the socket on invalid parameters.+Returns:ConnectionParams if all parameters are valid, None otherwise."""- # Extract session_id- raw_session_id = self.app_state.query_params(SESSION_QUERY_PARAM_KEY)- if raw_session_id is None:- await self.websocket.close(- WebSocketCodes.NORMAL_CLOSE, WebSocketCloseReason.NO_SESSION_ID- )- return None-- session_id = SessionId(raw_session_id)-- # Extract file_key- file_key: MarimoFileKey | None = (- self.app_state.query_params(FILE_QUERY_PARAM_KEY)- or self.app_state.session_manager.workspace.get_unique_file_key()- )-- if file_key is None:- await self.websocket.close(- WebSocketCodes.NORMAL_CLOSE, WebSocketCloseReason.NO_FILE_KEY- )+ result = parse_connection_params(self.app_state)+ if isinstance(result, ConnectionRejection):+ await self.websocket.close(result.code, result.reason)return None-- # Extract kiosk mode- kiosk = self.app_state.query_params(KIOSK_QUERY_PARAM_KEY) == "true"-- # Extract config-based parameters- config = self.app_state.config_manager_at_file(file_key).get_config()- rtc_enabled = config.get("experimental", {}).get("rtc_v2", False)- auto_instantiate = config["runtime"]["auto_instantiate"]-- return ConnectionParams(- session_id=session_id,- file_key=file_key,- kiosk=kiosk,- auto_instantiate=auto_instantiate,- rtc_enabled=rtc_enabled,- )+ return resultasync def extract_file_key_only(self) -> MarimoFileKey | None:"""Extract only the file_key parameter (for RTC endpoint).diff --git a/marimo/_server/api/endpoints/ws/ws_formatter.py b/marimo/_server/api/endpoints/ws/ws_formatter.pyindex 59fd3836e9..2e72b707db 100644--- a/marimo/_server/api/endpoints/ws/ws_formatter.py+++ b/marimo/_server/api/endpoints/ws/ws_formatter.py@@ -1,8 +1,8 @@# Copyright 2026 Marimo. All rights reserved.-"""WebSocket message formatting utilities.+"""Wire-format utilities for kernel messages sent to the frontend.-This module handles the wire format for WebSocket transport:-wrapping serialized notification data with operation metadata.+Wraps serialized notification data with operation metadata. The wire+format is shared by the WebSocket and SSE transports."""from __future__ import annotations@@ -16,10 +16,9 @@ if TYPE_CHECKING:def format_wire_message(op: str, data: bytes) -> str:- """Format a serialized message for WebSocket transport.+ """Format a serialized message for transport to the frontend.- Wraps serialized notification data with operation metadata- for the WebSocket wire protocol.+ Wraps serialized notification data with operation metadata.Args:op: The operation name (e.g., "cell-op", "kernel-ready")@@ -31,10 +30,10 @@ def format_wire_message(op: str, data: bytes) -> str:return f'{{"op": "{op}", "data": {data.decode("utf-8")}}}'-def serialize_notification_for_websocket(+def serialize_notification_for_wire(notification: NotificationMessage,) -> str:- """Serialize and format a notification for WebSocket transport.+ """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.diff --git a/marimo/_server/api/endpoints/ws/ws_message_loop.py b/marimo/_server/api/endpoints/ws/ws_message_loop.pyindex 21ef55ea21..77cc266253 100644--- a/marimo/_server/api/endpoints/ws/ws_message_loop.py+++ b/marimo/_server/api/endpoints/ws/ws_message_loop.py@@ -33,6 +33,55 @@ KIOSK_EXCLUDED_OPERATIONS = {}+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", str(e))+ LOGGER.error("Message: %s", data)+ return None++class WebSocketMessageLoop:"""Handles the async message send/receive loops for WebSocket."""@@ -75,17 +124,8 @@ class WebSocketMessageLoop:"""Listen for messages from kernel and send to frontend."""while True:data = await self.message_queue.get()- op: str = deserialize_kernel_notification_name(data)-- if self._should_filter_operation(op):- continue-- # Serialize message- try:- text = format_wire_message(op, data)- except Exception as e:- LOGGER.error("Failed to deserialize message: %s", str(e))- LOGGER.error("Message: %s", data)+ text = prepare_wire_message(data, is_kiosk=self.is_kiosk())+ if text is None:continue# Send to WebSocket@@ -124,31 +164,6 @@ class WebSocketMessageLoop:LOGGER.error("Error listening for disconnect: %s", str(e))raise- def _should_filter_operation(self, op: str) -> bool:- """Determine if operation should be filtered based on kiosk mode.-- Args:- op: Operation name to check-- Returns:- True if the operation should be filtered (not sent), False- otherwise.- """- kiosk = self.is_kiosk()- if op in KIOSK_ONLY_OPERATIONS and not kiosk:- LOGGER.debug(- "Ignoring operation %s, not in kiosk mode",- op,- )- return True- if op in KIOSK_EXCLUDED_OPERATIONS and kiosk:- LOGGER.debug(- "Ignoring operation %s, in kiosk mode",- op,- )- return True- return False-def _cancel_messages_task(self) -> None:"""Cancel the messages task."""if (diff --git a/marimo/_server/api/endpoints/ws/ws_session_connector.py b/marimo/_server/api/endpoints/ws/ws_session_connector.pyindex 7de0ddd45e..6a43643edb 100644--- a/marimo/_server/api/endpoints/ws/ws_session_connector.py+++ b/marimo/_server/api/endpoints/ws/ws_session_connector.py@@ -7,12 +7,12 @@ from typing import TYPE_CHECKINGfrom marimo._session.consumer_policy import initial_capabilitiesif TYPE_CHECKING:- from starlette.websockets import WebSocket+ from starlette.requests import HTTPConnection+ from marimo._server.api.endpoints.ws.session_handler import SessionHandlerfrom marimo._server.api.endpoints.ws.ws_connection_validator import (ConnectionParams,)- from marimo._server.api.endpoints.ws_endpoint import WebSocketHandlerfrom marimo._server.session_manager import SessionManagerfrom marimo._session import Session@@ -59,14 +59,14 @@ class SessionConnector:def __init__(self,manager: SessionManager,- handler: WebSocketHandler,+ handler: SessionHandler,params: ConnectionParams,- websocket: WebSocket,+ connection: HTTPConnection,):self.manager = managerself.handler = handlerself.params = params- self.websocket = websocket+ self.connection = connectiondef connect(self) -> tuple[Session, ConnectionType]:"""Determine connection type and establish session connection.@@ -199,7 +199,7 @@ class SessionConnector:def _create_new_session(self) -> tuple[Session, ConnectionType]:"""Create a new session.- Grabs query params from the websocket and creates a new session+ Grabs query params from the connection and creates a new sessionwith the session manager."""@@ -225,9 +225,9 @@ class SessionConnector:return new_session, ConnectionType.NEWdef _extract_query_params(self) -> QueryParams:- """Extract query params from the websocket, filtering ignored keys."""+ """Extract query params from the connection, filtering ignored keys."""query_params = QueryParams({}, NoopStream())- for key, value in self.websocket.query_params.multi_items():+ for key, value in self.connection.query_params.multi_items():if key not in QueryParams.IGNORED_KEYS:query_params.append(key, value)return query_params@@ -257,5 +257,5 @@ class SessionConnector:values=[],auto_run=True,),- http_request=HTTPRequest.from_request(self.websocket),+ http_request=HTTPRequest.from_request(self.connection),)diff --git a/marimo/_server/api/endpoints/ws_endpoint.py b/marimo/_server/api/endpoints/ws_endpoint.pyindex ed544e856d..e1b091a65f 100644--- a/marimo/_server/api/endpoints/ws_endpoint.py+++ b/marimo/_server/api/endpoints/ws_endpoint.py@@ -3,61 +3,48 @@ from __future__ import annotationsimport asyncioimport sys-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING+from starlette.responses import StreamingResponsefrom starlette.websockets import WebSocket, WebSocketStatefrom marimo import _loggers-from marimo._cli.upgrade import check_for_updates-from marimo._config.cli_state import MarimoCLIState-from marimo._config.settings import GLOBAL_SETTINGSfrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._messaging.notification import (- AlertNotification,- BannerNotification,KernelStartupErrorNotification,- NotificationMessage,- ReconnectedNotification,)-from marimo._messaging.serde import serialize_kernel_message-from marimo._messaging.types import KernelMessage-from marimo._plugins.core.web_component import JSONType+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 (- ConnectionParams,+ ConnectionRejection,WebSocketConnectionValidator,+ parse_connection_params,)from marimo._server.api.endpoints.ws.ws_formatter import (- serialize_notification_for_websocket,-)-from marimo._server.api.endpoints.ws.ws_kernel_ready import (- build_kernel_ready,- is_rtc_available,+ 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 RTCWebSocketHandler-from marimo._server.api.endpoints.ws.ws_session_connector import (- SessionConnector,- is_viewer_connection,-)from marimo._server.codes import WebSocketCloseReason, WebSocketCodesfrom marimo._server.router import APIRouterfrom marimo._server.rtc.doc import LoroDocManager-from marimo._server.session_manager import SessionManager-from marimo._session import Session-from marimo._session.consumer import SessionConsumer-from marimo._session.events import SessionEventBus+from marimo._server.sse import SSE_HEADERS, format_close_eventfrom marimo._session.managers.ipc import KernelStartupError-from marimo._session.model import (- ConnectionState,- SessionMode,-)-from marimo._types.ids import CellId_t, ConsumerId+from marimo._session.model import SessionModeif TYPE_CHECKING:- from collections.abc import Callable+ from collections.abc import AsyncGenerator++ from starlette.requests import Request++ from marimo._server.api.endpoints.ws.ws_connection_validator import (+ ConnectionParams,+ )+ from marimo._server.session_manager import SessionManagerLOGGER = _loggers.marimo_logger()@@ -102,6 +89,74 @@ async def websocket_endpoint().start()+def _sse_response(events: AsyncGenerator[str, None]) -> StreamingResponse:+ return StreamingResponse(+ events, media_type="text/event-stream", headers=SSE_HEADERS+ )+++def _close_only_stream(code: int, reason: str) -> StreamingResponse:+ """A stream carrying just a `close` event.++ Connection errors are delivered in-band (over an HTTP 200 stream) so+ the frontend handles them through the same close-reason path as+ WebSocket close frames.+ """++ async def gen() -> AsyncGenerator[str, None]:+ yield format_close_event(code, reason)++ return _sse_response(gen())++[email protected]("/sse", include_in_schema=False)+async def sse_endpoint(request: Request) -> StreamingResponse:+ """Experimental SSE alternative to the main `/ws` endpoint.++ Enabled with `server.transport = "sse"`. Streams kernel messages as+ server-sent events; control requests flow through the regular HTTP+ POST endpoints.++ responses:+ 200:+ description: Kernel messages as a server-sent event stream+ content:+ text/event-stream:+ schema:+ type: string+ """+ app_state = AppState(request)++ # Validate authentication before proceeding+ if app_state.enable_auth and not validate_auth(request):+ return _close_only_stream(+ WebSocketCodes.UNAUTHORIZED, WebSocketCloseReason.UNAUTHORIZED+ )++ # Extract and validate connection parameters. SSE cannot carry the+ # /ws_sync document stream, so RTC is disabled.+ params = parse_connection_params(app_state, allow_rtc=False)+ if isinstance(params, ConnectionRejection):+ return _close_only_stream(params.code, params.reason)++ LOGGER.debug(+ "SSE open request for session with id %s",+ params.session_id,+ )++ # 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())++# WebSocket endpoint for LoroDoc synchronization@router.websocket("/ws_sync")async def ws_sync(@@ -151,7 +206,7 @@ async def ws_sync(await handler.handle()-class WebSocketHandler(SessionConsumer):+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@@ -166,221 +221,14 @@ class WebSocketHandler(SessionConsumer):params: ConnectionParams,mode: SessionMode,):- self.websocket = websocket- self.manager = manager- self.params = params- self.mode = mode- self.status: ConnectionState- self.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]- self.ws_future: asyncio.Task[None] | None = None- self._consumer_id = ConsumerId(params.session_id)-- @property- def consumer_id(self) -> ConsumerId:- return self._consumer_id-- def notify(self, notification: KernelMessage) -> None:- self.message_queue.put_nowait(notification)-- def _serialize_and_notify(self, notification: NotificationMessage) -> None:- self.notify(serialize_kernel_message(notification))-- def _write_kernel_ready_from_session_view(- self, session: Session, kiosk: bool- ) -> None:- """Write kernel ready message using current session view state."""- self._write_kernel_ready(- session=session,- resumed=True,- ui_values=session.session_view.ui_values,- last_executed_code=session.session_view.last_executed_code,- last_execution_time=session.session_view.last_execution_time,- kiosk=kiosk,- auto_instantiated=False,- )-- def _write_kernel_ready(- self,- session: Session,- resumed: bool,- ui_values: dict[str, JSONType],- last_executed_code: dict[CellId_t, str],- last_execution_time: dict[CellId_t, float],- kiosk: bool,- auto_instantiated: bool,- ) -> None:- """Communicates to the client that the kernel is ready.-- Sends cell code and other metadata to client.-- Args:- session: Current session- resumed: Whether this is a resumed session- ui_values: UI element values- last_executed_code: Last executed code for each cell- last_execution_time: Last execution time for each cell- kiosk: Whether this is kiosk mode- auto_instantiated: Whether the kernel has already been instantiated- server-side (run mode). If True, the frontend does not need- to instantiate the app.- """- # Only send execution data if sending code to frontend- should_send = self.manager.should_send_code_to_frontend()-- # RTC is only enabled if configured AND Loro is available- effective_rtc_enabled = self.params.rtc_enabled and is_rtc_available()-- # Build kernel ready message- kernel_ready_msg = build_kernel_ready(- session=session,- manager=self.manager,- resumed=resumed,- ui_values=ui_values,- last_executed_code=last_executed_code if should_send else {},- last_execution_time=last_execution_time if should_send else {},- kiosk=kiosk,- rtc_enabled=effective_rtc_enabled,- file_key=self.params.file_key,- mode=self.mode,+ super().__init__(+ manager=manager,+ params=params,+ mode=mode,doc_manager=DOC_MANAGER,- auto_instantiated=auto_instantiated,)- self._serialize_and_notify(kernel_ready_msg)-- def _reconnect_session(self, session: Session, replay: bool) -> None:- """Reconnect to an existing session (kernel).-- A websocket can be closed when a user's computer goes to sleep,- spurious network issues, etc.- """- # Cancel previous close handle- if self.cancel_close_handle is not None:- self.cancel_close_handle.cancel()-- self.status = ConnectionState.OPEN- session.connect_consumer(self, main=True)-- # Write reconnected message- self._serialize_and_notify(ReconnectedNotification())-- # If not replaying, just send a toast- if not replay:- self._serialize_and_notify(- AlertNotification(- title="Reconnected",- description="You have reconnected to an existing session.",- )- )- return-- self._write_kernel_ready_from_session_view(session, self.params.kiosk)- self._serialize_and_notify(- BannerNotification(- title="Reconnected",- description="You have reconnected to an existing session.",- action="restart",- )- )-- self._replay_previous_session(session)-- def _connect_kiosk(self, session: Session) -> None:- """Connect to a kiosk session.-- A kiosk session is a write-ish session that is connected to a- frontend. It can set UI elements and interact with the sidebar,- but cannot change or execute code. This is not a permission limitation,- but rather we don't have full multi-player support yet.-- Kiosk mode is useful when the user is using an editor (VSCode or VIM)- that does not easily support our reactive frontend or our panels.- The user uses VSCode or VIM to write code, and the- marimo kiosk/frontend to visualize the output.- """-- session.connect_consumer(self, main=False)- self.status = ConnectionState.CONNECTING- self._write_kernel_ready_from_session_view(session, kiosk=True)- self.status = ConnectionState.OPEN- self._replay_previous_session(session)-- def _replay_previous_session(self, session: Session) -> None:- """Replay the previous session view."""- notifications = session.session_view.notifications- if len(notifications) == 0:- LOGGER.debug("No notifications to replay")- return- LOGGER.debug(f"Replaying {len(notifications)} notifications")- for notif in notifications:- LOGGER.debug("Replaying notification %s", notif)- self._serialize_and_notify(notif)-- def _on_disconnect(- self,- e: Exception,- cleanup_fn: Callable[[], Any],- ) -> None:- LOGGER.debug(- "Websocket disconnected for session %s with exception %s, type %s",- self.params.session_id,- str(e),- type(e),- )-- # Change the status- self.status = ConnectionState.CLOSED- # Disconnect the consumer- session = self.manager.get_session(self.params.session_id)- if session:- session.disconnect_consumer(self)-- # When the websocket is closed, we wait session.ttl_seconds before- # closing the session. This prevents the session from being closed- # during intermittent network issues.- # In RUN mode, this always applies (sessions always have a default- # TTL even if the manager's ttl_seconds is None).- # In EDIT mode, this only applies when --session-ttl is explicitly set.- should_ttl_close = (- self.manager.ttl_seconds is not None- or self.mode == SessionMode.RUN- )- if should_ttl_close:-- def _close() -> None:- if self.status != ConnectionState.OPEN:- # Guard: if another consumer has taken over, the session- # is alive.- live = self.manager.get_session(self.params.session_id)- if (- live is not None- and live.connection_state() == ConnectionState.OPEN- ):- LOGGER.debug(- "Session %s has active consumer, skipping TTL close",- self.params.session_id,- )- return- LOGGER.debug(- "Closing session %s (TTL EXPIRED)",- self.params.session_id,- )- # wait until TTL is expired before calling the cleanup- # function- cleanup_fn()- self.manager.close_session(self.params.session_id)-- if session is not None:- cancellation_handle = asyncio.get_running_loop().call_later(- session.ttl_seconds, _close- )- self.cancel_close_handle = cancellation_handle- else:- _close()- else:- cleanup_fn()+ self.websocket = websocket+ self.ws_future: asyncio.Task[None] | None = Noneasync def start(self) -> None:"""Start the WebSocket handler.@@ -390,8 +238,6 @@ class WebSocketHandler(SessionConsumer):"""# Accept the websocket connectionawait self.websocket.accept()- # Create a new queue for this session- self.message_queue = asyncio.Queue()LOGGER.debug("Websocket open request for session with id %s",@@ -399,15 +245,8 @@ class WebSocketHandler(SessionConsumer):)LOGGER.debug("Existing sessions: %s", self.manager.sessions)- # Use SessionConnector to establish session connection- connector = SessionConnector(- manager=self.manager,- handler=self,- params=self.params,- websocket=self.websocket,- )try:- session, connection_type = connector.connect()+ session, connection_type = self._connect_session(self.websocket)except KernelStartupError as e:LOGGER.error("Kernel startup failed: %s", e)await self._close_kernel_startup_error(str(e))@@ -422,10 +261,7 @@ class WebSocketHandler(SessionConsumer):message_loop = WebSocketMessageLoop(websocket=self.websocket,message_queue=self.message_queue,- is_kiosk=lambda: is_viewer_connection(- connection_type=connection_type,- is_main_consumer=session.room.main_consumer is self,- ),+ is_kiosk=lambda: self._is_viewer(session, connection_type),on_disconnect=self._on_disconnect,on_check_status_update=self._check_status_update,)@@ -459,7 +295,7 @@ class WebSocketHandler(SessionConsumer):"""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_websocket(notification)+ text = serialize_notification_for_wire(notification)await self.websocket.send_text(text)# Then close with simple reasonawait self._safe_close(@@ -467,83 +303,14 @@ class WebSocketHandler(SessionConsumer):WebSocketCloseReason.KERNEL_STARTUP_ERROR,)- def on_attach(self, session: Session, event_bus: SessionEventBus) -> None:- del session- del event_bus- return+ 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 on_detach(self) -> None:- # If the websocket is open, send a close message- is_connected = (- self.status == ConnectionState.OPEN- or self.status == ConnectionState.CONNECTING- ) and self.websocket.application_state is WebSocketState.CONNECTED- if is_connected:- task = asyncio.create_task(- self._safe_close(- WebSocketCodes.NORMAL_CLOSE, WebSocketCloseReason.SHUTDOWN- )- )- _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()-- def connection_state(self) -> ConnectionState:- return self.status-- def _check_status_update(self) -> None:- # Only check for updates if we're in edit mode- if (- not GLOBAL_SETTINGS.CHECK_STATUS_UPDATE- or self.mode != SessionMode.EDIT- ):- return-- def on_update(current_version: str, state: MarimoCLIState) -> None:- # Let's only toast once per marimo server- # so we can just store this in memory.- # We still want to check for updates (which are debounced 24 hours)- # but don't keep toasting.- global has_toasted- if has_toasted:- return-- has_toasted = True-- title = (- f"Update available {current_version} → {state.latest_version}"- )- release_url = "https://github.com/marimo-team/marimo/releases"-- # Build description with notices if present- description = f"Check out the <a class='underline' target='_blank' href='{release_url}'>latest release on GitHub.</a>"-- if state.notices:- notices_text = (- "<br><br><strong>Recent updates:</strong><br>"- + "<br>".join(f"• {notice}" for notice in state.notices)- )- description += notices_text-- self._serialize_and_notify(- AlertNotification(title=title, description=description)- )-- check_for_updates(on_update)-- def _connect_to_existing_session(self, session: Session) -> None:- """Connect to an existing session and replay all messages."""- self.status = ConnectionState.CONNECTING- session.connect_consumer(self, main=False)-- # Write kernel ready with current state- self._write_kernel_ready_from_session_view(session, kiosk=False)- self.status = ConnectionState.OPEN-- # Replay all operations- self._replay_previous_session(session)---has_toasted = Falsediff --git a/marimo/_server/scratchpad.py b/marimo/_server/scratchpad.pyindex 56ca93dc07..1e7bdad727 100644--- a/marimo/_server/scratchpad.py+++ b/marimo/_server/scratchpad.py@@ -23,6 +23,7 @@ from marimo._messaging.serde import deserialize_kernel_messagefrom marimo._runtime.commands import ExecuteScratchpadCommand, HTTPRequestfrom marimo._runtime.scratch import SCRATCH_CELL_IDfrom marimo._server.models.models import InstantiateNotebookRequest+from marimo._server.sse import format_sse_eventfrom marimo._session.extensions.types import EventAwareExtensionif TYPE_CHECKING:@@ -72,7 +73,7 @@ class Done(TypedDict):def _format_sse(event: str, data: Any) -> str:"""Format a single SSE event (event + JSON data)."""- return f"event: {event}\ndata: {json.dumps(data)}\n\n"+ return format_sse_event(json.dumps(data), event=event)# -- Listeners ----------------------------------------------------------------diff --git a/marimo/_server/sse.py b/marimo/_server/sse.pynew file mode 100644index 0000000000..8f309b77ee--- /dev/null+++ b/marimo/_server/sse.py@@ -0,0 +1,58 @@+# Copyright 2026 Marimo. All rights reserved.+"""Server-sent events (SSE) framing and connection utilities.++Shared by every endpoint that streams `text/event-stream` responses (the+session `/sse` transport and the scratchpad `/api/kernel/execute` stream).+"""++from __future__ import annotations++import json+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from starlette.requests import Request++SSE_HEADERS = {+ "Cache-Control": "no-cache, no-transform",+ # Disable proxy buffering (nginx) so events are delivered immediately+ "X-Accel-Buffering": "no",+}++HEARTBEAT_EVENT = ": keep-alive\n\n"+++def format_sse_event(data: str, event: str | None = None) -> str:+ """Frame `data` as a server-sent event.++ Multi-line payloads are split into one `data:` line each, per the SSE+ spec; clients rejoin them with newlines.+ """+ lines = "".join(f"data: {line}\n" for line in data.split("\n"))+ if event is None:+ return f"{lines}\n"+ return f"event: {event}\n{lines}\n"+++def format_close_event(code: int, reason: str) -> str:+ """Frame the SSE equivalent of a WebSocket close frame."""+ return format_sse_event(+ json.dumps({"code": code, "reason": reason}), event="close"+ )+++async def wait_for_http_disconnect(request: Request) -> None:+ """Wait until the client disconnects.++ `request._receive` is the ASGI `receive` callable; reading it is the+ standard way to detect disconnects. Note that on ASGI servers+ advertising spec_version < 2.4 (e.g. uvicorn), Starlette's+ `StreamingResponse` also listens on the same receive channel and+ cancels the response on disconnect — so callers must not rely on this+ helper as their only cleanup path; treat it as a prompt-shutdown+ signal and put teardown in a `finally` that also runs on cancellation.+ """+ while True:+ message = await request._receive()+ if message.get("type") == "http.disconnect":+ returndiff --git a/marimo/_smoke_tests/inline_sse_transport.py b/marimo/_smoke_tests/inline_sse_transport.pynew file mode 100644index 0000000000..9a01f4a350--- /dev/null+++ b/marimo/_smoke_tests/inline_sse_transport.py@@ -0,0 +1,73 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "marimo",+# ]+#+# [tool.marimo.server]+# transport = "sse"+# ///+# Copyright 2026 Marimo. All rights reserved.++import marimo++__generated_with = "0.23.13"+app = marimo.App()++[email protected](hide_code=True)+def _():+ import marimo as mo++ return (mo,)++[email protected](hide_code=True)+def _(mo):+ mo.md("""+ # SSE transport smoke test++ This notebook sets `transport = "sse"` via inline+ `[tool.marimo.server]` metadata, selecting the **experimental**+ server-sent-events transport for the kernel connection instead of the+ default websocket. In deployments, the equivalent is the+ `MARIMO_SERVER_TRANSPORT=sse` environment variable.++ To verify:++ 1. Open with `marimo edit marimo/_smoke_tests/inline_sse_transport.py`+ (or `marimo run ...`).+ 2. In the browser devtools **Network** tab, confirm that **no `/ws`+ connection opens** and that a `/sse` request is streaming with+ content-type `text/event-stream`.+ 3. The notebook should load and cells below should run — client→kernel+ traffic goes over HTTP POST while kernel→client updates arrive over+ the SSE stream.+ 4. Kill the server: the "disconnected / shutdown" UX should appear.+ Restart it: the client should reconnect and resume the session.++ Note: with the SSE transport, RTC is auto-disabled and the terminal /+ LSP features still require websockets.+ """)+ return++[email protected](hide_code=True)+def _(mo):+ # A reactive slider to confirm UI element updates round-trip over+ # POST (input) + SSE (output).+ slider = mo.ui.slider(1, 100, value=10, label="value")+ slider+ return (slider,)++[email protected](hide_code=True)+def _(mo, slider):+ mo.md(f"""+ Slider value is **{slider.value}** — squared is **{slider.value**2}**.+ """)+ return+++if __name__ == "__main__":+ app.run()diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yamlindex f4af702f2b..8b118dfedb 100644--- a/packages/openapi/api.yaml+++ b/packages/openapi/api.yaml@@ -4679,7 +4679,14 @@ components:\ Python's webbrowser module (eg, `\"firefox\"` or `\"chrome\"`)\n - `follow_symlink`:\\ if true, the server will follow symlinks it finds\n inside its static\\ assets directory.\n - `disable_file_downloads`: if true, the file download\- \ button will be\n hidden in the file explorer."+ \ button will be\n hidden in the file explorer.\n - `transport`:\+ \ experimental. The transport used to stream kernel\n messages to the\+ \ frontend, typically set with the\n `MARIMO_SERVER_TRANSPORT` environment\+ \ variable. `\"websocket\"`\n (default) uses the `/ws` WebSocket endpoint;\+ \ `\"sse\"` uses\n server-sent events over HTTP, for deployments behind\+ \ proxies or\n services that do not support WebSockets. Terminal, LSP,\+ \ and\n real-time collaboration still require WebSockets; RTC is disabled\n\+ \ when using `\"sse\"`."properties:browser:anyOf:@@ -4690,6 +4697,10 @@ components:type: booleanfollow_symlink:type: boolean+ transport:+ enum:+ - sse+ - websocketrequired:- browser- follow_symlinkdiff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.tsindex b8b0006a7c..7812a6d95c 100644--- a/packages/openapi/src/api.ts+++ b/packages/openapi/src/api.ts@@ -6307,11 +6307,21 @@ export interface components {* inside its static assets directory.* - `disable_file_downloads`: if true, the file download button will be* hidden in the file explorer.+ * - `transport`: experimental. The transport used to stream kernel+ * messages to the frontend, typically set with the+ * `MARIMO_SERVER_TRANSPORT` environment variable. `"websocket"`+ * (default) uses the `/ws` WebSocket endpoint; `"sse"` uses+ * server-sent events over HTTP, for deployments behind proxies or+ * services that do not support WebSockets. Terminal, LSP, and+ * real-time collaboration still require WebSockets; RTC is disabled+ * when using `"sse"`.*/ServerConfig: {browser: "default" | string;disable_file_downloads?: boolean;follow_symlink: boolean;+ /** @enum {unknown} */+ transport?: "sse" | "websocket";};/** Format: session-id */SessionId: TypedString<"SessionId">;diff --git a/tests/_config/test_manager.py b/tests/_config/test_manager.pyindex 067d2da65f..6bdab1eade 100644--- a/tests/_config/test_manager.py+++ b/tests/_config/test_manager.py@@ -664,6 +664,27 @@ def test_env_config_manager_no_env_vars() -> None:assert config == {}[email protected]("transport", ["websocket", "sse"])+def test_env_config_manager_server_transport(+ monkeypatch: pytest.MonkeyPatch, transport: str+) -> None:+ """MARIMO_SERVER_TRANSPORT selects the kernel-connection transport"""+ monkeypatch.setenv("MARIMO_SERVER_TRANSPORT", transport)+ manager = EnvConfigManager()+ config = manager.get_config(hide_secrets=False)+ assert config == {"server": {"transport": transport}}+++def test_env_config_manager_server_transport_invalid(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Invalid MARIMO_SERVER_TRANSPORT values are ignored with a warning"""+ monkeypatch.setenv("MARIMO_SERVER_TRANSPORT", "carrier-pigeon")+ manager = EnvConfigManager()+ config = manager.get_config(hide_secrets=False)+ assert config == {}++RESTRICTED_SHARING = {"wasm": False, "html": False, "molab": False}diff --git a/tests/_server/api/endpoints/test_auto_instantiate.py b/tests/_server/api/endpoints/test_auto_instantiate.pyindex a2c7afe441..a7b5a94b3f 100644--- a/tests/_server/api/endpoints/test_auto_instantiate.py+++ b/tests/_server/api/endpoints/test_auto_instantiate.py@@ -127,11 +127,11 @@ class TestAutoInstantiateHTTPRequest:"""Tests for HTTP request propagation during auto-instantiate."""def test_auto_instantiate_passes_http_request(self) -> None:- """Verify _auto_instantiate passes HTTPRequest from websocket.+ """Verify _auto_instantiate passes HTTPRequest from the connection.This verifies the fix for the issue where mo.app_meta().requestreturned None in run mode because _auto_instantiate was passing- http_request=None instead of extracting it from the websocket.+ http_request=None instead of extracting it from the connection."""from marimo._server.api.endpoints.ws.ws_session_connector import (SessionConnector,@@ -144,7 +144,7 @@ class TestAutoInstantiateHTTPRequest:manager=MagicMock(),handler=MagicMock(),params=MagicMock(),- websocket=MagicMock(),+ connection=MagicMock(),)with patch(@@ -153,7 +153,7 @@ class TestAutoInstantiateHTTPRequest:) as mock_from_request:connector._auto_instantiate(mock_session)- mock_from_request.assert_called_once_with(connector.websocket)+ mock_from_request.assert_called_once_with(connector.connection)assert (mock_session.instantiate.call_args.kwargs["http_request"]is mock_http_requestdiff --git a/tests/_server/api/endpoints/test_requires_decorator.py b/tests/_server/api/endpoints/test_requires_decorator.pyindex e55b1d6f9f..068ab1191c 100644--- a/tests/_server/api/endpoints/test_requires_decorator.py+++ b/tests/_server/api/endpoints/test_requires_decorator.py@@ -22,6 +22,10 @@ EXEMPT_ENDPOINTS: set[tuple[str, str]] = {# via `_MARIMO_DISABLE_AUTH_ON_VIRTUAL_FILES` for sandboxed/embedded# deployments.("assets.py", "/@file/{filename_and_length:path}"),+ # The SSE session stream does its own auth check so failures are+ # delivered in-band as a `close` event (matching /ws close frames)+ # instead of an HTTP error; covered by auth tests in test_sse.py.+ ("ws_endpoint.py", "/sse"),}ENDPOINTS_DIR = Path(__file__).resolve().parents[4] / (diff --git a/tests/_server/api/endpoints/test_sse.py b/tests/_server/api/endpoints/test_sse.pynew file mode 100644index 0000000000..4d94d9e410--- /dev/null+++ b/tests/_server/api/endpoints/test_sse.py@@ -0,0 +1,522 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import asyncio+import json+import threading+from functools import partial+from typing import TYPE_CHECKING, Any+from unittest.mock import MagicMock, patch++import pytest++from marimo._messaging.notification import AlertNotification+from marimo._messaging.serde import serialize_kernel_message+from marimo._server.api.endpoints.ws.sse_handler import SSESessionHandler+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.sse import format_close_event, format_sse_event+from marimo._session.managers.ipc import KernelStartupError+from marimo._session.model import ConnectionState, SessionMode+from marimo._types.ids import SessionId+from tests._server.api.endpoints.ws_helpers import (+ assert_kernel_ready_response,+ create_response,+)+from tests._server.mocks import get_session_manager++if TYPE_CHECKING:+ from starlette.applications import Starlette+ from starlette.testclient import TestClient+ from typing_extensions import Self++SSE_QUERY = "session_id=123&access_token=fake-token"+OTHER_SSE_QUERY = "session_id=456&access_token=fake-token"+++class SSETestConnection:+ """Drives a `GET /sse` request against the raw ASGI app.++ The TestClient buffers entire response bodies, which never works for an+ unbounded SSE stream; this speaks ASGI directly so tests can read+ events incrementally and disconnect at any time.+ """++ def __init__(+ self,+ app: Starlette,+ query: str,+ headers: dict[str, str] | None = None,+ ) -> None:+ self._app = app+ self._scope = {+ "type": "http",+ "asgi": {"version": "3.0"},+ "http_version": "1.1",+ "method": "GET",+ "scheme": "http",+ "path": "/sse",+ "raw_path": b"/sse",+ "query_string": query.encode(),+ "root_path": "",+ # ASGI header names must be lowercase bytes+ "headers": [+ (b"host", b"testserver"),+ *(+ (k.lower().encode(), v.encode())+ for k, v in (headers or {}).items()+ ),+ ],+ "client": ("testclient", 50000),+ "server": ("testserver", 80),+ }+ self._receive_queue: asyncio.Queue[dict[str, Any]] = asyncio.Queue()+ self._events: asyncio.Queue[dict[str, str]] = asyncio.Queue()+ self._buffer = ""+ self._task: asyncio.Task[None] | None = None+ self.status: int | None = None+ self.headers: dict[str, str] = {}++ async def __aenter__(self) -> Self:+ self._task = asyncio.create_task(+ self._app(self._scope, self._receive, self._send)+ )+ return self++ async def __aexit__(self, *args: Any) -> None:+ self.disconnect()+ assert self._task is not None+ await asyncio.wait_for(self._task, timeout=10)++ def disconnect(self) -> None:+ self._receive_queue.put_nowait({"type": "http.disconnect"})++ async def next_event(self, timeout: float = 10) -> dict[str, str]:+ """The next SSE record: {"event": ..., "data": ...} or a comment."""+ return await asyncio.wait_for(self._events.get(), timeout)++ def has_pending_events(self) -> bool:+ return not self._events.empty()++ def stream_ended(self) -> bool:+ assert self._task is not None+ return self._task.done()++ async def _receive(self) -> dict[str, Any]:+ return await self._receive_queue.get()++ async def _send(self, message: dict[str, Any]) -> None:+ if message["type"] == "http.response.start":+ self.status = message["status"]+ self.headers = {+ k.decode(): v.decode() for k, v in message.get("headers", [])+ }+ elif message["type"] == "http.response.body":+ self._buffer += message.get("body", b"").decode()+ while "\n\n" in self._buffer:+ record, self._buffer = self._buffer.split("\n\n", 1)+ self._events.put_nowait(_parse_record(record))+++def _parse_record(record: str) -> dict[str, str]:+ event = "message"+ data_lines: list[str] = []+ comments: list[str] = []+ for line in record.split("\n"):+ if line.startswith(":"):+ comments.append(line[1:].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)}+++def _connect(+ client: TestClient,+ query: str = SSE_QUERY,+ headers: dict[str, str] | None = None,+) -> SSETestConnection:+ return SSETestConnection(client.app, query, headers)+++async def _expect_close(+ connection: SSETestConnection, code: int, reason: str+) -> None:+ event = await connection.next_event()+ 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:+ event = await connection.next_event()+ assert connection.status == 200+ assert connection.headers["content-type"].startswith(+ "text/event-stream"+ )+ assert event["event"] == "message"+ message = json.loads(event["data"])+ assert message["op"] == "kernel-ready"+ assert_kernel_ready_response(message)+++async def test_sse_requires_session_id(client: TestClient) -> None:+ async with _connect(client, "access_token=fake-token") as connection:+ await _expect_close(connection, 1000, "MARIMO_NO_SESSION_ID")+++async def test_sse_requires_authentication(client: TestClient) -> None:+ async with _connect(client, "session_id=123") as connection:+ await _expect_close(connection, 3000, "MARIMO_UNAUTHORIZED")+++async def test_sse_authenticates_with_bearer_header(+ client: TestClient,+) -> None:+ # The frontend SSE transport sends auth in headers, not the URL+ async with _connect(+ client,+ "session_id=123",+ headers={"Authorization": "Bearer fake-token"},+ ) as connection:+ event = await connection.next_event()+ assert json.loads(event["data"])["op"] == "kernel-ready"+++async def test_sse_rejects_invalid_query_token(client: TestClient) -> None:+ async with _connect(+ client, "session_id=123&access_token=wrong-token"+ ) as connection:+ await _expect_close(connection, 3000, "MARIMO_UNAUTHORIZED")+++async def test_sse_rejects_invalid_bearer_token(client: TestClient) -> None:+ async with _connect(+ client,+ "session_id=123",+ headers={"Authorization": "Bearer wrong-token"},+ ) as connection:+ await _expect_close(connection, 3000, "MARIMO_UNAUTHORIZED")+++ "authorization",+ [+ "Bearer", # no credentials+ "Unknown fake-token", # unsupported scheme+ "Basic !!!not-base64!!!",+ "Basic dXNlcm5hbWUtb25seQ==", # no password ("username-only")+ ],+)+async def test_sse_rejects_malformed_authorization_header(+ client: TestClient, authorization: str+) -> None:+ async with _connect(+ client,+ "session_id=123",+ headers={"Authorization": authorization},+ ) as connection:+ await _expect_close(connection, 3000, "MARIMO_UNAUTHORIZED")+++async def test_sse_unauthorized_has_no_side_effects(+ client: TestClient,+) -> None:+ """A rejected request must not create a session or leak anything."""+ session_manager = get_session_manager(client)+ async with _connect(client, "session_id=123") as connection:+ await _expect_close(connection, 3000, "MARIMO_UNAUTHORIZED")++ assert session_manager.sessions == {}+ # The stream ends after the close event; nothing else is sent+ assert connection.stream_ended()+ assert not connection.has_pending_events()+ # Failed auth must not issue an authenticated session cookie+ assert "set-cookie" not in connection.headers+++async def test_sse_allows_unauthenticated_when_auth_disabled(+ client: TestClient,+) -> None:+ # Trusted environments (e.g. --no-token) disable marimo's own auth+ client.app.state.enable_auth = False+ async with _connect(client, "session_id=123") as connection:+ event = await connection.next_event()+ assert json.loads(event["data"])["op"] == "kernel-ready"+++async def test_sse_kiosk_not_allowed_in_run_mode(client: TestClient) -> None:+ get_session_manager(client).mode = SessionMode.RUN+ async with _connect(client, f"{SSE_QUERY}&kiosk=true") as connection:+ await _expect_close(connection, 1008, "MARIMO_KIOSK_NOT_ALLOWED")+ assert get_session_manager(client).sessions == {}+++async def test_sse_hides_code_when_include_code_false(+ client: TestClient,+) -> None:+ session_manager = get_session_manager(client)+ session_manager.mode = SessionMode.RUN+ session_manager.include_code = False+ async with _connect(client) as connection:+ event = await connection.next_event()+ message = json.loads(event["data"])+ assert message["op"] == "kernel-ready"+ assert message["data"]["codes"] == [""] # hidden+ assert message["data"]["last_executed_code"] == {} # hidden+ assert message["data"]["cell_ids"] == ["Hbol"] # preserved+++async def test_sse_kernel_startup_error(client: TestClient) -> None:+ with patch.object(+ SSESessionHandler,+ "_connect_session",+ side_effect=KernelStartupError("boom"),+ ):+ async with _connect(client) as connection:+ event = await connection.next_event()+ message = json.loads(event["data"])+ assert message["op"] == "kernel-startup-error"+ assert message["data"]["error"] == "boom"+ await _expect_close(+ connection, 1011, "MARIMO_KERNEL_STARTUP_ERROR"+ )+++async def test_sse_kiosk_without_session(client: TestClient) -> None:+ async with _connect(client, f"{SSE_QUERY}&kiosk=true") as connection:+ await _expect_close(connection, 1000, "MARIMO_NO_SESSION")+++async def test_sse_disconnect_and_reconnect(client: TestClient) -> None:+ async with _connect(client) as connection:+ event = await connection.next_event()+ assert json.loads(event["data"])["op"] == "kernel-ready"+ # Reconnect with the same session id+ async with _connect(client) as connection:+ event = await connection.next_event()+ assert json.loads(event["data"])["op"] == "reconnected"+ event = await connection.next_event()+ assert json.loads(event["data"])["op"] == "alert"+++async def test_sse_second_connection_joins_as_viewer(+ client: TestClient,+) -> None:+ async with _connect(client) as connection:+ event = await connection.next_event()+ assert json.loads(event["data"])["op"] == "kernel-ready"+ async with _connect(client, OTHER_SSE_QUERY) as viewer:+ event = await viewer.next_event()+ message = json.loads(event["data"])+ assert message["op"] == "kernel-ready"+ assert_kernel_ready_response(+ message, create_response({"kiosk": True, "resumed": True})+ )+++async def test_sse_heartbeat(client: TestClient) -> None:+ with_heartbeat = partial(SSESessionHandler, heartbeat_seconds=0.01)+ with patch(+ "marimo._server.api.endpoints.ws_endpoint.SSESessionHandler",+ with_heartbeat,+ ):+ async with _connect(client) as connection:+ event = await connection.next_event()+ assert json.loads(event["data"])["op"] == "kernel-ready"+ # Drain until the first heartbeat comment arrives+ for _ in range(20):+ event = await connection.next_event()+ if event["event"] == "comment":+ break+ assert event == {"event": "comment", "data": "keep-alive"}+++# Unit tests for the stream generator+++def _make_handler(+ request: MagicMock, *, mode: SessionMode = SessionMode.RUN+) -> SSESessionHandler:+ params = ConnectionParams(+ session_id=SessionId("s1"),+ file_key="test.py",+ kiosk=False,+ auto_instantiate=False,+ rtc_enabled=False,+ )+ handler = SSESessionHandler(+ request=request,+ manager=MagicMock(),+ params=params,+ mode=mode,+ doc_manager=MagicMock(),+ heartbeat_seconds=60,+ )+ handler.status = ConnectionState.OPEN+ # Bypass SessionConnector; unit tests drive the handler directly+ session = MagicMock()+ session.room.main_consumer = handler+ handler._connect_session = MagicMock( # type: ignore[method-assign]+ return_value=(session, ConnectionType.NEW)+ )+ return handler+++def _never_receive() -> Any:+ async def receive() -> dict[str, Any]:+ await asyncio.Event().wait()+ raise AssertionError("unreachable")++ return receive+++async def test_stream_sends_messages_and_close_event() -> None:+ request = MagicMock()+ request._receive = _never_receive()+ handler = _make_handler(request)++ stream = handler.stream()+ 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"++ # Detaching from the session requests a SHUTDOWN close+ handler.on_detach()+ second = await asyncio.wait_for(stream.__anext__(), timeout=10)+ assert second == format_close_event(1000, "MARIMO_SHUTDOWN")+ with pytest.raises(StopAsyncIteration):+ await asyncio.wait_for(stream.__anext__(), timeout=10)+ assert not handler._is_transport_connected()+++async def test_stream_does_not_connect_until_iterated() -> None:+ """A response body that is never consumed must not attach a consumer."""+ request = MagicMock()+ request._receive = _never_receive()+ handler = _make_handler(request)++ stream = handler.stream()+ await asyncio.sleep(0)+ handler._connect_session.assert_not_called()++ await stream.aclose()+ handler._connect_session.assert_not_called()+++async def test_stream_flushes_pending_messages_before_close() -> None:+ """Messages enqueued before a server close are sent, then the close."""+ request = MagicMock()+ request._receive = _never_receive()+ handler = _make_handler(request)++ handler.notify(+ serialize_kernel_message(+ AlertNotification(title="one", description="")+ )+ )+ handler.notify(+ serialize_kernel_message(+ AlertNotification(title="two", description="")+ )+ )+ handler.on_detach()++ events = [event async for event in handler.stream()]+ 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 events[2] == format_close_event(1000, "MARIMO_SHUTDOWN")+++async def test_stream_ends_on_client_disconnect() -> None:+ request = MagicMock()++ async def receive() -> dict[str, Any]:+ return {"type": "http.disconnect"}++ request._receive = receive+ handler = _make_handler(request, mode=SessionMode.EDIT)+ handler.manager.get_session.return_value = None+ handler.manager.ttl_seconds = None++ events = [event async for event in handler.stream()]+ assert events == []+ assert handler.connection_state() == ConnectionState.CLOSED+++async def test_check_status_update_runs_off_the_event_loop(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The synchronous update check must not block kernel messages."""+ from marimo._config.settings import GLOBAL_SETTINGS+ from marimo._server.api.endpoints.ws import session_handler++ monkeypatch.setattr(GLOBAL_SETTINGS, "CHECK_STATUS_UPDATE", True)+ monkeypatch.setattr(session_handler, "has_toasted", False)++ started = threading.Event()+ release = threading.Event()++ def slow_check(on_update: Any) -> None:+ started.set()+ assert release.wait(timeout=10)+ on_update("0.0.1", MagicMock(latest_version="9.9.9", notices=[]))++ monkeypatch.setattr(session_handler, "check_for_updates", slow_check)++ handler = _make_handler(MagicMock(), mode=SessionMode.EDIT)+ # Returns immediately, while the check is still running on a thread+ handler._check_status_update()+ assert await asyncio.wait_for(asyncio.to_thread(started.wait, 10), 20)+ assert handler.message_queue.empty()++ # Once the check completes, the alert is delivered onto the queue+ release.set()+ message = await asyncio.wait_for(handler.message_queue.get(), timeout=10)+ assert b"Update available" in bytes(message)+++async def test_stream_heartbeat_without_messages() -> None:+ request = MagicMock()+ request._receive = _never_receive()+ handler = _make_handler(request)+ handler.heartbeat_seconds = 0.01++ stream = handler.stream()+ first = await asyncio.wait_for(stream.__anext__(), timeout=10)+ assert first == ": keep-alive\n\n"+ handler._request_close(1000, "MARIMO_SHUTDOWN")+ async for _ in stream:+ pass+++# Unit tests for SSE framing+++def test_format_sse_event() -> None:+ assert format_sse_event('{"op": "alert"}') == 'data: {"op": "alert"}\n\n'+ assert (+ format_sse_event('{"code": 1}', event="close")+ == 'event: close\ndata: {"code": 1}\n\n'+ )+ # Multi-line payloads become one data line each+ assert format_sse_event("a\nb") == "data: a\ndata: b\n\n"+++def test_format_close_event() -> None:+ assert format_close_event(1000, "MARIMO_SHUTDOWN") == (+ 'event: close\ndata: {"code": 1000, "reason": "MARIMO_SHUTDOWN"}\n\n'+ )diff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.pyindex 2792d22427..bff1668eb2 100644--- a/tests/_server/api/endpoints/test_ws.py+++ b/tests/_server/api/endpoints/test_ws.py@@ -363,6 +363,20 @@ def test_ws_requires_authentication(client: TestClient) -> None:assert exc_info.value.reason == "MARIMO_UNAUTHORIZED"+def test_ws_rejects_invalid_token(client: TestClient) -> None:+ """An incorrect access_token must be rejected, not just a missing one."""+ with pytest.raises(WebSocketDisconnect) as exc_info:+ with client.websocket_connect(+ "/ws?session_id=123&access_token=wrong-token"+ ):+ raise AssertionError(+ "Should not be able to connect with an invalid token"+ )++ assert exc_info.value.code == WebSocketCodes.UNAUTHORIZED+ assert exc_info.value.reason == "MARIMO_UNAUTHORIZED"++def test_ws_sync_requires_authentication(client: TestClient) -> None:"""Test that WebSocket sync endpoint requires authentication."""# Try to connect without any authentication headersdiff --git a/tests/_server/api/endpoints/test_ws_message_loop.py b/tests/_server/api/endpoints/test_ws_message_loop.pyindex 8e88376466..928dbe4bf5 100644--- a/tests/_server/api/endpoints/test_ws_message_loop.py+++ b/tests/_server/api/endpoints/test_ws_message_loop.py@@ -1,54 +1,46 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations-from unittest.mock import MagicMock+import jsonfrom marimo._messaging.notification import (+ AlertNotification,CompletionResultNotification,FocusCellNotification,)+from marimo._messaging.serde import serialize_kernel_messagefrom marimo._server.api.endpoints.ws.ws_message_loop import (- WebSocketMessageLoop,+ prepare_wire_message,)+from marimo._types.ids import CellId_t, RequestId--def _loop(is_kiosk: bool) -> WebSocketMessageLoop:- return WebSocketMessageLoop(- websocket=MagicMock(),- message_queue=MagicMock(),- is_kiosk=lambda: is_kiosk,- on_disconnect=MagicMock(),- on_check_status_update=MagicMock(),+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:- loop = _loop(is_kiosk=False)- assert loop._should_filter_operation(FocusCellNotification.name) is True- assert (- loop._should_filter_operation(CompletionResultNotification.name)- is False- )+ assert prepare_wire_message(FOCUS_CELL, is_kiosk=False) is None+ assert prepare_wire_message(COMPLETION_RESULT, is_kiosk=False) is not Nonedef test_viewer_keeps_kiosk_only_and_filters_completions() -> None:- loop = _loop(is_kiosk=True)- assert loop._should_filter_operation(FocusCellNotification.name) is False- assert (- loop._should_filter_operation(CompletionResultNotification.name)- is True- )+ 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_derived_flag_follows_live_value() -> None:- state = {"kiosk": True}- loop = WebSocketMessageLoop(- websocket=MagicMock(),- message_queue=MagicMock(),- is_kiosk=lambda: state["kiosk"],- on_disconnect=MagicMock(),- on_check_status_update=MagicMock(),- )- assert loop._should_filter_operation(FocusCellNotification.name) is False- state["kiosk"] = False # takeover happened- assert loop._should_filter_operation(FocusCellNotification.name) is True+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/ws/test_ws_connection_validator.py b/tests/_server/api/endpoints/ws/test_ws_connection_validator.pynew file mode 100644index 0000000000..b1e9129348--- /dev/null+++ b/tests/_server/api/endpoints/ws/test_ws_connection_validator.py@@ -0,0 +1,86 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++from typing import Any+from unittest.mock import MagicMock++from marimo._server.api.endpoints.ws.ws_connection_validator import (+ ConnectionParams,+ ConnectionRejection,+ parse_connection_params,+)+from marimo._server.codes import WebSocketCloseReason, WebSocketCodes+++def _app_state(+ query: dict[str, str] | None = None,+ unique_file_key: str | None = "test.py",+ rtc_v2: bool = False,+) -> MagicMock:+ query = query or {}+ config: dict[str, Any] = {+ "runtime": {"auto_instantiate": True},+ "experimental": {"rtc_v2": rtc_v2},+ }+ app_state = MagicMock()+ app_state.query_params.side_effect = query.get+ workspace = app_state.session_manager.workspace+ workspace.get_unique_file_key.return_value = unique_file_key+ manager = app_state.config_manager_at_file.return_value+ manager.get_config.return_value = config+ return app_state+++def test_missing_session_id_is_rejected() -> None:+ result = parse_connection_params(_app_state())+ assert result == ConnectionRejection(+ WebSocketCodes.NORMAL_CLOSE, WebSocketCloseReason.NO_SESSION_ID+ )+++def test_missing_file_key_is_rejected() -> None:+ result = parse_connection_params(+ _app_state(query={"session_id": "123"}, unique_file_key=None)+ )+ assert result == ConnectionRejection(+ WebSocketCodes.NORMAL_CLOSE, WebSocketCloseReason.NO_FILE_KEY+ )+++def test_extracts_params() -> None:+ result = parse_connection_params(+ _app_state(query={"session_id": "123", "kiosk": "true"})+ )+ assert result == ConnectionParams(+ session_id="123",+ file_key="test.py",+ kiosk=True,+ auto_instantiate=True,+ rtc_enabled=False,+ )+++def test_file_query_param_wins_over_unique_file_key() -> None:+ result = parse_connection_params(+ _app_state(query={"session_id": "123", "file": "other.py"})+ )+ assert isinstance(result, ConnectionParams)+ assert result.file_key == "other.py"+++def test_rtc_enabled_from_config() -> None:+ result = parse_connection_params(+ _app_state(query={"session_id": "123"}, rtc_v2=True)+ )+ assert isinstance(result, ConnectionParams)+ assert result.rtc_enabled is True+++def test_allow_rtc_false_disables_rtc() -> None:+ # The SSE transport cannot carry the /ws_sync document stream+ result = parse_connection_params(+ _app_state(query={"session_id": "123"}, rtc_v2=True),+ allow_rtc=False,+ )+ assert isinstance(result, ConnectionParams)+ assert result.rtc_enabled is Falsediff --git a/tests/_server/api/endpoints/ws/test_ws_formatter.py b/tests/_server/api/endpoints/ws/test_ws_formatter.pyindex 64dc2a768a..c8d0e4c5fa 100644--- a/tests/_server/api/endpoints/ws/test_ws_formatter.py+++ b/tests/_server/api/endpoints/ws/test_ws_formatter.py@@ -9,7 +9,7 @@ from marimo._messaging.notification import ()from marimo._server.api.endpoints.ws.ws_formatter import (format_wire_message,- serialize_notification_for_websocket,+ serialize_notification_for_wire,)@@ -69,14 +69,14 @@ class TestFormatWireMessage:class TestSerializeNotificationForWebsocket:- """Tests for serialize_notification_for_websocket function."""+ """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_websocket(notification)+ result = serialize_notification_for_wire(notification)parsed = json.loads(result)assert parsed["op"] == "kernel-startup-error"@@ -91,7 +91,7 @@ class TestSerializeNotificationForWebsocket:title="Test Alert",description="This is a test alert message",)- result = serialize_notification_for_websocket(notification)+ result = serialize_notification_for_wire(notification)parsed = json.loads(result)assert parsed["op"] == "alert"@@ -105,7 +105,7 @@ class TestSerializeNotificationForWebsocket:description="Something went wrong",variant="danger",)- result = serialize_notification_for_websocket(notification)+ result = serialize_notification_for_wire(notification)parsed = json.loads(result)assert parsed["op"] == "alert"@@ -116,7 +116,7 @@ class TestSerializeNotificationForWebsocket:notification = KernelStartupErrorNotification(error='Error with "quotes" and special chars: <>&')- result = serialize_notification_for_websocket(notification)+ result = serialize_notification_for_wire(notification)# Should not raiseparsed = json.loads(result)@@ -134,7 +134,7 @@ class TestIntegration:{"op": "operation-name", "data": {...notification fields...}}"""notification = KernelStartupErrorNotification(error="test error")- result = serialize_notification_for_websocket(notification)+ result = serialize_notification_for_wire(notification)parsed = json.loads(result)