@marimo-team/islands 0.25.3-dev10 → 0.25.3-dev12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/{ErrorBoundary-BsqSMK9Y.js → ErrorBoundary-CUd8VnYI.js} +1 -1
  2. package/dist/{chat-ui-0lKdOoQ3.js → chat-ui-DaHynk8g.js} +4 -4
  3. package/dist/{code-visibility-CXQvUXHT.js → code-visibility-P0Ornave.js} +3 -3
  4. package/dist/{common-CuD-CAC-.js → common-BtO98PuE.js} +5 -5
  5. package/dist/{data-grid-overlay-editor-DgeyYmC1.js → data-grid-overlay-editor-B801aMeG.js} +1 -1
  6. package/dist/{error-entries-DSvFWT_M.js → error-entries-Bv6bZPF3.js} +1 -1
  7. package/dist/{feedback-button-DZMj9PF3.js → feedback-button-Bpu-arCP.js} +3 -3
  8. package/dist/{formats-CeOmU1MU.js → formats-27CW_UP4.js} +1 -1
  9. package/dist/{glide-data-editor-g_L8FLAC.js → glide-data-editor-XZB3u4tH.js} +3 -3
  10. package/dist/{globals-CYGlmBXb.js → globals-BIQc0DK0.js} +1 -1
  11. package/dist/{html-to-image-B8s5SgGm.js → html-to-image-Bf8QMGi4.js} +2 -2
  12. package/dist/main.js +13 -13
  13. package/dist/{number-overlay-editor-9VRv-pdj.js → number-overlay-editor-CEO_7tD7.js} +1 -1
  14. package/dist/{process-output-CKRXyszb.js → process-output-BZg56CCb.js} +2 -2
  15. package/dist/{reveal-component-C87mv9Mn.js → reveal-component-LPCUNcgp.js} +4 -4
  16. package/dist/{toDate-vIXljnsr.js → toDate-UtiwmnH2.js} +17 -16
  17. package/dist/{vega-component-DTG6zxaY.js → vega-component-BeF9dfyO.js} +2 -2
  18. package/package.json +1 -1
  19. package/src/__tests__/mount.test.ts +20 -0
  20. package/src/core/edit-app.tsx +2 -2
  21. package/src/core/host/__tests__/events.test.ts +46 -0
  22. package/src/core/host/__tests__/notebook-client.test.ts +191 -0
  23. package/src/core/host/connection.ts +81 -0
  24. package/src/core/host/events.ts +60 -0
  25. package/src/core/host/notebook-client.ts +226 -0
  26. package/src/core/run-app.tsx +2 -2
  27. package/src/core/runtime/__tests__/runtime.test.ts +55 -11
  28. package/src/core/runtime/runtime.ts +14 -1
  29. package/src/core/runtime/types.ts +2 -0
  30. package/src/core/websocket/__tests__/{useMarimoKernelConnection.test.ts → connection-state.test.ts} +15 -17
  31. package/src/core/websocket/__tests__/{useWebSocket.test.ts → createConnectionTransport.test.ts} +1 -1
  32. package/src/core/websocket/__tests__/useNotebookClient.hook.test.tsx +140 -0
  33. package/src/core/websocket/__tests__/{useMarimoKernelConnection.hook.test.tsx → useNotebookSession.hook.test.tsx} +227 -133
  34. package/src/core/websocket/connection-state.ts +70 -0
  35. package/src/core/websocket/transports/__tests__/sse.test.ts +1 -4
  36. package/src/core/websocket/transports/create.ts +31 -0
  37. package/src/core/websocket/transports/transport.ts +12 -23
  38. package/src/core/websocket/types.ts +9 -39
  39. package/src/core/websocket/useNotebookClient.ts +80 -0
  40. package/src/core/websocket/{useMarimoKernelConnection.tsx → useNotebookSession.tsx} +64 -231
  41. package/src/mount.tsx +4 -0
  42. package/src/core/websocket/useWebSocket.tsx +0 -88
