Skip to content

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

Remove the editor's old connection transports (#11414)

Trevor Manzd7f4cb370130
diff --git a/frontend/src/core/host/AGENTS.md b/frontend/src/core/host/AGENTS.md
index d52406a8ce..c2eafafdb3 100644
--- a/frontend/src/core/host/AGENTS.md
+++ b/frontend/src/core/host/AGENTS.md
@@ -5,11 +5,12 @@ Production code may import host modules, `@marimo-team/client`,
`marimo/host-imports`. Tests are exempt.
The protocol schemas and types live in `@marimo-team/client/protocol`.
-The native `marimo` event is a marimo extension and is defined in `events.ts`.
Define interfaces here and inject application behavior through adapters.
-`stream.ts` reduces stream events into one state. Each kind of object is a
-`Resource` in `resources/` with pure handlers keyed by event name. The stream
-handles phase, notebook identity, and control events itself. The client holds
-one state atom and exposes derived atoms.
+`notebook-client.ts` follows the notebook with `NotebookEvents` from
+`@marimo-team/client`, over a `NotebookTransport` the editor supplies. The
+editor's transports for its session routes live in
+`core/websocket/transports/notebook.ts`. Each kind of object is a `NotebookResource`
+in `resources/` with pure handlers keyed by event name, composed with
+`createNotebookReducer`. The client holds one state atom and exposes derived atoms.
diff --git a/frontend/src/core/host/__tests__/events.test.ts b/frontend/src/core/host/__tests__/events.test.ts
deleted file mode 100644
index 02d32b571a..0000000000
--- a/frontend/src/core/host/__tests__/events.test.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-/* Copyright 2026 Marimo. All rights reserved. */
-
-import { describe, expect, expectTypeOf, it } from "vitest";
-import { z } from "zod";
-import { type NotebookEvent, parseNotebookEvent } from "../events";
-
-describe("notebook messages", () => {
- it("normalizes session and host envelopes for native marimo messages", () => {
- const notification = {
- op: "variables",
- variables: [{ name: "x", value: Number.NaN }],
- };
- expectTypeOf<
- Extract<NotebookEvent, { event: "marimo" }>["data"]["marimo"]
- >().toBeUnknown();
- const host = { event: "marimo", data: { marimo: notification } };
- expect(parseNotebookEvent({ data: notification })).toEqual(host);
- expect(parseNotebookEvent({ ...host, id: "42" })).toEqual({
- ...host,
- id: "42",
- });
- });
-
- it("retains unknown event cursors without interpreting their payloads", () => {
- expect(
- parseNotebookEvent({ event: "future", id: "42", data: null }),
- ).toEqual({ event: "unknown", name: "future", id: "42" });
- });
-
- it("decodes known events outside the client's subscription filters", () => {
- const event = {
- event: "run.removed",
- id: "42",
- data: { id: "r1", time: "2026-10-19T12:00:00Z" },
- };
- expect(parseNotebookEvent(event)).toEqual(event);
- });
-
- it.each([
- { event: "cell", id: "42", data: { cell: { id: "c1" } } },
- { event: "run.removed", id: "42", data: {} },
- { event: "ready", data: {} },
- { event: "marimo", data: {} },
- {},
- null,
- ])("rejects malformed known messages: %j", (message) => {
- expect(() => parseNotebookEvent(message)).toThrow(z.ZodError);
- });
-});
diff --git a/frontend/src/core/host/connection.ts b/frontend/src/core/host/connection.ts
index 6ab17aabe4..e71802307b 100644
--- a/frontend/src/core/host/connection.ts
+++ b/frontend/src/core/host/connection.ts
@@ -37,45 +37,6 @@ export type ConnectionStatus =
/** The recovery policy for a closed connection. */
export interface CloseDecision {
- kind: "terminal" | "gave-up" | "retry";
+ kind: "terminal" | "retry";
status: ConnectionStatus;
}
-
-export type ConnectionEvent = "open" | "close" | "message" | "error";
-
-export interface IConnectionTransportMap {
- open: WebSocketEventMap["open"];
- message: WebSocketEventMap["message"];
- close: WebSocketEventMap["close"];
- error: WebSocketEventMap["error"];
-}
-
-export type ConnectionTransportCallback<T extends ConnectionEvent> = (
- data: IConnectionTransportMap[T],
-) => void;
-
-/** Transport readiness, using the WebSocket readyState values. */
-export const TransportReadyState = {
- CONNECTING: 0,
- OPEN: 1,
- CLOSING: 2,
- CLOSED: 3,
-} as const;
-
-export type TransportReadyState =
- (typeof TransportReadyState)[keyof typeof TransportReadyState];
-
-/** A reconnectable source of notebook messages. */
-export interface NotebookTransport {
- reconnect(code?: number | undefined, reason?: string | undefined): void;
- close(): void;
- addEventListener<T extends ConnectionEvent>(
- event: T,
- callback: ConnectionTransportCallback<T>,
- ): void;
- removeEventListener<T extends ConnectionEvent>(
- event: T,
- callback: ConnectionTransportCallback<T>,
- ): void;
- readyState: TransportReadyState;
-}
diff --git a/frontend/src/core/host/events.ts b/frontend/src/core/host/events.ts
deleted file mode 100644
index f982aaef5d..0000000000
--- a/frontend/src/core/host/events.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-/* Copyright 2026 Marimo. All rights reserved. */
-
-import { z } from "zod";
-import * as Protocol from "@marimo-team/client/protocol";
-
-/**
- * Notebook stream events, including native marimo notifications.
- *
- * Known events follow the generated protocol. Unknown events retain their name
- * and cursor so clients can skip them without losing their place in the stream.
- */
-
-const envelope = z.object({
- event: z.string().min(1),
- data: z.unknown(),
- id: z.string().min(1).optional(),
-});
-
-const knownNames = new Set<string>(
- Protocol.Event.options.flatMap((schema) => schema.shape.event.options),
-);
-
-/**
- * A native marimo message carried by a host stream.
- *
- * The protocol leaves extension events to their producer. The payload is
- * passed through for the session handler to interpret.
- */
-const MarimoEvent = z.object({
- event: z.literal("marimo"),
- id: z.string().min(1).optional(),
- data: z.object({ marimo: z.unknown() }),
-});
-
-/** A decoded event, or the name and cursor of an unrecognized event. */
-export type NotebookEvent =
- | Protocol.EventOutput
- | z.output<typeof MarimoEvent>
- | {
- readonly event: "unknown";
- readonly name: string;
- readonly id?: string;
- };
-
-const sessionEnvelope = z.object({ data: z.unknown() });
-
-/**
- * Decode a host event or an in-process WASM `{ data: notification }` message.
- *
- * Throws if the envelope or a known event is malformed. Native notification
- * payloads are passed through for the session handler to interpret.
- */
-export function parseNotebookEvent(value: unknown): NotebookEvent {
- if (typeof value === "object" && value !== null && !("event" in value)) {
- return {
- event: "marimo",
- data: { marimo: sessionEnvelope.parse(value).data },
- };
- }
- const parsed = envelope.parse(value);
- if (parsed.event === "marimo") {
- return MarimoEvent.parse(parsed);
- }
- if (knownNames.has(parsed.event)) {
- return Protocol.Event.parse(parsed);
- }
- return { event: "unknown", name: parsed.event, id: parsed.id };
-}
diff --git a/frontend/src/core/wasm/bridge.ts b/frontend/src/core/wasm/bridge.ts
index 5fc8ca87df..9aa2ca80fd 100644
--- a/frontend/src/core/wasm/bridge.ts
+++ b/frontend/src/core/wasm/bridge.ts
@@ -38,8 +38,6 @@ import type {
} from "../network/types";
import { filenameAtom } from "../saving/file-state";
import { store } from "../state/jotai";
-import { BasicTransport } from "../websocket/transports/basic";
-import type { IConnectionTransport } from "../websocket/transports/transport";
import { PyodideRouter } from "./router";
import { getWorkerRPC } from "./rpc";
import { getWasmRuntimeConfig } from "./runtime-config";
@@ -719,12 +717,6 @@ export class PyodideBridge implements RunRequests, EditRequests {
}
}
-export function createPyodideConnection(): IConnectionTransport {
- return BasicTransport.withProducerCallback((callback) => {
- PyodideBridge.INSTANCE.attachMessageConsumer(callback);
- });
-}
-
// Compose the worker name. The optional "::controller" suffix tells
// getController.ts that the host page provides a custom /wasm/controller.js
// and that the dynamic import should be attempted. Hosts opt in by setting
diff --git a/frontend/src/core/websocket/__tests__/connection-state.test.ts b/frontend/src/core/websocket/__tests__/connection-state.test.ts
index d40af075ab..8cbfcb4075 100644
--- a/frontend/src/core/websocket/__tests__/connection-state.test.ts
+++ b/frontend/src/core/websocket/__tests__/connection-state.test.ts
@@ -64,16 +64,4 @@ describe("classifyCloseEvent", () => {
});
});
});
-
- describe("transport exhaustion", () => {
- it("MARIMO_TRANSPORT_EXHAUSTED → gave-up with KERNEL_DISCONNECTED", () => {
- const decision = classify("MARIMO_TRANSPORT_EXHAUSTED");
- expect(decision.kind).toBe("gave-up");
- expect(decision.status).toEqual({
- state: ConnectionState.CLOSED,
- code: WebSocketClosedReason.KERNEL_DISCONNECTED,
- reason: "kernel not found",
- });
- });
- });
});
diff --git a/frontend/src/core/websocket/__tests__/createConnectionTransport.test.ts b/frontend/src/core/websocket/__tests__/createConnectionTransport.test.ts
deleted file mode 100644
index 8d70252c96..0000000000
--- a/frontend/src/core/websocket/__tests__/createConnectionTransport.test.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-/* 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 "../transports/create";
-
-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/connection-state.ts b/frontend/src/core/websocket/connection-state.ts
index 921e6a7574..9f4116a99f 100644
--- a/frontend/src/core/websocket/connection-state.ts
+++ b/frontend/src/core/websocket/connection-state.ts
@@ -2,22 +2,12 @@
import type { CloseDecision } from "../host/connection";
import { Logger } from "@/utils/Logger";
-import { TRANSPORT_EXHAUSTED_REASON } from "./transports/ws";
import { ConnectionState, WebSocketClosedReason } from "./types";
// Keep server reasons in sync with ws_endpoint.py and ws/*.py.
// SSE carries the same reasons in close events. Unclassified reasons retry.
export function classifyCloseEvent(event: { reason?: string }): CloseDecision {
switch (event.reason) {
- case TRANSPORT_EXHAUSTED_REASON:
- return {
- kind: "gave-up",
- status: {
- state: ConnectionState.CLOSED,
- code: WebSocketClosedReason.KERNEL_DISCONNECTED,
- reason: "kernel not found",
- },
- };
case "MARIMO_NO_FILE_KEY":
case "MARIMO_NO_SESSION_ID":
case "MARIMO_NO_SESSION":
diff --git a/frontend/src/core/websocket/transports/__tests__/basic.test.ts b/frontend/src/core/websocket/transports/__tests__/basic.test.ts
deleted file mode 100644
index e510b346f8..0000000000
--- a/frontend/src/core/websocket/transports/__tests__/basic.test.ts
+++ /dev/null
@@ -1,275 +0,0 @@
-/* Copyright 2026 Marimo. All rights reserved. */
-
-import { describe, expect, it, vi } from "vitest";
-import { BasicTransport } from "../basic";
-
-describe("BasicTransport", () => {
- describe("close", () => {
- it("should trigger close event", () => {
- const transport = BasicTransport.empty();
- const closeCallback = vi.fn();
-
- transport.addEventListener("close", closeCallback);
- transport.close();
-
- expect(closeCallback).toHaveBeenCalledTimes(1);
- expect(closeCallback).toHaveBeenCalledWith(expect.any(Event));
- });
- });
-
- describe("reconnect", () => {
- it("should trigger close and open events", async () => {
- const transport = BasicTransport.empty();
- const openCallback = vi.fn();
- const closeCallback = vi.fn();
-
- transport.addEventListener("open", openCallback);
- transport.addEventListener("close", closeCallback);
-
- // Clear the initial open callback
- openCallback.mockClear();
-
- transport.reconnect();
-
- // Wait for connect to complete
- await new Promise((resolve) => setTimeout(resolve, 10));
-
- expect(closeCallback).toHaveBeenCalledTimes(1);
- expect(openCallback).toHaveBeenCalledTimes(1);
- });
- });
-
- describe("send", () => {
- it("should trigger message event with string data", async () => {
- const transport = BasicTransport.empty();
- const messageCallback = vi.fn();
-
- transport.addEventListener("message", messageCallback);
-
- transport.send("test message");
-
- expect(messageCallback).toHaveBeenCalledTimes(1);
- expect(messageCallback).toHaveBeenCalledWith(
- expect.objectContaining({
- data: "test message",
- }),
- );
- });
-
- it("should trigger message event with ArrayBuffer data", async () => {
- const transport = BasicTransport.empty();
- const messageCallback = vi.fn();
-
- transport.addEventListener("message", messageCallback);
-
- const buffer = new ArrayBuffer(8);
- transport.send(buffer);
-
- expect(messageCallback).toHaveBeenCalledTimes(1);
- expect(messageCallback).toHaveBeenCalledWith(
- expect.objectContaining({
- data: buffer,
- }),
- );
- });
- });
-
- describe("addEventListener", () => {
- it("should add open event listener and call it immediately", () => {
- const transport = BasicTransport.empty();
- const callback = vi.fn();
-
- transport.addEventListener("open", callback);
-
- expect(callback).toHaveBeenCalledTimes(1);
- expect(callback).toHaveBeenCalledWith(expect.any(Event));
- });
-
- it("should add message event listener and start producer", () => {
- const producer = vi.fn();
- const transport = BasicTransport.withProducerCallback(producer);
- const callback = vi.fn();
-
- transport.addEventListener("message", callback);
-
- // Producer should be called once
- expect(producer).toHaveBeenCalledTimes(1);
- expect(producer).toHaveBeenCalledWith(expect.any(Function));
- });
- });
-
- describe("removeEventListener", () => {
- it("should remove event listener", async () => {
- const transport = BasicTransport.empty();
- const callback = vi.fn();
-
- transport.addEventListener("message", callback);
- transport.removeEventListener("message", callback);
-
- transport.send("test");
-
- expect(callback).not.toHaveBeenCalled();
- });
-
- it("should only remove the specific listener", () => {
- const transport = BasicTransport.empty();
- const callback1 = vi.fn();
- const callback2 = vi.fn();
-
- transport.addEventListener("close", callback1);
- transport.addEventListener("close", callback2);
-
- transport.removeEventListener("close", callback1);
-
- transport.close();
-
- expect(callback1).not.toHaveBeenCalled();
- expect(callback2).toHaveBeenCalledTimes(1);
- });
- });
-
- describe("Producer functionality", () => {
- it("should pass producer callback that triggers message events", () => {
- let producerCallback: ((message: MessageEvent) => void) | undefined;
- const producer = vi.fn((callback) => {
- producerCallback = callback;
- });
- const transport = BasicTransport.withProducerCallback(producer);
- const messageCallback = vi.fn();
-
- transport.addEventListener("message", messageCallback);
-
- expect(producerCallback).toBeDefined();
-
- const testMessage = new MessageEvent("message", { data: "test" });
- producerCallback?.(testMessage);
-
- expect(messageCallback).toHaveBeenCalledWith(testMessage);
- });
-
- it("should handle multiple messages from producer", () => {
- let producerCallback: ((message: MessageEvent) => void) | undefined;
- const producer = vi.fn((callback) => {
- producerCallback = callback;
- });
- const transport = BasicTransport.withProducerCallback(producer);
- const messageCallback = vi.fn();
-
- transport.addEventListener("message", messageCallback);
-
- producerCallback?.(new MessageEvent("message", { data: "msg1" }));
- producerCallback?.(new MessageEvent("message", { data: "msg2" }));
- producerCallback?.(new MessageEvent("message", { data: "msg3" }));
-
- expect(messageCallback).toHaveBeenCalledTimes(3);
- expect(messageCallback).toHaveBeenNthCalledWith(
- 1,
- expect.objectContaining({ data: "msg1" }),
- );
- expect(messageCallback).toHaveBeenNthCalledWith(
- 2,
- expect.objectContaining({ data: "msg2" }),
- );
- expect(messageCallback).toHaveBeenNthCalledWith(
- 3,
- expect.objectContaining({ data: "msg3" }),
- );
- });
-
- it("should not start producer if no message listener is added", () => {
- const producer = vi.fn();
- const transport = BasicTransport.withProducerCallback(producer);
-
- transport.addEventListener("open", vi.fn());
- transport.addEventListener("close", vi.fn());
-
- expect(producer).not.toHaveBeenCalled();
- });
- });
-
- describe("Integration scenarios", () => {
- it("should handle complete connection lifecycle", async () => {
- const transport = BasicTransport.empty();
- const openCallback = vi.fn();
- const closeCallback = vi.fn();
-
- transport.addEventListener("open", openCallback);
- transport.addEventListener("close", closeCallback);
-
- expect(openCallback).toHaveBeenCalledTimes(1);
-
- transport.reconnect();
- await new Promise((resolve) => setTimeout(resolve, 10));
- expect(openCallback).toHaveBeenCalledTimes(2);
- expect(closeCallback).toHaveBeenCalledTimes(1);
-
- transport.close();
- expect(closeCallback).toHaveBeenCalledTimes(2);
- });
-
- it("should handle send and receive flow", async () => {
- let producerCallback: ((message: MessageEvent) => void) | undefined;
- const producer = vi.fn((callback) => {
- producerCallback = callback;
- });
- const transport = BasicTransport.withProducerCallback(producer);
- const messageCallback = vi.fn();
-
- transport.addEventListener("message", messageCallback);
-
- transport.send("outgoing");
- expect(messageCallback).toHaveBeenCalledWith(
- expect.objectContaining({ data: "outgoing" }),
- );
-
- messageCallback.mockClear();
-
- producerCallback?.(new MessageEvent("message", { data: "incoming" }));
- expect(messageCallback).toHaveBeenCalledWith(
- expect.objectContaining({ data: "incoming" }),
- );
- });
-
- it("should maintain separate event queues for different event types", async () => {
- const transport = BasicTransport.empty();
- const openCallback = vi.fn();
- const closeCallback = vi.fn();
- const messageCallback = vi.fn();
-
- transport.addEventListener("open", openCallback);
- transport.addEventListener("close", closeCallback);
- transport.addEventListener("message", messageCallback);
-
- openCallback.mockClear();
-
- transport.reconnect();
- await new Promise((resolve) => setTimeout(resolve, 10));
- transport.send("test");
- transport.close();
-
- expect(openCallback).toHaveBeenCalledTimes(1);
- expect(messageCallback).toHaveBeenCalledTimes(1);
- expect(closeCallback).toHaveBeenCalledTimes(2);
- });
-
- it("should handle rapid reconnections", async () => {
- const transport = BasicTransport.empty();
- const openCallback = vi.fn();
- const closeCallback = vi.fn();
-
- transport.addEventListener("open", openCallback);
- transport.addEventListener("close", closeCallback);
-
- openCallback.mockClear();
-
- transport.reconnect();
- transport.reconnect();
- transport.reconnect();
-
- await new Promise((resolve) => setTimeout(resolve, 20));
-
- expect(closeCallback).toHaveBeenCalledTimes(3);
- expect(openCallback).toHaveBeenCalledTimes(3);
- });
- });
-});
diff --git a/frontend/src/core/websocket/transports/__tests__/sse.test.ts b/frontend/src/core/websocket/transports/__tests__/sse.test.ts
deleted file mode 100644
index afb890fb0c..0000000000
--- a/frontend/src/core/websocket/transports/__tests__/sse.test.ts
+++ /dev/null
@@ -1,352 +0,0 @@
-/* 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("preserves host event names and cursors without carrying IDs into snapshots", async () => {
- const { stream, push } = createControllableStream();
- fetchMock.mockResolvedValueOnce(sseResponse(stream));
- transport.reconnect();
- await vi.waitFor(() => expect(opens).toHaveLength(1));
-
- push("id: cursor-1\nevent: rea");
- push("dy\ndata: {}\n\n: keep-alive\n\nevent: reset\ndata: {}\n\n");
- push('event: marimo\ndata: {"marimo":\ndata: {"op":"reconnected"}}\n\n');
- await vi.waitFor(() => expect(messages).toHaveLength(3));
- expect(messages.map((message) => JSON.parse(message.data))).toEqual([
- { event: "ready", id: "cursor-1", data: {} },
- { event: "reset", data: {} },
- { event: "marimo", data: { marimo: { op: "reconnected" } } },
- ]);
- });
-
- it("ignores keep-alive comments", async () => {
- const { stream, push } = createControllableStream();
- fetchMock.mockResolvedValueOnce(sseResponse(stream));
- 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));
-
- 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));
- // Reconnect synchronously from 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/__tests__/transport.test.ts b/frontend/src/core/websocket/transports/__tests__/transport.test.ts
deleted file mode 100644
index d8bd8c71f5..0000000000
--- a/frontend/src/core/websocket/transports/__tests__/transport.test.ts
+++ /dev/null
@@ -1,308 +0,0 @@
-/* Copyright 2026 Marimo. All rights reserved. */
-
-import { describe, expect, it, vi } from "vitest";
-import { ConnectionSubscriptions } from "../transport";
-
-describe("ConnectionSubscriptions", () => {
- describe("addSubscription", () => {
- it("should add a subscription for an event", () => {
- const subscriptions = new ConnectionSubscriptions();
- const callback = vi.fn();
-
- subscriptions.addSubscription("open", callback);
-
- // Verify by notifying
- subscriptions.notify("open", new Event("open"));
- expect(callback).toHaveBeenCalledTimes(1);
- });
-
- it("should add multiple subscriptions for the same event", () => {
- const subscriptions = new ConnectionSubscriptions();
- const callback1 = vi.fn();
- const callback2 = vi.fn();
- const callback3 = vi.fn();
-
- subscriptions.addSubscription("message", callback1);
- subscriptions.addSubscription("message", callback2);
- subscriptions.addSubscription("message", callback3);
-
- const messageEvent = new MessageEvent("message", { data: "test" });
- subscriptions.notify("message", messageEvent);
-
- expect(callback1).toHaveBeenCalledWith(messageEvent);
- expect(callback2).toHaveBeenCalledWith(messageEvent);
- expect(callback3).toHaveBeenCalledWith(messageEvent);
- });
-
- it("should add subscriptions for different event types", () => {
- const subscriptions = new ConnectionSubscriptions();
- const openCallback = vi.fn();
- const closeCallback = vi.fn();
- const messageCallback = vi.fn();
-
- subscriptions.addSubscription("open", openCallback);
- subscriptions.addSubscription("close", closeCallback);
- subscriptions.addSubscription("message", messageCallback);
-
- subscriptions.notify("open", new Event("open"));
- expect(openCallback).toHaveBeenCalledTimes(1);
- expect(closeCallback).not.toHaveBeenCalled();
- expect(messageCallback).not.toHaveBeenCalled();
- });
-
- it("should not add duplicate subscriptions for the same callback", () => {
- const subscriptions = new ConnectionSubscriptions();
- const callback = vi.fn();
-
- subscriptions.addSubscription("close", callback);
- subscriptions.addSubscription("close", callback);
- subscriptions.addSubscription("close", callback);
-
- subscriptions.notify("close", new Event("close"));
-
- // Set only stores unique callbacks, so should be called once
- expect(callback).toHaveBeenCalledTimes(1);
- });
- });
-
- describe("removeSubscription", () => {
- it("should remove a subscription", () => {
- const subscriptions = new ConnectionSubscriptions();
- const callback = vi.fn();
-
- subscriptions.addSubscription("message", callback);
- subscriptions.removeSubscription("message", callback);
-
- const messageEvent = new MessageEvent("message", { data: "test" });
- subscriptions.notify("message", messageEvent);
-
- expect(callback).not.toHaveBeenCalled();
- });
-
- it("should only remove the specific callback", () => {
- const subscriptions = new ConnectionSubscriptions();
- const callback1 = vi.fn();
- const callback2 = vi.fn();
- const callback3 = vi.fn();
-
- subscriptions.addSubscription("close", callback1);
- subscriptions.addSubscription("close", callback2);
- subscriptions.addSubscription("close", callback3);
-
- subscriptions.removeSubscription("close", callback2);
-
- subscriptions.notify("close", new Event("close"));
-
- expect(callback1).toHaveBeenCalledTimes(1);
- expect(callback2).not.toHaveBeenCalled();
- expect(callback3).toHaveBeenCalledTimes(1);
- });
-
- it("should handle removing subscription from non-existent event type", () => {
- const subscriptions = new ConnectionSubscriptions();
- const callback = vi.fn();
-
- subscriptions.addSubscription("open", callback);
-
- expect(() =>
- subscriptions.removeSubscription("close", callback),
- ).not.toThrow();
-
- subscriptions.notify("open", new Event("open"));
- expect(callback).toHaveBeenCalledTimes(1);
- });
- });
-
- describe("notify", () => {
- it("should notify all subscribed callbacks for an event", () => {
- const subscriptions = new ConnectionSubscriptions();
- const callback1 = vi.fn();
- const callback2 = vi.fn();
-
- subscriptions.addSubscription("open", callback1);
- subscriptions.addSubscription("open", callback2);
-
- const openEvent = new Event("open");
- subscriptions.notify("open", openEvent);
-
- expect(callback1).toHaveBeenCalledWith(openEvent);
- expect(callback2).toHaveBeenCalledWith(openEvent);
- });
-
- it("should pass the correct data to callbacks", () => {
- const subscriptions = new ConnectionSubscriptions();
- const callback = vi.fn();
-
- subscriptions.addSubscription("message", callback);
-
- const messageEvent = new MessageEvent("message", {
- data: "test data",
- });
- subscriptions.notify("message", messageEvent);
-
- expect(callback).toHaveBeenCalledWith(messageEvent);
- expect(callback.mock.calls[0][0].data).toBe("test data");
- });
-
- it("should not notify callbacks for different event types", () => {
- const subscriptions = new ConnectionSubscriptions();
- const openCallback = vi.fn();
- const closeCallback = vi.fn();
-
- subscriptions.addSubscription("open", openCallback);
- subscriptions.addSubscription("close", closeCallback);
-
- subscriptions.notify("open", new Event("open"));
-
- expect(openCallback).toHaveBeenCalledTimes(1);
- expect(closeCallback).not.toHaveBeenCalled();
- });
-
- it("should handle exceptions in callbacks without affecting other callbacks", () => {
- const subscriptions = new ConnectionSubscriptions();
- const throwingCallback = vi.fn(() => {
- throw new Error("Callback error");
- });
- const normalCallback = vi.fn();
-
- subscriptions.addSubscription("message", throwingCallback);
- subscriptions.addSubscription("message", normalCallback);
-
- const messageEvent = new MessageEvent("message", { data: "test" });
-
- expect(() => subscriptions.notify("message", messageEvent)).toThrow(
- "Callback error",
- );
-
- expect(throwingCallback).toHaveBeenCalledWith(messageEvent);
- expect(normalCallback).not.toHaveBeenCalled();
- });
- });
-
- describe("Integration scenarios", () => {
- it("should handle complete subscription lifecycle", () => {
- const subscriptions = new ConnectionSubscriptions();
- const callback = vi.fn();
-
- subscriptions.addSubscription("open", callback);
-
- subscriptions.notify("open", new Event("open"));
- expect(callback).toHaveBeenCalledTimes(1);
-
- subscriptions.removeSubscription("open", callback);
-
- subscriptions.notify("open", new Event("open"));
- expect(callback).toHaveBeenCalledTimes(1);
- });
-
- it("should handle multiple events with multiple callbacks", () => {
- const subscriptions = new ConnectionSubscriptions();
-
- const openCallback1 = vi.fn();
- const openCallback2 = vi.fn();
- const closeCallback1 = vi.fn();
- const messageCallback = vi.fn();
-
- subscriptions.addSubscription("open", openCallback1);
- subscriptions.addSubscription("open", openCallback2);
- subscriptions.addSubscription("close", closeCallback1);
- subscriptions.addSubscription("message", messageCallback);
-
- subscriptions.notify("open", new Event("open"));
- expect(openCallback1).toHaveBeenCalledTimes(1);
- expect(openCallback2).toHaveBeenCalledTimes(1);
- expect(closeCallback1).not.toHaveBeenCalled();
- expect(messageCallback).not.toHaveBeenCalled();
-
- const messageEvent = new MessageEvent("message", { data: "test" });
- subscriptions.notify("message", messageEvent);
- expect(openCallback1).toHaveBeenCalledTimes(1);
- expect(openCallback2).toHaveBeenCalledTimes(1);
- expect(closeCallback1).not.toHaveBeenCalled();
- expect(messageCallback).toHaveBeenCalledTimes(1);
- expect(messageCallback).toHaveBeenCalledWith(messageEvent);
-
- subscriptions.notify("close", new Event("close"));
- expect(openCallback1).toHaveBeenCalledTimes(1);
- expect(openCallback2).toHaveBeenCalledTimes(1);
- expect(closeCallback1).toHaveBeenCalledTimes(1);
- expect(messageCallback).toHaveBeenCalledTimes(1);
- });
-
- it("should handle add and remove operations interleaved", () => {
- const subscriptions = new ConnectionSubscriptions();
- const callback1 = vi.fn();
- const callback2 = vi.fn();
- const callback3 = vi.fn();
-
- subscriptions.addSubscription("message", callback1);
- subscriptions.addSubscription("message", callback2);
-
- const msg1 = new MessageEvent("message", { data: "msg1" });
- subscriptions.notify("message", msg1);
-
- expect(callback1).toHaveBeenCalledWith(msg1);
- expect(callback2).toHaveBeenCalledWith(msg1);
- expect(callback3).not.toHaveBeenCalled();
-
- subscriptions.removeSubscription("message", callback1);
- subscriptions.addSubscription("message", callback3);
-
- const msg2 = new MessageEvent("message", { data: "msg2" });
- subscriptions.notify("message", msg2);
-
- expect(callback1).toHaveBeenCalledTimes(1);
- expect(callback2).toHaveBeenCalledWith(msg2);
- expect(callback3).toHaveBeenCalledWith(msg2);
- });
-
- it("should maintain separate subscription lists per event type", () => {
- const subscriptions = new ConnectionSubscriptions();
- const callback = vi.fn();
-
- subscriptions.addSubscription("open", callback);
- subscriptions.addSubscription("close", callback);
- subscriptions.addSubscription("message", callback);
-
- subscriptions.removeSubscription("close", callback);
-
- subscriptions.notify("open", new Event("open"));
- expect(callback).toHaveBeenCalledTimes(1);
-
- subscriptions.notify(
- "message",
- new MessageEvent("message", { data: "test" }),
- );
- expect(callback).toHaveBeenCalledTimes(2);
-
- subscriptions.notify("close", new Event("close"));
- expect(callback).toHaveBeenCalledTimes(2);
- });
- });
-
- describe("Edge cases", () => {
- it("should handle callback that modifies subscriptions", () => {
- const subscriptions = new ConnectionSubscriptions();
- const callback1 = vi.fn();
- const callback2 = vi.fn(() => {
- subscriptions.removeSubscription("message", callback1);
- });
-
- subscriptions.addSubscription("message", callback1);
- subscriptions.addSubscription("message", callback2);
-
- const messageEvent = new MessageEvent("message", { data: "test" });
- subscriptions.notify("message", messageEvent);
-
- expect(callback1).toHaveBeenCalledTimes(1);
- expect(callback2).toHaveBeenCalledTimes(1);
-
- callback1.mockClear();
- callback2.mockClear();
-
- subscriptions.notify("message", messageEvent);
- expect(callback1).not.toHaveBeenCalled();
- expect(callback2).toHaveBeenCalledTimes(1);
- });
- });
-});
diff --git a/frontend/src/core/websocket/transports/__tests__/ws.test.ts b/frontend/src/core/websocket/transports/__tests__/ws.test.ts
deleted file mode 100644
index 131e8c5a45..0000000000
--- a/frontend/src/core/websocket/transports/__tests__/ws.test.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-/* Copyright 2026 Marimo. All rights reserved. */
-
-import { beforeEach, describe, expect, it, vi } from "vitest";
-import { MAX_RETRIES, WsTransport, TRANSPORT_EXHAUSTED_REASON } from "../ws";
-
-let innerListeners: Record<string, ((e: unknown) => void)[]>;
-
-vi.mock("partysocket/ws", () => {
- class FakeReconnectingWebSocket {
- public retryCount = 0;
- public readyState = WebSocket.CONNECTING;
- public constructor() {
- innerListeners = { open: [], close: [], message: [], error: [] };
- }
- public addEventListener(event: string, cb: (e: unknown) => void) {
- innerListeners[event].push(cb);
- }
- public removeEventListener(event: string, cb: (e: unknown) => void) {
- innerListeners[event] = innerListeners[event].filter((c) => c !== cb);
- }
- public reconnect() {}
- public close() {}
- public send() {}
- }
- return { default: FakeReconnectingWebSocket };
-});
-
-interface FakeReconnectingWebSocket {
- retryCount: number;
- readyState: number;
-}
-
-function dispatchClose(reason = "") {
- const evt = new CloseEvent("close", { reason, code: 1006 });
- for (const cb of innerListeners.close) {
- cb(evt);
- }
-}
-
-describe("WsTransport", () => {
- let transport: WsTransport;
- let inner: FakeReconnectingWebSocket;
-
- beforeEach(() => {
- transport = new WsTransport(() => "ws://example.invalid/ws");
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- inner = (transport as any).inner;
- });
-
- describe("close event reason", () => {
- it("forwards the original reason before retry budget is exhausted", () => {
- const seen: CloseEvent[] = [];
- transport.addEventListener("close", (e) => seen.push(e));
-
- inner.retryCount = MAX_RETRIES - 1;
- dispatchClose("");
-
- expect(seen).toHaveLength(1);
- expect(seen[0].reason).toBe("");
- });
-
- it("rewrites reason to MARIMO_TRANSPORT_EXHAUSTED on exhaustion", () => {
- const seen: CloseEvent[] = [];
- transport.addEventListener("close", (e) => seen.push(e));
-
- inner.retryCount = MAX_RETRIES;
- dispatchClose("");
-
- expect(seen).toHaveLength(1);
- expect(seen[0].reason).toBe(TRANSPORT_EXHAUSTED_REASON);
- });
-
- it("does not rewrite a server-sent reason on exhaustion", () => {
- // If partysocket happens to deliver a real MARIMO_* reason at the same
- // moment the retry budget exhausts, the exhausted-state rewrite still
- // wins because the wrapper keys off retryCount, not the original reason.
- // Document the behavior so a future change is deliberate.
- const seen: CloseEvent[] = [];
- transport.addEventListener("close", (e) => seen.push(e));
-
- inner.retryCount = MAX_RETRIES;
- dispatchClose("MARIMO_SHUTDOWN");
-
- expect(seen[0].reason).toBe(TRANSPORT_EXHAUSTED_REASON);
- });
- });
-
- describe("addEventListener dedupe", () => {
- it("does not double-fire when the same close listener is added twice", () => {
- const cb = vi.fn();
- transport.addEventListener("close", cb);
- transport.addEventListener("close", cb);
-
- dispatchClose("");
-
- expect(cb).toHaveBeenCalledTimes(1);
- });
-
- it("a single removeEventListener fully unregisters a duplicated add", () => {
- const cb = vi.fn();
- transport.addEventListener("close", cb);
- transport.addEventListener("close", cb);
- transport.removeEventListener("close", cb);
-
- dispatchClose("");
-
- expect(cb).not.toHaveBeenCalled();
- // Inner socket has no orphaned wrappers left.
- expect(innerListeners.close).toHaveLength(0);
- });
- });
-
- describe("removeEventListener", () => {
- it("unregisters the right wrapper for close listeners", () => {
- const cb = vi.fn();
- transport.addEventListener("close", cb);
- transport.removeEventListener("close", cb);
-
- inner.retryCount = MAX_RETRIES;
- dispatchClose("");
-
- expect(cb).not.toHaveBeenCalled();
- });
- });
-});
diff --git a/frontend/src/core/websocket/transports/basic.ts b/frontend/src/core/websocket/transports/basic.ts
deleted file mode 100644
index 77fe860a64..0000000000
--- a/frontend/src/core/websocket/transports/basic.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-/* Copyright 2026 Marimo. All rights reserved. */
-
-import {
- type ConnectionEvent,
- ConnectionSubscriptions,
- type ConnectionTransportCallback,
- type IConnectionTransport,
-} from "./transport";
-
-type MessageProducer = (callback: (message: MessageEvent) => void) => void;
-
-export class BasicTransport implements IConnectionTransport {
- private subscriptions = new ConnectionSubscriptions();
- private producer?: MessageProducer;
-
- public static withProducerCallback(
- producer: MessageProducer,
- ): IConnectionTransport {
- return new BasicTransport(producer);
- }
-
- public static empty(): IConnectionTransport {
- return new BasicTransport();
- }
-
- private constructor(producer?: MessageProducer) {
- this.producer = producer;
- }
-
- private startProducer() {
- if (this.producer) {
- this.producer((message) => {
- this.subscriptions.notify("message", message);
- });
- }
- }
-
- private connect(): Promise<void> {
- return new Promise<void>((resolve) => setTimeout(resolve, 0)).then(() => {
- this.subscriptions.notify("open", new Event("open"));
- });
- }
-
- public get readyState(): WebSocket["readyState"] {
- return WebSocket.OPEN;
- }
-
- public reconnect(
- _code?: number | undefined,
- _reason?: string | undefined,
- ): void {
- this.close();
- this.connect();
- return;
- }
-
- public close(): void {
- this.subscriptions.notify("close", new Event("close"));
- }
-
- public send(
- data: string | ArrayBuffer | Blob | ArrayBufferView,
- ): Promise<void> {
- this.subscriptions.notify(
- "message",
- new MessageEvent("message", {
- data,
- }),
- );
- return Promise.resolve();
- }
-
- public addEventListener<T extends ConnectionEvent>(
- event: T,
- callback: ConnectionTransportCallback<T>,
- ): void {
- this.subscriptions.addSubscription(
- event,
- callback as ConnectionTransportCallback<ConnectionEvent>,
- );
-
- // Call open right away
- if (event === "open") {
- (callback as ConnectionTransportCallback<"open">)(new Event("open"));
- }
-
- // Start the producer when we have one consumer
- if (event === "message") {
- this.startProducer();
- }
- }
-
- public removeEventListener<T extends ConnectionEvent>(
- event: T,
- callback: ConnectionTransportCallback<T>,
- ): void {
- this.subscriptions.removeSubscription(
- event,
- callback as ConnectionTransportCallback<ConnectionEvent>,
- );
- }
-}
diff --git a/frontend/src/core/websocket/transports/create.ts b/frontend/src/core/websocket/transports/create.ts
deleted file mode 100644
index 016bf2d869..0000000000
--- a/frontend/src/core/websocket/transports/create.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-/* Copyright 2026 Marimo. All rights reserved. */
-
-import { createPyodideConnection } from "../../wasm/bridge";
-import { isWasm } from "../../wasm/utils";
-import { BasicTransport } from "./basic";
-import { SseTransport } from "./sse";
-import { WsTransport } from "./ws";
-import type { IConnectionTransport } from "./transport";
-
-export interface ConnectionTransportOptions {
- url: () => string;
- static: boolean;
- transportType: "websocket" | "sse";
- headers: () => Record<string, string>;
-}
-
-export function createConnectionTransport(
- options: ConnectionTransportOptions,
-): IConnectionTransport {
- if (options.static) {
- return BasicTransport.empty();
- }
- if (isWasm()) {
- return createPyodideConnection();
- }
- // Read the URL lazily to follow runtime redirects.
- if (options.transportType === "sse") {
- return new SseTransport(options.url, options.headers);
- }
- return new WsTransport(options.url);
-}
diff --git a/frontend/src/core/websocket/transports/sse.ts b/frontend/src/core/websocket/transports/sse.ts
deleted file mode 100644
index aba9556371..0000000000
--- a/frontend/src/core/websocket/transports/sse.ts
+++ /dev/null
@@ -1,320 +0,0 @@
-/* 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;
-
- public constructor(
- urlProvider: () => string,
- headersProvider: () => Record<string, string> = () => ({}),
- ) {
- this.urlProvider = urlProvider;
- this.headersProvider = headersProvider;
- }
-
- public get readyState(): WebSocket["readyState"] {
- return this.state;
- }
-
- public reconnect(_code?: number, _reason?: string): void {
- this.userClosed = false;
- this.retryCount = 0;
- this.clearRetryTimer();
- this.abortController?.abort();
- this.connect();
- }
-
- public close(): void {
- this.userClosed = true;
- this.clearRetryTimer();
- this.state = WebSocket.CLOSED;
- this.abortController?.abort();
- this.abortController = null;
- }
-
- public 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");
- }
-
- public addEventListener<T extends ConnectionEvent>(
- event: T,
- callback: ConnectionTransportCallback<T>,
- ): void {
- this.subscriptions.addSubscription(
- event,
- callback as ConnectionTransportCallback<ConnectionEvent>,
- );
- }
-
- public 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 eventId: string | null = null;
- let dataLines: string[] = [];
-
- const dispatch = (): ServerClose | null => {
- if (dataLines.length === 0) {
- eventName = null;
- eventId = null;
- return null;
- }
- const data = dataLines.join("\n");
- const name = eventName;
- const id = eventId;
- eventName = null;
- eventId = null;
- dataLines = [];
- if (name === "close") {
- return parseServerClose(data);
- }
- // 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;
- // Normalize SSE fields into the same envelope as host WebSockets.
- // Leave the payload text intact for the client's JSON decoder.
- const envelope =
- name === null
- ? data
- : `{"event":${JSON.stringify(name)},"data":${data}${id === null ? "" : `,"id":${JSON.stringify(id)}`}}`;
- this.subscriptions.notify(
- "message",
- new MessageEvent("message", { data: envelope }),
- );
- 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;
- } else if (field === "id") {
- eventId = fieldValue;
- }
- // The host client owns the cursor; `retry` does not override our policy.
- }
- 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/transports/transport.ts b/frontend/src/core/websocket/transports/transport.ts
deleted file mode 100644
index bd8c5e6e4b..0000000000
--- a/frontend/src/core/websocket/transports/transport.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-/* Copyright 2026 Marimo. All rights reserved. */
-
-import type {
- NotebookTransport,
- ConnectionEvent,
- ConnectionTransportCallback,
- IConnectionTransportMap,
-} from "../../host/connection";
-export type {
- ConnectionEvent,
- ConnectionTransportCallback,
- IConnectionTransportMap,
-} from "../../host/connection";
-
-export interface IConnectionTransport extends NotebookTransport {
- send(data: string | ArrayBuffer | Blob | ArrayBufferView<ArrayBuffer>): void;
-}
-
-export class ConnectionSubscriptions {
- private subscriptions = new Map<
- ConnectionEvent,
- Set<ConnectionTransportCallback<ConnectionEvent>>
- >();
-
- public addSubscription(
- event: ConnectionEvent,
- callback: ConnectionTransportCallback<ConnectionEvent>,
- ): void {
- if (!this.subscriptions.has(event)) {
- this.subscriptions.set(event, new Set());
- }
- this.subscriptions.get(event)?.add(callback);
- }
-
- public removeSubscription(
- event: ConnectionEvent,
- callback: ConnectionTransportCallback<ConnectionEvent>,
- ): void {
- this.subscriptions.get(event)?.delete(callback);
- }
-
- public notify(
- event: ConnectionEvent,
- data: IConnectionTransportMap[ConnectionEvent],
- ): void {
- for (const callback of this.subscriptions.get(event) ?? []) {
- callback(data);
- }
- }
-}
diff --git a/frontend/src/core/websocket/transports/ws.ts b/frontend/src/core/websocket/transports/ws.ts
deleted file mode 100644
index 92d2ffbb25..0000000000
--- a/frontend/src/core/websocket/transports/ws.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-/* Copyright 2026 Marimo. All rights reserved. */
-
-import ReconnectingWebSocket from "partysocket/ws";
-import type {
- ConnectionEvent,
- ConnectionTransportCallback,
- IConnectionTransport,
-} from "./transport";
-
-// Per-`reconnect()` retry budget. After exhaustion, partysocket stops silently;
-// the wrapper rewrites the close-event reason to surface the give-up.
-export const MAX_RETRIES = 10;
-
-export const TRANSPORT_EXHAUSTED_REASON = "MARIMO_TRANSPORT_EXHAUSTED";
-
-export class WsTransport implements IConnectionTransport {
- private inner: ReconnectingWebSocket;
- private closeWrappers = new WeakMap<
- ConnectionTransportCallback<"close">,
- ConnectionTransportCallback<"close">
- >();
-
- public constructor(urlProvider: () => string) {
- this.inner = new ReconnectingWebSocket(urlProvider, undefined, {
- maxRetries: MAX_RETRIES,
- debug: false,
- startClosed: true,
- // long timeout — the server can become slow when many notebooks are open.
- connectionTimeout: 10_000,
- });
- }
-
- public get readyState(): WebSocket["readyState"] {
- return this.inner.readyState as WebSocket["readyState"];
- }
-
- public reconnect(code?: number, reason?: string): void {
- this.inner.reconnect(code, reason);
- }
-
- public close(): void {
- this.inner.close();
- }
-
- public send(
- data: string | ArrayBuffer | Blob | ArrayBufferView<ArrayBuffer>,
- ): void {
- this.inner.send(data);
- }
-
- public addEventListener<T extends ConnectionEvent>(
- event: T,
- callback: ConnectionTransportCallback<T>,
- ): void {
- if (event === "close") {
- const userCb = callback as ConnectionTransportCallback<"close">;
- // Match native EventTarget dedupe: a second addEventListener with the
- // same listener is a no-op. Without this, repeated adds leak wrappers
- // on the inner socket and double-fire on close.
- if (this.closeWrappers.has(userCb)) {
- return;
- }
- const wrapper: ConnectionTransportCallback<"close"> = (e) => {
- if (this.inner.retryCount >= MAX_RETRIES) {
- userCb(
- new CloseEvent("close", {
- code: e.code,
- reason: TRANSPORT_EXHAUSTED_REASON,
- wasClean: e.wasClean,
- }),
- );
- } else {
- userCb(e);
- }
- };
- this.closeWrappers.set(userCb, wrapper);
- this.inner.addEventListener("close", wrapper);
- return;
- }
- this.inner.addEventListener(event, callback as never);
- }
-
- public removeEventListener<T extends ConnectionEvent>(
- event: T,
- callback: ConnectionTransportCallback<T>,
- ): void {
- if (event === "close") {
- const userCb = callback as ConnectionTransportCallback<"close">;
- const wrapper = this.closeWrappers.get(userCb);
- if (wrapper) {
- this.closeWrappers.delete(userCb);
- this.inner.removeEventListener("close", wrapper);
- }
- return;
- }
- this.inner.removeEventListener(event, callback as never);
- }
-}