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
Export `sse` and simplify client options in `@marimo-team/client` (#11411)
Trevor Manzb5e7e073c068
diff --git a/packages/client/README.md b/packages/client/README.mdindex 17ed6557ef..b0eebfdbfb 100644--- a/packages/client/README.md+++ b/packages/client/README.md@@ -19,8 +19,8 @@ const client = new Client("http://127.0.0.1:2718/api/marimo/v1", {});```-Requests use HTTP and event streams use server-sent events. Pass `fetch` or-`headers` alongside `token` to customize requests.+Requests use HTTP and event streams use server-sent events. Pass `fetch`+alongside `token` to customize requests.## Find notebooksdiff --git a/packages/client/TRANSPORTS.md b/packages/client/TRANSPORTS.mdindex a6931909c3..3d1ad49e78 100644--- a/packages/client/TRANSPORTS.md+++ b/packages/client/TRANSPORTS.md@@ -26,5 +26,28 @@ The transport sends any filters the host needs. The stream's `types` optionfilters delivered events locally. A notebook transport must apply `runId`itself. Each reconnect must use the same filters.+## Build on server-sent events++`sse` is the transport a stream uses for a URL. Use it directly when a host+serves the protocol's events with a URL that changes between connections or+with frames of its own that end the stream.++```ts+import { NotebookEvents, StreamStopped, sse } from "@marimo-team/client";++const events = new NotebookEvents(+ sse(() => `${base}/events?session_id=${session()}`, {+ token,+ stop: (frame) =>+ frame.event === "close"+ ? new StreamStopped("The session closed")+ : undefined,+ }),+);+```++The URL function runs before each connection. A `StreamStopped` it throws+stops the stream.+See the [transport contract](src/transport/frame.ts) for the function andevent types.diff --git a/packages/client/src/__tests__/catalog-events.test.ts b/packages/client/src/__tests__/catalog-events.test.tsindex d799c96407..5a43654b13 100644--- a/packages/client/src/__tests__/catalog-events.test.ts+++ b/packages/client/src/__tests__/catalog-events.test.ts@@ -6,7 +6,7 @@ import { notebooks, projects } from "./catalog-resources.ts";import {CatalogEvents,type CatalogEvent,- type CatalogEventsInit,+ type CatalogEventsOptions,type Transport,} from "../index.ts";import { fixtureEvents } from "./fixtures.ts";@@ -153,8 +153,8 @@ describe("CatalogEvents", () => {expectTypeOf<CatalogEvent<"notebook">["event"]>().toEqualTypeOf<"notebook" | "notebook.removed" | "ready" | "reset">();- expectTypeOf<CatalogEventsInit>().not.toHaveProperty("runId");- expectTypeOf<CatalogEventsInit["types"]>().toEqualTypeOf<+ expectTypeOf<CatalogEventsOptions>().not.toHaveProperty("runId");+ expectTypeOf<CatalogEventsOptions["types"]>().toEqualTypeOf<| readonly ("host" | "project" | "notebook" | "runtime" | "attachment")[]| undefined>();diff --git a/packages/client/src/__tests__/client.test.ts b/packages/client/src/__tests__/client.test.tsindex cd913026c1..35204ed684 100644--- a/packages/client/src/__tests__/client.test.ts+++ b/packages/client/src/__tests__/client.test.ts@@ -18,7 +18,6 @@ function connect(response: () => Response) {"http://localhost/prefix/api/marimo/v1/?session_id=s1",{token: "secret",- headers: { "X-Example": "1" },fetch,},);@@ -54,7 +53,6 @@ describe("Client", () => {);expect(request.method).toBe("POST");expect(request.headers.get("Authorization")).toBe("Bearer secret");- expect(request.headers.get("X-Example")).toBe("1");expect(request.headers.get("Idempotency-Key")).toBe("create-1");expect(await request.json()).toEqual(input);});@@ -74,7 +72,6 @@ describe("Client", () => {"http://localhost/prefix/api/marimo/v1/notebooks/n%2F1%3F%23%25?session_id=s1",);expect(sent().headers.get("Authorization")).toBe("Bearer secret");- expect(sent().headers.get("X-Example")).toBe("1");expect(client.notebook("n1").url.href).toBe(client.notebook(record).url.href,);@@ -126,7 +123,6 @@ describe("Client", () => {"http://localhost/prefix/api/marimo/v1/events?session_id=s1&types=notebook",);expect(sent().headers.get("Authorization")).toBe("Bearer secret");- expect(sent().headers.get("X-Example")).toBe("1");expect(sent().headers.get("Last-Event-ID")).toBe("40");expect(sent(1).headers.get("Last-Event-ID")).toBeNull();first.close();diff --git a/packages/client/src/__tests__/notebook-client.test.ts b/packages/client/src/__tests__/notebook-client.test.tsindex 8768d816de..660fe124d9 100644--- a/packages/client/src/__tests__/notebook-client.test.ts+++ b/packages/client/src/__tests__/notebook-client.test.ts@@ -36,7 +36,6 @@ function connect();const notebook = new NotebookClient(url, {token: "secret",- headers: { "X-Example": "1" },fetch,});const sent = () => new Request(...fetch.mock.calls[0]);@@ -64,7 +63,6 @@ describe("NotebookClient", () => {"http://127.0.0.1:2718/api/marimo/v1/notebooks/n1/edits",);expect(request.headers.get("Authorization")).toBe("Bearer secret");- expect(request.headers.get("X-Example")).toBe("1");expect(request.headers.get("Idempotency-Key")).toMatch(/^[\da-f-]{36}$/);expect(await request.json()).toEqual({ changes });});diff --git a/packages/client/src/__tests__/notebook-events.test.ts b/packages/client/src/__tests__/notebook-events.test.tsindex 573ce10166..0bfba9ce21 100644--- a/packages/client/src/__tests__/notebook-events.test.ts+++ b/packages/client/src/__tests__/notebook-events.test.ts@@ -3,11 +3,12 @@import NodeFs from "node:fs";import NodeUrl from "node:url";import { afterEach, describe, expect, expectTypeOf, it, vi } from "vitest";+import { z } from "zod";import { NotebookClient } from "../notebook/client.ts";import { NotebookEvents } from "../notebook/events.ts";import type { NotebookEvent } from "../notebook/events.ts";import { type NotebookTransport, StreamStopped } from "../transport/frame.ts";-import { ServerSentEventStream } from "../transport/sse.ts";+import { ServerSentEventStream, sse } from "../transport/sse.ts";const fixtures = new NodeUrl.URL("../../../../protocols/host/fixtures/",@@ -479,11 +480,57 @@ describe("NotebookEvents", () => {queueMicrotask(() => handlers.message(null));});const events = new NotebookEvents(transport);- await expect(events.closed).rejects.toThrow("not an event");+ const error = await events.closed.catch((error: unknown) => error);+ expect((error as StreamStopped).message).toContain("not an event");+ expect((error as StreamStopped).cause).toBeInstanceOf(z.ZodError);expect(signal?.aborted).toBe(true);});});+describe("sse", () => {+ it("reads a URL given as a function before each connection", async () => {+ vi.useFakeTimers();+ const first = body();+ const { fetch, sent } = answering(first.response);+ let session = 1;+ const events = new NotebookEvents(+ sse(async () => `${url}?session_id=${session}`, { fetch }),+ );+ first.push(throughReady);+ await vi.waitFor(() => expect(events.cursor).toBe("95"));+ session = 2;+ first.end();+ await vi.advanceTimersByTimeAsync(2000);+ expect([sent(0).url, sent(1).url]).toMatchInlineSnapshot(`+ [+ "http://127.0.0.1:2718/api/marimo/v1/notebooks/n1/events?session_id=1",+ "http://127.0.0.1:2718/api/marimo/v1/notebooks/n1/events?session_id=2",+ ]+ `);+ expect(sent(1).headers.get("Last-Event-ID")).toBe("95");+ events.close();+ });++ it("stops on a frame outside the protocol when asked to", async () => {+ const stream = body();+ const shutdown = new Error("MARIMO_SHUTDOWN");+ const events = new NotebookEvents(+ sse(url, {+ fetch: answering(stream.response).fetch,+ stop: (frame) => (frame.event === "close" ? shutdown : undefined),+ }),+ { types: ["marimo"] },+ );+ const received = collect(events);+ stream.push('id: 1\nevent: marimo\ndata: {"marimo":{}}\n\n');+ stream.push(+ 'event: close\ndata: {"code":1000,"reason":"MARIMO_SHUTDOWN"}\n\n',+ );+ await expect(events.closed).rejects.toBe(shutdown);+ expect(received.map((event) => event.event)).toEqual(["marimo"]);+ });+});+describe("NotebookClient.events", () => {it("follows the stream below the notebook's URL with the client's connection", async () => {const { fetch, sent } = answering();diff --git a/packages/client/src/catalog/events.ts b/packages/client/src/catalog/events.tsindex c733faacf2..c97f3cc038 100644--- a/packages/client/src/catalog/events.ts+++ b/packages/client/src/catalog/events.ts@@ -1,7 +1,7 @@/* Copyright 2026 Marimo. All rights reserved. */import { type CatalogKind, catalogKinds } from "../kinds.ts";-import { Events, type EventsInit } from "../transport/events.ts";+import { Events, type EventsOptions } from "../transport/events.ts";import type { Transport } from "../transport/frame.ts";import type { StreamEvent } from "../transport/stream.ts";@@ -9,9 +9,9 @@ import type { StreamEvent } from "../transport/stream.ts";export type CatalogEvent<K extends CatalogKind = CatalogKind> = StreamEvent<K>;/** How a catalog stream reaches its host and what it follows. */-export interface CatalogEventsInit<+export interface CatalogEventsOptions<K extends CatalogKind = CatalogKind,-> extends EventsInit<K> {}+> extends EventsOptions<K> {}/*** The host's catalog, followed across reconnects without retaining its objects.@@ -25,7 +25,7 @@ export class CatalogEvents<> extends Events<K> {public constructor(source: string | URL | Transport,- init: CatalogEventsInit<K> = {},+ init: CatalogEventsOptions<K> = {},) {super(source, init, catalogKinds);}diff --git a/packages/client/src/client.ts b/packages/client/src/client.tsindex 3f384eb5d3..92c69f3ec9 100644--- a/packages/client/src/client.ts+++ b/packages/client/src/client.ts@@ -1,12 +1,12 @@/* Copyright 2026 Marimo. All rights reserved. */-import { CatalogEvents, type CatalogEventsInit } from "./catalog/events.ts";+import { CatalogEvents, type CatalogEventsOptions } from "./catalog/events.ts";import type { CatalogKind } from "./kinds.ts";import { NotebookClient } from "./notebook/client.ts";import type * as Protocol from "./protocol.ts";import {below,- type Connection,+ type ClientOptions,type MutationOptions,request,resolve,@@ -14,15 +14,12 @@ import {type Target,} from "./request.ts";-/** How a `Client` reaches and authenticates with its host. */-export type ClientInit = Connection;-/** A client for a host's API, without a retained catalog. */export class Client {readonly #target: Target<"">;- public constructor(url: string | URL, init: ClientInit = {}) {- this.#target = { url: new URL(url), prefix: "", connection: init };+ public constructor(url: string | URL, init: ClientOptions = {}) {+ this.#target = { url: new URL(url), prefix: "", client: init };}/** The host API's base URL. Each read returns a copy. */@@ -30,18 +27,18 @@ export class Client {return new URL(this.#target.url);}- /** Follow the catalog with this client's connection and an independent cursor. */+ /** Follow the catalog with this client's options and an independent cursor. */public events<const K extends CatalogKind = CatalogKind>(- options: Omit<CatalogEventsInit<K>, keyof Connection> = {},+ options: Omit<CatalogEventsOptions<K>, keyof ClientOptions> = {},): CatalogEvents<K> {return new CatalogEvents<K>(below(this.#target.url, "/events"), {- ...this.#target.connection,+ ...this.#target.client,...options,});}/**- * Address a notebook by id or catalog record, sharing this connection.+ * Address a notebook by id or catalog record, sharing this client's options.** Makes no request and retains no metadata. The id belongs to this host.*/@@ -51,7 +48,7 @@ export class Client {const id = typeof notebook === "string" ? notebook : notebook.id;return new NotebookClient(resolve(this.#target, "/notebooks/{notebook_id}", { notebook_id: id }),- this.#target.connection,+ this.#target.client,);}diff --git a/packages/client/src/index.ts b/packages/client/src/index.tsindex 3628f5b56e..2d72f0b0e1 100644--- a/packages/client/src/index.ts+++ b/packages/client/src/index.ts@@ -1,24 +1,30 @@/* Copyright 2026 Marimo. All rights reserved. */-export { Client, type ClientInit } from "./client.ts";+export { Client } from "./client.ts";+export type { ClientOptions } from "./request.ts";export {CatalogEvents,- type CatalogEventsInit,+ type CatalogEventsOptions,type CatalogEvent,} from "./catalog/events.ts";export type { CatalogKind, NotebookKind } from "./kinds.ts";-export { NotebookClient, type NotebookClientInit } from "./notebook/client.ts";+export {+ NotebookClient,+ type NotebookClientOptions,+} from "./notebook/client.ts";export {NotebookEvents,- type NotebookEventsInit,+ type NotebookEventsOptions,type NotebookEvent,} from "./notebook/events.ts";export type { Result } from "./request.ts";export {+ type Frame,type Transport,type NotebookTransport,StreamStopped,} from "./transport/frame.ts";+export { sse, type SseOptions, type StreamUrl } from "./transport/sse.ts";export {createCatalogReducer,diff --git a/packages/client/src/notebook/client.ts b/packages/client/src/notebook/client.tsindex a17afd050f..effd80f4f1 100644--- a/packages/client/src/notebook/client.ts+++ b/packages/client/src/notebook/client.ts@@ -4,17 +4,17 @@ import type * as Protocol from "../protocol.ts";import type { NotebookKind } from "../kinds.ts";import {below,- type Connection,+ type ClientOptions,type MutationOptions,type OperationsBelow,request,type Result,type Target,} from "../request.ts";-import { NotebookEvents, type NotebookEventsInit } from "./events.ts";+import { NotebookEvents, type NotebookEventsOptions } from "./events.ts";/** How a `NotebookClient` reaches and authenticates with its host. */-export type NotebookClientInit = Connection;+export type NotebookClientOptions = ClientOptions;/** Options for a request the host may need decisions for. */interface DecisionOptions extends MutationOptions {@@ -39,12 +39,12 @@ export class NotebookClient {readonly #url: URL;readonly #target: Target<Scope>;- public constructor(url: string | URL, init: NotebookClientInit = {}) {+ public constructor(url: string | URL, init: NotebookClientOptions = {}) {this.#url = new URL(url);this.#target = {url: this.#url,prefix: "/notebooks/{notebook_id}",- connection: init,+ client: init,};}@@ -61,13 +61,13 @@ export class NotebookClient {* Follow the notebook's stream.** The stream is served below the notebook's URL over server-sent events,- * and shares this client's connection.+ * and shares this client's options.*/public events<const K extends string = NotebookKind>(- options: Omit<NotebookEventsInit<K>, keyof Connection> = {},+ options: Omit<NotebookEventsOptions<K>, keyof ClientOptions> = {},): NotebookEvents<K> {return new NotebookEvents<K>(below(this.#url, "/events"), {- ...this.#target.connection,+ ...this.#target.client,...options,});}diff --git a/packages/client/src/notebook/events.ts b/packages/client/src/notebook/events.tsindex 8965f436c9..87cabeca50 100644--- a/packages/client/src/notebook/events.ts+++ b/packages/client/src/notebook/events.ts@@ -2,7 +2,7 @@import { type NotebookKind, notebookKinds } from "../kinds.ts";import type * as Protocol from "../protocol.ts";-import { Events, type EventsInit } from "../transport/events.ts";+import { Events, type EventsOptions } from "../transport/events.ts";import type { NotebookTransport } from "../transport/frame.ts";import type { StreamEvent } from "../transport/stream.ts";@@ -10,9 +10,9 @@ import type { StreamEvent } from "../transport/stream.ts";export type NotebookEvent<K extends string = NotebookKind> = StreamEvent<K>;/** How a notebook stream reaches its host and what it follows. */-export interface NotebookEventsInit<+export interface NotebookEventsOptions<K extends string = NotebookKind,-> extends EventsInit<K> {+> extends EventsOptions<K> {/** Follow one run. A custom transport filters its own requests. */readonly runId?: Protocol.RunId;}@@ -29,7 +29,7 @@ export class NotebookEvents<> extends Events<K> {public constructor(source: string | URL | NotebookTransport,- init: NotebookEventsInit<K> = {},+ init: NotebookEventsOptions<K> = {},) {if (typeof source !== "function" && init.runId !== undefined) {source = new URL(source);diff --git a/packages/client/src/request.ts b/packages/client/src/request.tsindex 144b0aa364..a9ab818049 100644--- a/packages/client/src/request.ts+++ b/packages/client/src/request.ts@@ -4,13 +4,16 @@ import type * as z from "zod";import { type OperationId, operations } from "./operations.ts";import * as Protocol from "./protocol.ts";-/** How requests reach and authenticate with a host. */-export interface Connection {+/** How a client reaches and authenticates with a host. */+export interface ClientOptions {/** Sent as `Authorization: Bearer <token>`. */readonly token?: string;- /** Added to every request. */- readonly headers?: HeadersInit;- /** Defaults to `globalThis.fetch`. */+ /**+ * Sends each request. Defaults to `globalThis.fetch`.+ *+ * Wrap it to add headers or change requests. It receives each request with+ * the client's own headers already set.+ */readonly fetch?: typeof globalThis.fetch;}@@ -66,7 +69,7 @@ export type OperationsBelow<Prefix extends string> = {export interface Target<Prefix extends string> {readonly url: URL;readonly prefix: Prefix;- readonly connection: Connection;+ readonly client: ClientOptions;}/** What a request reads from each entry of the operations table. */@@ -186,11 +189,11 @@ export async function request<{ params = {}, body, headers = {}, options = {} }: Call<Id>,): Promise<Result<Data<Id>>> {const operation = table[id];- const { connection } = target;- const sent = new Headers(connection.headers);+ const { client } = target;+ const sent = new Headers();sent.set("Accept", "application/json, application/problem+json");- if (connection.token !== undefined) {- sent.set("Authorization", `Bearer ${connection.token}`);+ if (client.token !== undefined) {+ sent.set("Authorization", `Bearer ${client.token}`);}if ("Idempotency-Key" in operation.headers) {sent.set("Idempotency-Key", options.idempotencyKey ?? idempotencyKey());@@ -205,7 +208,7 @@ export async function request<sent.set("Content-Type", "application/json");payload = JSON.stringify(operation.body.parse(body));}- const fetch = connection.fetch ?? globalThis.fetch;+ const fetch = client.fetch ?? globalThis.fetch;const response = await fetch(resolve(target, operation.path, params), {method: operation.method,headers: sent,diff --git a/packages/client/src/transport/events.ts b/packages/client/src/transport/events.tsindex f3873886ac..a960572328 100644--- a/packages/client/src/transport/events.ts+++ b/packages/client/src/transport/events.ts@@ -1,13 +1,13 @@/* Copyright 2026 Marimo. All rights reserved. */import type * as Protocol from "../protocol.ts";-import type { Connection } from "../request.ts";+import type { ClientOptions } from "../request.ts";import { type Transport, StreamStopped } from "./frame.ts";import { sse } from "./sse.ts";import {type StreamEvent,EventStream,- type EventStreamInit,+ type EventStreamOptions,report,} from "./stream.ts";@@ -23,8 +23,8 @@ function delay(attempt: number): number {type Status = "connecting" | "connected" | "closed";/** How an event stream reaches its host and what it follows. */-export interface EventsInit<K extends string = Protocol.ObjectTypeOutput>- extends Connection, EventStreamInit<K> {+export interface EventsOptions<K extends string = Protocol.ObjectTypeOutput>+ extends ClientOptions, EventStreamOptions<K> {/** Aborting closes the stream. */readonly signal?: AbortSignal;/**@@ -50,8 +50,9 @@ function sleep(ms: number, signal: AbortSignal): Promise<void> {/*** A host stream, followed across reconnects.*- * Given a URL, it follows the stream there over server-sent events. Given a- * `Transport`, it follows whatever connection the transport opens.+ * Given a URL, it follows the stream there with `sse` and sends `types` as a+ * query parameter. Given a `Transport`, it follows whatever connection the+ * transport opens.** - It starts with a snapshot that ends in `ready`, then delivers changes.* - After a dropped connection it resumes from its cursor, backing off between@@ -78,7 +79,7 @@ export class Events<public constructor(source: string | URL | Transport,- init: EventsInit<K>,+ init: EventsOptions<K>,kinds: readonly string[],) {let transport: Transport;diff --git a/packages/client/src/transport/frame.ts b/packages/client/src/transport/frame.tsindex 0144db5d4b..e0a376b37c 100644--- a/packages/client/src/transport/frame.ts+++ b/packages/client/src/transport/frame.ts@@ -7,26 +7,14 @@ export interface Frame {readonly id?: string;}-/** Whether a decoded message has the shape of a stream event. */-export function isFrame(value: unknown): value is Frame {- if (typeof value !== "object" || value === null) {- return false;- }- const { event, id } = value as Record<string, unknown>;- return (- typeof event === "string" &&- event !== "" &&- (id === undefined || typeof id === "string")- );-}-/*** A stream stopped and will not reconnect.** `cause` says why when there is more to say.** - The host refused the stream. `cause` is the `Problem` it answered with.- * - The host sent an invalid event. `cause` is the validation error.+ * - The host sent a message that is not an event, or an invalid event.+ * `cause` is the validation error.* - The host could not be reached after repeated attempts. `cause` is* undefined.* - A custom transport decided to stop. `cause` is whatever it passed.diff --git a/packages/client/src/transport/sse.ts b/packages/client/src/transport/sse.tsindex 92be9b1c9c..e8be036df8 100644--- a/packages/client/src/transport/sse.ts+++ b/packages/client/src/transport/sse.ts@@ -1,7 +1,7 @@/* Copyright 2026 Marimo. All rights reserved. */import * as Protocol from "../protocol.ts";-import { type Connection, isType } from "../request.ts";+import { type ClientOptions, isType } from "../request.ts";import { type Frame, type Transport, StreamStopped } from "./frame.ts";/** Hosts send a comment every fifteen seconds while nothing else happens. */@@ -74,19 +74,36 @@ export class ServerSentEventStream extends TransformStream<string, Frame> {/** Statuses a host answers when it may accept the stream later. */const RETRY_STATUSES = new Set([408, 429]);+/** Where a stream is, read again before each connection. */+export type StreamUrl =+ | string+ | URL+ | (() => string | URL | Promise<string | URL>);++/** How `sse` reaches its host and which frames end the stream. */+export interface SseOptions extends ClientOptions {+ /**+ * Decide whether a frame outside the protocol ends the stream.+ *+ * Return an error to stop with it. Return nothing to deliver the frame.+ */+ readonly stop?: (frame: Frame) => Error | undefined;+}+/*** Follow a stream over server-sent events, as the protocol defines.** The cursor travels in `Last-Event-ID`. A refusal stops the stream with its* `Problem`, except for statuses that ask the client to try again. Other- * failures and 45 seconds of silence are retried.+ * failures and 45 seconds of silence are retried. A URL given as a function+ * is read before each connection. It can throw a `StreamStopped` to stop.*/-export function sse(url: URL, connection: Connection): Transport {+export function sse(url: StreamUrl, options: SseOptions = {}): Transport {return async ({ cursor, signal }, { open, message }) => {- const headers = new Headers(connection.headers);+ const headers = new Headers();headers.set("Accept", "text/event-stream");- if (connection.token !== undefined) {- headers.set("Authorization", `Bearer ${connection.token}`);+ if (options.token !== undefined) {+ headers.set("Authorization", `Bearer ${options.token}`);}if (cursor !== null) {headers.set("Last-Event-ID", cursor);@@ -95,15 +112,17 @@ export function sse(url: URL, connection: Connection): Transport {const abort = () => controller.abort();signal.addEventListener("abort", abort, { once: true });let silence: ReturnType<typeof setTimeout> | undefined;+ let stopped: Error | undefined;const listen = () => {clearTimeout(silence);silence = setTimeout(abort, SILENCE_MS);};try {- const fetch = connection.fetch ?? globalThis.fetch;+ const target = new URL(typeof url === "function" ? await url() : url);+ const fetch = options.fetch ?? globalThis.fetch;// A host that accepts the request but never answers counts as silence.listen();- const response = await fetch(url, {+ const response = await fetch(target, {headers,signal: controller.signal,});@@ -149,10 +168,14 @@ export function sse(url: URL, connection: Connection): Transport {if (done) {return;}+ stopped = options.stop?.(value);+ if (stopped !== undefined) {+ throw stopped;+ }message(value);}} catch (error) {- if (error instanceof StreamStopped) {+ if (error instanceof StreamStopped || error === stopped) {throw error;}} finally {diff --git a/packages/client/src/transport/stream.ts b/packages/client/src/transport/stream.tsindex e472105fc2..a748df2464 100644--- a/packages/client/src/transport/stream.ts+++ b/packages/client/src/transport/stream.ts@@ -1,7 +1,8 @@/* Copyright 2026 Marimo. All rights reserved. */+import { z } from "zod";import * as Protocol from "../protocol.ts";-import { type Frame, isFrame, StreamStopped } from "./frame.ts";+import { type Frame, StreamStopped } from "./frame.ts";/** An event the host sends for a kind outside the protocol, such as `marimo`. */type ExtensionEvent<Name extends string> = Name extends unknown@@ -23,7 +24,9 @@ export type StreamEvent<K extends string = Protocol.ObjectTypeOutput> =| ExtensionEvent<Exclude<K, Protocol.ObjectTypeOutput>>;/** What an `EventStream` delivers and where it starts. */-export interface EventStreamInit<K extends string = Protocol.ObjectTypeOutput> {+export interface EventStreamOptions<+ K extends string = Protocol.ObjectTypeOutput,+> {/*** The kinds to deliver.*@@ -45,6 +48,13 @@ const PROTOCOL_EVENTS = new Set<string>(Protocol.Event.options.flatMap((schema) => schema.shape.event.options),);+/** The envelope every stream event has, before its data is validated. */+const Envelope = z.object({+ event: z.string().min(1),+ data: z.unknown(),+ id: z.string().optional(),+});+/** Rethrow a listener's error without interrupting the stream. */export function report(error: unknown): void {queueMicrotask(() => {@@ -74,7 +84,7 @@ export class EventStream<const K extends string = Protocol.ObjectTypeOutput> {readonly #wanted: ReadonlySet<string>;readonly #listeners = new Set<(event: StreamEvent<K>) => void>();- public constructor(init: EventStreamInit<K>, kinds: readonly string[]) {+ public constructor(init: EventStreamOptions<K>, kinds: readonly string[]) {this.#cursor = init.cursor ?? null;this.#wanted = new Set(["ready",@@ -122,13 +132,17 @@ export class EventStream<const K extends string = Protocol.ObjectTypeOutput> {* Accept one message from the connection.** Throws `StreamStopped` when the message is not an event or an event the- * protocol defines is invalid. The caller stops following the stream then.+ * protocol defines is invalid. Its `cause` is the validation error. The+ * caller stops following the stream then.*/public receive(message: unknown): void {- if (!isFrame(message)) {- throw new StreamStopped("The host sent a message that is not an event");+ const envelope = Envelope.safeParse(message);+ if (!envelope.success) {+ throw new StreamStopped("The host sent a message that is not an event", {+ cause: envelope.error,+ });}- this.#accept(message);+ this.#accept(envelope.data);}#accept(frame: Frame) {