@@ -0,0 +1,191 @@
1
+ /* Copyright 2026 Marimo. All rights reserved. */
2
+ // @vitest-environment jsdom
3
+
4
+ import { describe, expect, it, vi } from "vitest";
5
+ import { createStore } from "jotai";
6
+ import { ConnectionState } from "../../websocket/types";
7
+ import { Deferred } from "@/utils/Deferred";
8
+ import { jsonParseWithSpecialChar } from "@/utils/json/json-parser";
9
+ import { classifyCloseEvent } from "../../websocket/connection-state";
10
+ import { createNotebookClient } from "../notebook-client";
11
+
12
+ function setup() {
13
+ const events = new EventTarget();
14
+ const healthy = new Deferred<void>();
15
+ const transport = {
16
+ readyState: WebSocket.CLOSED,
17
+ reconnect: vi.fn(),
18
+ close: vi.fn(() => events.dispatchEvent(new CloseEvent("close"))),
19
+ send: vi.fn(),
20
+ addEventListener: events.addEventListener.bind(events),
21
+ removeEventListener: events.removeEventListener.bind(events),
22
+ };
23
+ const onNotification = vi.fn();
24
+ const checkHealth = vi.fn(async () => true);
25
+ const store = createStore();
26
+ const controller = createNotebookClient(store);
27
+ const client = controller.client;
28
+ const connect = (signal: AbortSignal) =>
29
+ controller.connect({
30
+ createTransport: () => transport,
31
+ url: () => "ws://localhost/ws",
32
+ messageFormat: "host",
33
+ signal,
34
+ waitUntilReady: () => healthy.promise,
35
+ checkHealth,
36
+ onNotification: (notification) => onNotification({ data: notification }),
37
+ onMessageError: vi.fn(),
38
+ decodeJson: jsonParseWithSpecialChar,
39
+ classifyClose: classifyCloseEvent,
40
+ });
41
+ return {
42
+ events,
43
+ healthy,
44
+ transport,
45
+ client,
46
+ connect,
47
+ onNotification,
48
+ store,
49
+ checkHealth,
50
+ };
51
+ }
52
+
53
+ describe("NotebookClient lifetime", () => {
54
+ it.each(["{broken", JSON.stringify({ event: "ready", data: {} })])(
55
+ "stops consuming a malformed host stream: %s",
56
+ (data) => {
57
+ const { connect, events, client, store, transport, onNotification } =
58
+ setup();
59
+ const lifetime = new AbortController();
60
+ connect(lifetime.signal);
61
+ events.dispatchEvent(new Event("open"));
62
+ events.dispatchEvent(new MessageEvent("message", { data }));
63
+ events.dispatchEvent(
64
+ new MessageEvent("message", {
65
+ data: JSON.stringify({
66
+ event: "marimo",
67
+ data: { marimo: { op: "reconnected" } },
68
+ }),
69
+ }),
70
+ );
71
+ expect(store.get(client.connectionAtom)).toEqual({
72
+ state: ConnectionState.CLOSED,
73
+ code: "KERNEL_DISCONNECTED",
74
+ reason: "Failed to decode notebook message",
75
+ });
76
+ expect(transport.close).toHaveBeenCalledOnce();
77
+ expect(onNotification).not.toHaveBeenCalled();
78
+ lifetime.abort();
79
+ },
80
+ );
81
+
82
+ it.each(["MARIMO_UNAUTHORIZED", "MARIMO_TRANSPORT_EXHAUSTED"])(
83
+ "stops automatic recovery after %s but permits an explicit reconnect",
84
+ async (reason) => {
85
+ const {
86
+ connect,
87
+ client,
88
+ store,
89
+ events,
90
+ transport,
91
+ healthy,
92
+ checkHealth,
93
+ } = setup();
94
+ const lifetime = new AbortController();
95
+ connect(lifetime.signal);
96
+ healthy.resolve();
97
+ await healthy.promise;
98
+ events.dispatchEvent(new CloseEvent("close", { reason }));
99
+ events.dispatchEvent(new Event("error"));
100
+ expect(store.get(client.connectionAtom).state).toBe(
101
+ ConnectionState.CLOSED,
102
+ );
103
+ expect(transport.reconnect).toHaveBeenCalledOnce();
104
+ await client.reconnect();
105
+ expect(checkHealth).toHaveBeenCalledOnce();
106
+ expect(transport.reconnect).toHaveBeenCalledTimes(2);
107
+ lifetime.abort();
108
+ },
109
+ );
110
+
111
+ it("only resets the automatic retry budget after an open event", () => {
112
+ const { connect, events, transport } = setup();
113
+ const lifetime = new AbortController();
114
+ connect(lifetime.signal);
115
+ events.dispatchEvent(new CloseEvent("close"));
116
+ events.dispatchEvent(new Event("error"));
117
+ events.dispatchEvent(new CloseEvent("close"));
118
+ expect(transport.reconnect).toHaveBeenCalledOnce();
119
+ events.dispatchEvent(new Event("open"));
120
+ events.dispatchEvent(new CloseEvent("close"));
121
+ expect(transport.reconnect).toHaveBeenCalledTimes(2);
122
+ lifetime.abort();
123
+ });
124
+
125
+ it("does not revive an aborted lifetime when a manual health check finishes", async () => {
126
+ const { connect, client, transport, checkHealth } = setup();
127
+ const health = new Deferred<boolean>();
128
+ checkHealth.mockReturnValue(health.promise);
129
+ const lifetime = new AbortController();
130
+ connect(lifetime.signal);
131
+ const attempt = client.reconnect();
132
+ lifetime.abort();
133
+ health.resolve(true);
134
+ await attempt;
135
+ expect(transport.reconnect).not.toHaveBeenCalled();
136
+ });
137
+
138
+ it("does not connect after abort, even when the health check finishes", async () => {
139
+ const { client, connect, healthy, transport } = setup();
140
+ const controller = new AbortController();
141
+ connect(controller.signal);
142
+ controller.abort();
143
+ healthy.resolve();
144
+ await healthy.promise;
145
+ client.reconnect();
146
+ expect(transport.reconnect).not.toHaveBeenCalled();
147
+ expect(transport.close).toHaveBeenCalledOnce();
148
+ });
149
+
150
+ it("detaches listeners before closing so cleanup cannot trigger a session retry", () => {
151
+ const { connect, client, store, events, transport, onNotification } =
152
+ setup();
153
+ const controller = new AbortController();
154
+ connect(controller.signal);
155
+ controller.abort();
156
+ events.dispatchEvent(
157
+ new MessageEvent("message", {
158
+ data: JSON.stringify({ data: { op: "reconnected" } }),
159
+ }),
160
+ );
161
+ expect(transport.reconnect).not.toHaveBeenCalled();
162
+ expect(store.get(client.connectionAtom)).toEqual({
163
+ state: ConnectionState.NOT_STARTED,
164
+ });
165
+ expect(onNotification).not.toHaveBeenCalled();
166
+ });
167
+
168
+ it("can reconnect after effect cleanup without reviving the earlier client attempt", async () => {
169
+ const { connect, healthy, transport, events, onNotification } = setup();
170
+ const first = new AbortController();
171
+ connect(first.signal);
172
+ first.abort();
173
+ const second = new AbortController();
174
+ connect(second.signal);
175
+ healthy.resolve();
176
+ await healthy.promise;
177
+ expect(transport.reconnect).toHaveBeenCalledOnce();
178
+ events.dispatchEvent(
179
+ new MessageEvent("message", {
180
+ data: JSON.stringify({
181
+ event: "marimo",
182
+ data: { marimo: { op: "reconnected" } },
183
+ }),
184
+ }),
185
+ );
186
+ expect(onNotification).toHaveBeenCalledExactlyOnceWith({
187
+ data: { op: "reconnected" },
188
+ });
189
+ second.abort();
190
+ });
191
+ });
@@ -0,0 +1,81 @@
1
+ /* Copyright 2026 Marimo. All rights reserved. */
2
+
3
+ export const ConnectionState = {
4
+ NOT_STARTED: "NOT_STARTED",
5
+ CONNECTING: "CONNECTING",
6
+ OPEN: "OPEN",
7
+ CLOSING: "CLOSING",
8
+ CLOSED: "CLOSED",
9
+ } as const;
10
+
11
+ export type ConnectionState =
12
+ (typeof ConnectionState)[keyof typeof ConnectionState];
13
+
14
+ export const ConnectionClosedReason = {
15
+ KERNEL_DISCONNECTED: "KERNEL_DISCONNECTED",
16
+ KERNEL_STARTUP_ERROR: "KERNEL_STARTUP_ERROR",
17
+ } as const;
18
+
19
+ export type ConnectionClosedReason =
20
+ (typeof ConnectionClosedReason)[keyof typeof ConnectionClosedReason];
21
+
22
+ export type ConnectionStatus =
23
+ | {
24
+ state: typeof ConnectionState.CLOSED;
25
+ code: ConnectionClosedReason;
26
+ reason: string;
27
+ }
28
+ | {
29
+ state: typeof ConnectionState.CONNECTING;
30
+ }
31
+ | {
32
+ state:
33
+ | typeof ConnectionState.OPEN
34
+ | typeof ConnectionState.CLOSING
35
+ | typeof ConnectionState.NOT_STARTED;
36
+ };
37
+
38
+ /** The recovery policy for a closed connection. */
39
+ export interface CloseDecision {
40
+ kind: "terminal" | "gave-up" | "retry";
41
+ status: ConnectionStatus;
42
+ }
43
+
44
+ export type ConnectionEvent = "open" | "close" | "message" | "error";
45
+
46
+ export interface IConnectionTransportMap {
47
+ open: WebSocketEventMap["open"];
48
+ message: WebSocketEventMap["message"];
49
+ close: WebSocketEventMap["close"];
50
+ error: WebSocketEventMap["error"];
51
+ }
52
+
53
+ export type ConnectionTransportCallback<T extends ConnectionEvent> = (
54
+ data: IConnectionTransportMap[T],
55
+ ) => void;
56
+
57
+ /** Transport readiness, using the WebSocket readyState values. */
58
+ export const TransportReadyState = {
59
+ CONNECTING: 0,
60
+ OPEN: 1,
61
+ CLOSING: 2,
62
+ CLOSED: 3,
63
+ } as const;
64
+
65
+ export type TransportReadyState =
66
+ (typeof TransportReadyState)[keyof typeof TransportReadyState];
67
+
68
+ /** A reconnectable source of notebook messages. */
69
+ export interface NotebookTransport {
70
+ reconnect(code?: number | undefined, reason?: string | undefined): void;
71
+ close(): void;
72
+ addEventListener<T extends ConnectionEvent>(
73
+ event: T,
74
+ callback: ConnectionTransportCallback<T>,
75
+ ): void;
76
+ removeEventListener<T extends ConnectionEvent>(
77
+ event: T,
78
+ callback: ConnectionTransportCallback<T>,
79
+ ): void;
80
+ readyState: TransportReadyState;
81
+ }
@@ -0,0 +1,60 @@
1
+ /* Copyright 2026 Marimo. All rights reserved. */
2
+
3
+ import { z } from "zod";
4
+ import * as Protocol from "./protocol";
5
+
6
+ /**
7
+ * Notebook stream events, including native marimo notifications.
8
+ *
9
+ * Known events follow the generated protocol. Unknown events retain their name
10
+ * and cursor so clients can skip them without losing their place in the stream.
11
+ */
12
+
13
+ /** Event kinds requested by the client; removals and controls are implicit. */
14
+ export const NOTEBOOK_EVENT_TYPES = [
15
+ "notebook",
16
+ "document",
17
+ "cell",
18
+ "marimo",
19
+ ] as const satisfies readonly (Protocol.ObjectType | "marimo")[];
20
+
21
+ const envelope = z.object({
22
+ event: z.string().min(1),
23
+ data: z.unknown(),
24
+ id: z.string().min(1).optional(),
25
+ });
26
+
27
+ const knownNames = new Set<string>(
28
+ Protocol.Event.options.flatMap((schema) => schema.shape.event.options),
29
+ );
30
+
31
+ /** A decoded event, or the name and cursor of an unrecognized event. */
32
+ export type NotebookEvent =
33
+ | Protocol.EventOutput
34
+ | {
35
+ readonly event: "unknown";
36
+ readonly name: string;
37
+ readonly id?: string;
38
+ };
39
+
40
+ const sessionEnvelope = z.object({ data: Protocol.MarimoNotification });
41
+
42
+ /**
43
+ * Decode a host event or a legacy `{ data: notification }` session message.
44
+ *
45
+ * Throws if the envelope or a known event is malformed. Native notification
46
+ * payloads are passed through for the session handler to interpret.
47
+ */
48
+ export function parseNotebookEvent(value: unknown): NotebookEvent {
49
+ if (typeof value === "object" && value !== null && !("event" in value)) {
50
+ return {
51
+ event: "marimo",
52
+ data: { marimo: sessionEnvelope.parse(value).data },
53
+ };
54
+ }
55
+ const parsed = envelope.parse(value);
56
+ if (knownNames.has(parsed.event)) {
57
+ return Protocol.Event.parse(parsed);
58
+ }
59
+ return { event: "unknown", name: parsed.event, id: parsed.id };
60
+ }
@@ -0,0 +1,226 @@
1
+ /* Copyright 2026 Marimo. All rights reserved. */
2
+
3
+ import { Logger } from "@/utils/Logger";
4
+ import { type Atom, atom, type createStore } from "jotai/vanilla";
5
+ import {
6
+ type ConnectionStatus,
7
+ ConnectionState,
8
+ ConnectionClosedReason,
9
+ type CloseDecision,
10
+ type NotebookTransport,
11
+ TransportReadyState,
12
+ } from "./connection";
13
+ import { parseNotebookEvent } from "./events";
14
+
15
+ /** A connection to a notebook on a marimo host. */
16
+ export interface NotebookClient {
17
+ /** Transport state, independent of kernel readiness. */
18
+ readonly connectionAtom: Atom<ConnectionStatus>;
19
+ /** Attempt to restore a closed connection after checking host health. */
20
+ reconnect(): Promise<void>;
21
+ }
22
+
23
+ /** The transport and application callbacks needed to connect a notebook. */
24
+ export interface NotebookConnection {
25
+ /** Create a transport that reads the URL again on each connection attempt. */
26
+ createTransport: (url: () => string) => NotebookTransport;
27
+ /** The current stream URL, including authentication and subscription options. */
28
+ url: () => string;
29
+ /** Host events require an intact stream; legacy notifications are independent. */
30
+ messageFormat: "host" | "session";
31
+ /** Abort to close the transport and clear the client's state. */
32
+ signal: AbortSignal;
33
+ /** Wait until the host can accept the initial connection. */
34
+ waitUntilReady: () => Promise<void>;
35
+ /** Check whether the host is reachable before an explicit reconnect. */
36
+ checkHealth: () => Promise<boolean>;
37
+ /** Decode wire text without interpreting its event type. */
38
+ decodeJson: (message: string) => unknown;
39
+ /** Handle a native marimo notification. Its payload has not been validated. */
40
+ onNotification: (notification: unknown) => void;
41
+ /** Report a malformed message without coupling the client to editor UI. */
42
+ onMessageError: (error: unknown) => void;
43
+ /** Choose the connection status and retry policy after the transport closes. */
44
+ classifyClose: (event: CloseEvent) => CloseDecision;
45
+ }
46
+
47
+ /** Create a client without opening a connection. */
48
+ export function createNotebookClient(store: ReturnType<typeof createStore>) {
49
+ const connectionAtom = atom<ConnectionStatus>({
50
+ state: ConnectionState.NOT_STARTED,
51
+ });
52
+ let reconnect: (() => Promise<void>) | undefined;
53
+ const client: NotebookClient = {
54
+ connectionAtom,
55
+ reconnect: async () => reconnect?.(),
56
+ };
57
+
58
+ function connect({
59
+ createTransport,
60
+ url,
61
+ messageFormat,
62
+ signal,
63
+ waitUntilReady,
64
+ checkHealth,
65
+ onNotification,
66
+ onMessageError,
67
+ decodeJson,
68
+ classifyClose,
69
+ }: NotebookConnection) {
70
+ if (signal.aborted) {
71
+ return;
72
+ }
73
+ let shouldRetry = true;
74
+ let terminal = false;
75
+ let checkingHealth = false;
76
+ const transport = createTransport(url);
77
+ const setStatus = (status: ConnectionStatus) =>
78
+ store.set(connectionAtom, status);
79
+ const disconnected = {
80
+ state: ConnectionState.CLOSED,
81
+ code: ConnectionClosedReason.KERNEL_DISCONNECTED,
82
+ reason: "kernel not found",
83
+ } satisfies ConnectionStatus;
84
+
85
+ function retry(code?: number, reason?: string) {
86
+ if (!signal.aborted && !terminal && shouldRetry) {
87
+ shouldRetry = false;
88
+ transport.reconnect(code, reason);
89
+ }
90
+ }
91
+
92
+ function onOpen() {
93
+ if (signal.aborted || terminal) {
94
+ return;
95
+ }
96
+ shouldRetry = true;
97
+ setStatus({ state: ConnectionState.OPEN });
98
+ }
99
+
100
+ function onClose(event: CloseEvent) {
101
+ if (signal.aborted || terminal) {
102
+ return;
103
+ }
104
+ Logger.warn("Notebook connection closed", event.code, event.reason);
105
+ const decision = classifyClose(event);
106
+ setStatus(decision.status);
107
+ if (decision.kind === "terminal") {
108
+ terminal = true;
109
+ transport.close();
110
+ } else if (decision.kind === "retry") {
111
+ retry(event.code, event.reason);
112
+ } else {
113
+ terminal = true;
114
+ }
115
+ }
116
+
117
+ function onError(event: Event) {
118
+ if (signal.aborted || terminal) {
119
+ return;
120
+ }
121
+ Logger.warn("Notebook connection error", event);
122
+ setStatus(disconnected);
123
+ retry();
124
+ }
125
+
126
+ function onMessage(message: MessageEvent<string>) {
127
+ if (signal.aborted || terminal) {
128
+ return;
129
+ }
130
+ let event;
131
+ try {
132
+ event = parseNotebookEvent(decodeJson(message.data));
133
+ } catch (error) {
134
+ Logger.error("Failed to decode notebook message", error);
135
+ if (messageFormat === "session") {
136
+ onMessageError(error);
137
+ return;
138
+ }
139
+ terminal = true;
140
+ setStatus({
141
+ ...disconnected,
142
+ reason: "Failed to decode notebook message",
143
+ });
144
+ transport.close();
145
+ return;
146
+ }
147
+ if (event.event === "marimo") {
148
+ onNotification(event.data.marimo);
149
+ }
150
+ }
151
+
152
+ reconnect = async () => {
153
+ if (
154
+ signal.aborted ||
155
+ checkingHealth ||
156
+ transport.readyState === TransportReadyState.OPEN ||
157
+ transport.readyState === TransportReadyState.CONNECTING
158
+ ) {
159
+ return;
160
+ }
161
+ checkingHealth = true;
162
+ setStatus({ state: ConnectionState.CONNECTING });
163
+ try {
164
+ const healthy = await checkHealth();
165
+ if (signal.aborted) {
166
+ return;
167
+ }
168
+ if (!healthy) {
169
+ shouldRetry = false;
170
+ setStatus(disconnected);
171
+ return;
172
+ }
173
+ terminal = false;
174
+ shouldRetry = true;
175
+ transport.reconnect();
176
+ } catch (error) {
177
+ if (!signal.aborted) {
178
+ Logger.error("Notebook health check failed", error);
179
+ shouldRetry = false;
180
+ setStatus(disconnected);
181
+ }
182
+ } finally {
183
+ checkingHealth = false;
184
+ }
185
+ };
186
+
187
+ signal.addEventListener(
188
+ "abort",
189
+ () => {
190
+ transport.removeEventListener("open", onOpen);
191
+ transport.removeEventListener("close", onClose);
192
+ transport.removeEventListener("error", onError);
193
+ transport.removeEventListener("message", onMessage);
194
+ transport.close();
195
+ reconnect = undefined;
196
+ setStatus({ state: ConnectionState.NOT_STARTED });
197
+ },
198
+ { once: true },
199
+ );
200
+
201
+ transport.addEventListener("open", onOpen);
202
+ transport.addEventListener("close", onClose);
203
+ transport.addEventListener("error", onError);
204
+ transport.addEventListener("message", onMessage);
205
+
206
+ if (transport.readyState === TransportReadyState.CLOSED) {
207
+ setStatus({ state: ConnectionState.CONNECTING });
208
+ void waitUntilReady()
209
+ .then(() => {
210
+ if (!signal.aborted) {
211
+ transport.reconnect();
212
+ }
213
+ })
214
+ .catch((error) => {
215
+ if (!signal.aborted) {
216
+ Logger.error("Healthy connection never made", error);
217
+ terminal = true;
218
+ setStatus(disconnected);
219
+ transport.close();
220
+ }
221
+ });
222
+ }
223
+ }
224
+
225
+ return { client, connect };
226
+ }
@@ -22,7 +22,7 @@ import { getSessionId } from "./kernel/session";
22
22
  import { connectionAtom } from "./network/connection";
23
23
  import { useRequestClient } from "./network/requests";
24
24
  import { isAppConnecting } from "./websocket/connection-utils";
25
- import { useMarimoKernelConnection } from "./websocket/useMarimoKernelConnection";
25
+ import { useNotebookSession } from "./websocket/useNotebookSession";
26
26
 
27
27
  interface AppProps {
28
28
  appConfig: AppConfig;
@@ -51,7 +51,7 @@ export const RunApp: React.FC<AppProps> = ({ appConfig, hideHeader }) => {
51
51
  };
52
52
  }, []);
53
53
 
54
- const { connection, reconnect } = useMarimoKernelConnection({
54
+ const { connection, reconnect } = useNotebookSession({
55
55
  autoInstantiate: true,
56
56
  setCells: setCells,
57
57
  sessionId: getSessionId(),
@@ -2,14 +2,19 @@
2
2
 
3
3
  import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4
4
  import { Mocks } from "@/__mocks__/common";
5
- import type { SessionId } from "@/core/kernel/session";
5
+ import {
6
+ generateSessionId,
7
+ isSessionId,
8
+ type SessionId,
9
+ } from "@/core/kernel/session";
6
10
  import { Logger } from "@/utils/Logger";
7
11
  import { RuntimeManager } from "../runtime";
8
12
  import type { RuntimeConfig } from "../types";
9
13
 
10
14
  // Mock the session module
11
- vi.mock("@/core/kernel/session", () => ({
12
- getSessionId: () => "test-session-id" as SessionId,
15
+ vi.mock("@/core/kernel/session", async (importOriginal) => ({
16
+ ...(await importOriginal<typeof import("@/core/kernel/session")>()),
17
+ getSessionId: () => "test-session-id",
13
18
  }));
14
19
 
15
20
  vi.mock("@/utils/Logger", () => ({ Logger: Mocks.quietLogger() }));
@@ -51,6 +56,38 @@ describe("RuntimeManager", () => {
51
56
  });
52
57
 
53
58
  describe("getWsURL", () => {
59
+ it("uses host notebook events with the existing session and auth parameters", () => {
60
+ const original = window.location.href;
61
+ window.history.replaceState({}, "", "/?types=run");
62
+ try {
63
+ const runtime = new RuntimeManager({
64
+ ...mockConfig,
65
+ url: "https://example.com/nested?file=notebook.py",
66
+ notebookId: "nb_123",
67
+ });
68
+ const sessionId = "s_123456";
69
+ if (!isSessionId(sessionId)) {
70
+ throw new Error("Invalid test session ID");
71
+ }
72
+ const url = runtime.getWsURL(sessionId);
73
+ expect({
74
+ endpoint: `${url.origin}${url.pathname}`,
75
+ params: Object.fromEntries(url.searchParams),
76
+ }).toEqual({
77
+ endpoint:
78
+ "wss://example.com/nested/api/marimo/v1/notebooks/nb_123/events/ws",
79
+ params: {
80
+ file: "notebook.py",
81
+ types: "marimo",
82
+ session_id: sessionId,
83
+ access_token: "test-token",
84
+ },
85
+ });
86
+ } finally {
87
+ window.history.replaceState({}, "", original);
88
+ }
89
+ });
90
+
54
91
  it("should return WebSocket URL with session ID for https", () => {
55
92
  const runtime = new RuntimeManager(mockConfig);
56
93
  const sessionId = "1234" as SessionId;
@@ -59,6 +96,7 @@ describe("RuntimeManager", () => {
59
96
  expect(url.protocol).toBe("wss:");
60
97
  expect(url.hostname).toBe("example.com");
61
98
  expect(url.pathname).toBe("/ws");
99
+ expect(url.searchParams.has("types")).toBe(false);
62
100
  expect(url.searchParams.get("session_id")).toBe(sessionId);
63
101
  });
64
102
 
@@ -219,14 +257,20 @@ describe("RuntimeManager", () => {
219
257
  });
220
258
 
221
259
  describe("getSseURL", () => {
222
- it("should return an http(s) URL with the session ID", () => {
223
- const runtime = new RuntimeManager(mockConfig);
224
- const url = runtime.getSseURL("1234" as SessionId);
225
-
226
- expect(url.protocol).toBe("https:");
227
- expect(url.pathname).toBe("/sse");
228
- expect(url.searchParams.get("session_id")).toBe("1234");
229
- });
260
+ it.each([undefined, "nb_123"])(
261
+ "uses the legacy session stream when notebookId is %s",
262
+ (notebookId) => {
263
+ const runtime = new RuntimeManager({
264
+ ...mockConfig,
265
+ url: "https://example.com/nested?file=notebook.py",
266
+ notebookId,
267
+ });
268
+ const sessionId = generateSessionId();
269
+ expect(runtime.getSseURL(sessionId).toString()).toBe(
270
+ `https://example.com/nested/sse?file=notebook.py&session_id=${sessionId}`,
271
+ );
272
+ },
273
+ );
230
274
 
231
275
  it("should never put the auth token in the URL, even cross-origin", () => {
232
276
  // SSE requests can send headers, so auth travels in the