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.

Add root `Client` and reducers (#11394)

Trevor Manzb18f0b9ac27e
diff --git a/frontend/src/core/host/__tests__/attachments.test.ts b/frontend/src/core/host/__tests__/attachments.test.ts
index ac65f5b8a0..731f9fef9c 100644
--- a/frontend/src/core/host/__tests__/attachments.test.ts
+++ b/frontend/src/core/host/__tests__/attachments.test.ts
@@ -2,10 +2,10 @@
import { describe, expect, it } from "vitest";
import { attachments } from "../resources/attachments";
-import { createReducer } from "@marimo-team/client/reducer";
+import { createNotebookReducer } from "@marimo-team/client";
import { fixtureEvents } from "./fixtures";
-const reducer = createReducer({ attachments });
+const reducer = createNotebookReducer({ attachments });
const snapshot = fixtureEvents("notebook-events.sse");
const records = snapshot.flatMap((event) =>
event.event === "attachment" ? [event.data.attachment] : [],
diff --git a/frontend/src/core/host/__tests__/document.test.ts b/frontend/src/core/host/__tests__/document.test.ts
index 12142310a9..b65462db85 100644
--- a/frontend/src/core/host/__tests__/document.test.ts
+++ b/frontend/src/core/host/__tests__/document.test.ts
@@ -3,10 +3,10 @@
import { describe, expect, it } from "vitest";
import type * as Protocol from "@marimo-team/client/protocol";
import { document } from "../resources/document";
-import { createReducer } from "@marimo-team/client/reducer";
+import { createNotebookReducer } from "@marimo-team/client";
import { fixtureEvents } from "./fixtures";
-const reducer = createReducer({ document });
+const reducer = createNotebookReducer({ document });
const snapshot = fixtureEvents("notebook-events.sse");
const edits = fixtureEvents("edits.sse");
diff --git a/frontend/src/core/host/notebook-client.ts b/frontend/src/core/host/notebook-client.ts
index 69b61300bb..c30a5e5be5 100644
--- a/frontend/src/core/host/notebook-client.ts
+++ b/frontend/src/core/host/notebook-client.ts
@@ -2,7 +2,7 @@
import { Logger } from "@/utils/Logger";
import type { Attachment, NotebookOutput } from "@marimo-team/client/protocol";
-import { createReducer } from "@marimo-team/client/reducer";
+import { createNotebookReducer } from "@marimo-team/client";
import { type Atom, atom, type createStore } from "jotai/vanilla";
import {
type ConnectionStatus,
@@ -69,7 +69,7 @@ export function createNotebookClient(store: ReturnType<typeof createStore>) {
state: ConnectionState.NOT_STARTED,
});
// One atom holds the whole stream, which resource atoms derive from.
- const reducer = createReducer({ document, attachments });
+ const reducer = createNotebookReducer({ document, attachments });
const streamAtom = atom(reducer.initial);
// A resumed stream is live, but presence waits for this connection's ready.
const readyAtom = atom(false);
diff --git a/frontend/src/core/host/resources/attachments.ts b/frontend/src/core/host/resources/attachments.ts
index 3b876cdbb6..973e3d9577 100644
--- a/frontend/src/core/host/resources/attachments.ts
+++ b/frontend/src/core/host/resources/attachments.ts
@@ -1,10 +1,13 @@
/* Copyright 2026 Marimo. All rights reserved. */
import type { Attachment } from "@marimo-team/client/protocol";
-import type { Resource } from "@marimo-team/client/reducer";
+import type { NotebookResource } from "@marimo-team/client";
/** Attachment records retained with the stream's resume cursor. */
-export const attachments: Resource<readonly Attachment[], "attachment"> = {
+export const attachments: NotebookResource<
+ readonly Attachment[],
+ "attachment"
+> = {
initial: [],
on: {
attachment: (state, { data: { attachment } }) =>
diff --git a/frontend/src/core/host/resources/document.ts b/frontend/src/core/host/resources/document.ts
index 56c7f11563..4168c35851 100644
--- a/frontend/src/core/host/resources/document.ts
+++ b/frontend/src/core/host/resources/document.ts
@@ -1,7 +1,7 @@
/* Copyright 2026 Marimo. All rights reserved. */
import type * as Protocol from "@marimo-team/client/protocol";
-import type { Resource } from "@marimo-team/client/reducer";
+import type { NotebookResource } from "@marimo-team/client";
/**
* The notebook's content at one revision.
@@ -58,7 +58,7 @@ function publish(
return { current: { revision, cells }, pending: null };
}
-export const document: Resource<DocumentState, "cell" | "document"> = {
+export const document: NotebookResource<DocumentState, "cell" | "document"> = {
initial: { current: null, pending: null },
on: {
cell: (state, { data }) => {
diff --git a/packages/client/README.md b/packages/client/README.md
index 1cc9f38dec..29add73451 100644
--- a/packages/client/README.md
+++ b/packages/client/README.md
@@ -1,67 +1,128 @@
# @marimo-team/client
-A typed client for notebooks served by a marimo host. Hosts expose each
-notebook through the [host protocol](../../protocols/host/README.md), an HTTP
-API with its own event stream. `NotebookClient` sends the protocol's requests
-for one notebook, addressed by the notebook's URL. Request bodies are
-validated before they are sent, and the host's answer comes back as data or a
-problem.
-
-`NotebookEvents` follows a notebook's stream. The stream starts with a
-snapshot that ends in `ready` and then delivers changes. When a connection
-drops, the stream resumes from the last event it received. When it cannot,
-it delivers `reset` and a fresh snapshot follows. Given a URL, it follows the
-stream over server-sent events, as the protocol defines. Given a
-`NotebookTransport`, it follows whatever connection the transport opens.
+Connect to a marimo host to find notebooks, read their state, and request
+edits or execution. A host serves notebooks through the
+[host protocol](../../protocols/host/spec.md). `Client` works with the host's
+catalog. `NotebookClient` works with one notebook.
+
+## Connect to a host
+
+Give `Client` the host's API base URL and token. These can come from your
+application's configuration or the host's
+[local discovery record](../../protocols/host/spec.md#local-discovery).
```ts
-import { NotebookClient } from "@marimo-team/client";
-
-const notebook = new NotebookClient(
- "http://127.0.0.1:2718/api/marimo/v1/notebooks/n1",
- { token: "your-token" },
-);
-
-const result = await notebook.edit([
- { kind: "delete_cell", id: "c3", base_etag: "*" },
-]);
-if (!result.ok) {
- console.error(result.problem.type);
-}
+import { Client } from "@marimo-team/client";
+
+const client = new Client("http://127.0.0.1:2718/api/marimo/v1", {
+ token: "your-token",
+});
+```
+
+Requests use HTTP and event streams use server-sent events. Pass `fetch` or
+`headers` alongside `token` to customize requests.
+
+## Find notebooks
+
+The catalog stream describes the host's notebooks, projects, runtimes, and
+attachments. It also reports the host's capabilities. This example prints
+the notebooks the host currently knows about.
-for await (const event of notebook.events({ types: ["cell", "document"] })) {
- if (event.event === "reset") {
- // Discard what you built. A fresh snapshot follows.
+```ts
+for await (const event of client.events({ types: ["notebook"] })) {
+ if (event.event === "notebook") {
+ console.log(event.data.notebook.id, event.data.notebook.name);
}
+ if (event.event === "ready") break;
+}
+```
+
+`ready` ends the initial snapshot. Breaking out closes the stream. Projects
+may still be indexing when `ready` arrives, so more notebooks can appear
+afterward.
+
+## Work with a notebook
+
+Use an id or a notebook record from the catalog to get a `NotebookClient`.
+This example reads the document, prints its cell count, and asks the host
+to save it. It assumes the notebook supports `notebook.save`.
+
+```ts
+import type { DocumentOutput } from "@marimo-team/client/protocol";
+
+const notebook = client.notebook("n1");
+let document: DocumentOutput | undefined;
+
+for await (const event of notebook.events({ types: ["document"] })) {
+ if (event.event === "document") document = event.data.document;
+ if (event.event === "reset") document = undefined;
+ if (event.event === "ready") break;
+}
+
+if (document === undefined) throw new Error("The host did not send a document");
+console.log(`${document.order.length} cells`);
+
+const result = await notebook.save({ ifMatch: document.etag });
+if (result.ok) {
+ console.log("Saved", result.data.document.etag);
+} else {
+ console.error(result.problem);
}
```
-## Entry points
+`ifMatch` makes the document's etag a precondition. If the document changes
+before the save, the host returns a conflict problem. Other actions, such
+as `edit` and `run`, use the same result shape. The notebook's advertised
+operations describe which actions it permits. Invalid request data,
+invalid responses, and connection failures throw.
+
+You can also construct a `NotebookClient` directly when you already know
+the notebook's URL.
+
+## Follow changes
+
+Keep iterating after `ready` to follow changes. Streams reconnect and resume
+from their last cursor. If they cannot resume, they deliver `reset` followed
+by a new snapshot. Discard accumulated state on `reset` before applying the
+snapshot.
-- `@marimo-team/client` exports `NotebookClient` and `NotebookEvents`.
-- `@marimo-team/client/protocol` has the protocol's types and zod 4 schemas,
- generated from `protocols/host/openapi.yaml`. Use the schemas to validate
- protocol data yourself, for example in a host or a conformance test.
-- `@marimo-team/client/reducer` composes resources into a pure reducer over a
- notebook stream. It handles `ready`, `reset`, and the notebook's identity,
- so each resource handles the events of its own kinds.
+To maintain a notebook list or document state from events, see the
+[reducer guide](REDUCERS.md).
-## Development
+To follow events over a WebSocket or another connection, see the
+[custom transport guide](TRANSPORTS.md).
-The package is consumed from `dist`. Build it once, or keep it built while
-you work.
+## Contributing
+
+The [host protocol](../../protocols/host/spec.md) explains the model and
+behavior. [OpenAPI](../../protocols/host/openapi.yaml) defines the routes and
+payloads. `@marimo-team/client/protocol` exports the TypeScript types and Zod
+schemas generated from it.
+
+Run these commands from the repository root. See
+[CONTRIBUTING.md](../../CONTRIBUTING.md) for setup.
+
+The package is consumed from `dist`. Build it once, or watch for changes
+while developing.
```sh
pnpm --dir packages/client build
pnpm --dir packages/client build --watch
```
-`src/operations.ts` is generated from the same spec as the schemas. It
-describes each operation for the client to call and is not exported.
-
-Regenerate and check the generated files.
+After changing OpenAPI, regenerate the protocol types, schemas, and
+operation definitions. `codegen:check` checks that generated files match
+the specification.
```sh
pnpm --dir packages/client codegen
pnpm --dir packages/client codegen:check
```
+
+Run the package's tests and typecheck. Omit `--run` to watch tests while
+developing.
+
+```sh
+pnpm --dir packages/client test --run
+pnpm --dir packages/client typecheck
+```
diff --git a/packages/client/REDUCERS.md b/packages/client/REDUCERS.md
new file mode 100644
index 0000000000..c98f26ccda
--- /dev/null
+++ b/packages/client/REDUCERS.md
@@ -0,0 +1,118 @@
+# Keep state from events
+
+Host state is read over event streams. The catalog stream describes the
+host's notebooks, projects, runtimes, and attachments. A notebook stream
+describes one notebook's document and execution state.
+
+A stream starts with a snapshot of the current state. A `ready` event marks
+the end of the snapshot. Subsequent events report changes. For example, a
+`notebook` event carries the notebook's current record, and
+`notebook.removed` identifies a notebook that was removed.
+
+`CatalogEvents` and `NotebookEvents` validate incoming events and track the
+cursor used to resume after a disconnect. They deliver events through an
+async iterator or a subscription. Your application decides which records
+to retain. If the stream cannot resume, it delivers `reset` followed by a
+new snapshot that replaces the previous state.
+
+## Keep a notebook list
+
+To keep a notebook list, define a resource that starts with an empty list.
+Its `notebook` handler adds or replaces an entry. Its `notebook.removed`
+handler removes an entry by id. Each entry keeps only the notebook's id
+and name.
+
+Pass the resource to `createCatalogReducer`, then apply each event with
+`reduce(state, event)`. The resulting list is in `state.resources.notebooks`.
+This example stops at `ready` and prints the list from the snapshot.
+
+```ts
+import type { NotebookOutput } from "@marimo-team/client/protocol";
+import {
+ Client,
+ createCatalogReducer,
+ type CatalogResource,
+} from "@marimo-team/client";
+
+type NotebookSummary = Pick<NotebookOutput, "id" | "name">;
+
+const notebooks: CatalogResource<readonly NotebookSummary[], "notebook"> = {
+ initial: [],
+ on: {
+ notebook: (state, { data }) => [
+ ...state.filter((entry) => entry.id !== data.notebook.id),
+ { id: data.notebook.id, name: data.notebook.name },
+ ],
+ "notebook.removed": (state, { data }) =>
+ state.filter((entry) => entry.id !== data.id),
+ },
+};
+
+const reducer = createCatalogReducer({ notebooks });
+const client = new Client("http://127.0.0.1:2718/api/marimo/v1", {
+ token: "your-token",
+});
+let state = reducer.initial;
+
+for await (const event of client.events({ types: ["notebook"] })) {
+ state = reducer.reduce(state, event);
+ if (event.event === "ready") break;
+}
+
+console.log(state.resources.notebooks);
+```
+
+The reducer handles the stream's lifecycle. `ready` changes `state.phase`
+from `snapshot` to `live`. `reset` returns the phase to `snapshot` and each
+resource to its initial value. Resources can handle `ready` to finish
+assembling a snapshot. The handler's third argument contains the phase
+before the event is applied. It is `snapshot` for the initial `ready` and
+`live` for a `ready` that follows a resumed connection.
+
+Handlers return a new value when state changes and the existing value
+otherwise. They must not modify the previous value or perform side effects.
+
+For a notebook stream, define a `NotebookResource` and pass it to
+`createNotebookReducer`. This reducer also keeps the notebook's record and
+identity in `notebook` and `notebookId`. It handles `notebook` and
+`notebook.removed` itself. Removing the notebook clears its record and
+resources. A `reset` also clears its identity.
+
+## Follow changes in React
+
+To keep a notebook list updated in a UI, subscribe to the stream and pass
+each event to the reducer through your store's state update function. This
+hook uses React state. It removes the subscription and closes the stream
+when the effect is cleaned up.
+
+```tsx
+import { useEffect, useState } from "react";
+
+function useNotebooks(client: Client) {
+ const [state, setState] = useState(reducer.initial);
+
+ useEffect(() => {
+ setState(reducer.initial);
+ const events = client.events({ types: ["notebook"] });
+ const unsubscribe = events.subscribe((event) => {
+ setState((current) => reducer.reduce(current, event));
+ });
+ return () => {
+ unsubscribe();
+ events.close();
+ };
+ }, [client]);
+
+ return state;
+}
+```
+
+Keep the client instance stable across renders. Temporary disconnects preserve
+state while the stream resumes. A `reset` rebuilds it. `events.closed` rejects
+if the stream stops with an error, so you can use it to surface connection
+failures in your application.
+
+If you persist state for a later connection, save its matching cursor and
+reuse the same host, stream, and filter. The stream's cursor tracks received
+events. When state updates are queued, as in React, it can be ahead of the
+state you have applied. Resume needs both state and its matching cursor.
diff --git a/packages/client/TRANSPORTS.md b/packages/client/TRANSPORTS.md
new file mode 100644
index 0000000000..a6931909c3
--- /dev/null
+++ b/packages/client/TRANSPORTS.md
@@ -0,0 +1,30 @@
+# Custom transports
+
+`Client` and `NotebookClient` send HTTP requests and read server-sent events.
+To follow events from an existing WebSocket, message channel, or another
+source, pass a `Transport` function to `NotebookEvents` or `CatalogEvents`.
+
+The stream calls the transport once for each connection attempt. The
+transport receives a cursor and an abort signal. A null cursor requests a
+snapshot. Otherwise, the transport sends the cursor to the host to resume
+after that position.
+
+Call `open()` when the connection is established. Call `message(event)` for
+each decoded protocol event, in order. Close the connection when the signal
+is aborted.
+
+Resolve when the connection ends and another attempt makes sense. Reject
+when the stream should stop. The stream's `closed` promise rejects with the
+same error. Use `StreamStopped` to describe the failure.
+
+The stream validates events, tracks the cursor, delivers events to
+subscribers, and reconnects. It delivers `reset` when an interrupted snapshot
+must be discarded. The host must also send `reset` when it cannot resume
+from the supplied cursor.
+
+The transport sends any filters the host needs. The stream's `types` option
+filters delivered events locally. A notebook transport must apply `runId`
+itself. Each reconnect must use the same filters.
+
+See the [transport contract](src/transport/frame.ts) for the function and
+event types.
diff --git a/packages/client/package.json b/packages/client/package.json
index 4208077456..5c8d6c56e7 100644
--- a/packages/client/package.json
+++ b/packages/client/package.json
@@ -8,8 +8,7 @@
"license": "Apache-2.0",
"exports": {
".": "./dist/index.js",
- "./protocol": "./dist/protocol.js",
- "./reducer": "./dist/reducer.js"
+ "./protocol": "./dist/protocol.js"
},
"files": [
"dist"
diff --git a/packages/client/src/__tests__/catalog-events.test.ts b/packages/client/src/__tests__/catalog-events.test.ts
new file mode 100644
index 0000000000..d799c96407
--- /dev/null
+++ b/packages/client/src/__tests__/catalog-events.test.ts
@@ -0,0 +1,200 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { afterEach, describe, expect, expectTypeOf, it, vi } from "vitest";
+import { createCatalogReducer } from "../index.ts";
+import { notebooks, projects } from "./catalog-resources.ts";
+import {
+ CatalogEvents,
+ type CatalogEvent,
+ type CatalogEventsInit,
+ type Transport,
+} from "../index.ts";
+import { fixtureEvents } from "./fixtures.ts";
+
+const snapshot = fixtureEvents("events.sse");
+const ready = snapshot.findIndex((event) => event.event === "ready");
+const record = snapshot.find((event) => event.event === "notebook")!.data
+ .notebook;
+
+/** A transport whose last connection stays open until closed by the caller. */
+function scripted(...connections: (readonly unknown[])[]) {
+ const attempts: (string | null)[] = [];
+ const transport: Transport = async (
+ { cursor, signal },
+ { open, message },
+ ) => {
+ attempts.push(cursor);
+ open();
+ const events = connections.shift();
+ events?.forEach(message);
+ if (connections.length === 0 && !signal.aborted) {
+ await new Promise<void>((resolve) =>
+ signal.addEventListener("abort", () => resolve(), { once: true }),
+ );
+ }
+ };
+ return { transport, attempts };
+}
+
+afterEach(() => vi.useRealTimers());
+
+describe("CatalogEvents", () => {
+ it("lets a caller wait for the complete snapshot and close the stream", async () => {
+ const { transport } = scripted(snapshot);
+ const events = new CatalogEvents(transport);
+ const reducer = createCatalogReducer({ notebooks, projects });
+ let state = reducer.initial;
+ for await (const event of events) {
+ state = reducer.reduce(state, event);
+ if (event.event === "ready") {
+ break;
+ }
+ }
+ expect(state.phase).toBe("live");
+ expect(state.resources.notebooks).toEqual([record]);
+ expect(state.resources.projects.map((project) => project.id)).toEqual([
+ "p1",
+ ]);
+ expect(events.status).toBe("closed");
+ await expect(events.closed).resolves.toBeUndefined();
+ });
+
+ it("resumes with caller-owned state and applies replay before ready", async () => {
+ vi.useFakeTimers();
+ const renamed = { ...record, name: "Renamed" };
+ const { transport, attempts } = scripted(snapshot.slice(0, ready + 1), [
+ { event: "notebook", id: "42", data: { notebook: renamed } },
+ { event: "ready", id: "42", data: {} },
+ ]);
+ const events = new CatalogEvents(transport);
+ const reducer = createCatalogReducer({ notebooks });
+ let state = reducer.initial;
+ events.subscribe((event) => {
+ state = reducer.reduce(state, event);
+ });
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(attempts).toEqual([null, "41"]);
+ expect(state).toEqual({
+ phase: "live",
+ resources: { notebooks: [renamed] },
+ });
+ expect(events.cursor).toBe("42");
+ events.close();
+ });
+
+ it("discards an interrupted snapshot before reconnecting without a cursor", async () => {
+ vi.useFakeTimers();
+ const { transport, attempts } = scripted(snapshot.slice(0, ready), [
+ { event: "notebook", data: { notebook: { ...record, id: "n2" } } },
+ { event: "ready", id: "50", data: {} },
+ ]);
+ const events = new CatalogEvents(transport);
+ const reducer = createCatalogReducer({ notebooks });
+ let state = reducer.initial;
+ const names: string[] = [];
+ events.subscribe((event) => {
+ names.push(event.event);
+ state = reducer.reduce(state, event);
+ });
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(attempts).toEqual([null, null]);
+ expect(names).toEqual([
+ "host",
+ "project",
+ "notebook",
+ "runtime",
+ "attachment",
+ "reset",
+ "notebook",
+ "ready",
+ ]);
+ expect(state.resources.notebooks.map((entry) => entry.id)).toEqual(["n2"]);
+ events.close();
+ });
+
+ it("clears the cursor and caller state when a saved cursor cannot be resumed", async () => {
+ const replacement = fixtureEvents("events-reset.sse");
+ const { transport, attempts } = scripted(replacement);
+ const events = new CatalogEvents(transport, { cursor: "old" });
+ const reducer = createCatalogReducer({ notebooks });
+ let state = reducer.reduce(reducer.initial, {
+ event: "notebook",
+ data: { notebook: { ...record, id: "stale" } },
+ });
+ const cursors: (string | null)[] = [];
+ events.subscribe((event) => {
+ state = reducer.reduce(state, event);
+ cursors.push(events.cursor);
+ });
+ await vi.waitFor(() => expect(events.cursor).toBe("57"));
+ expect(attempts).toEqual(["old"]);
+ expect(cursors).toEqual([
+ ...replacement.slice(0, -1).map(() => null),
+ "57",
+ ]);
+ expect(state.resources.notebooks.map((entry) => entry.id)).toEqual(["n1"]);
+ events.close();
+ });
+
+ it("filters catalog kinds while tracking positions of undispatched events", async () => {
+ const { transport } = scripted([
+ ...snapshot,
+ { event: "future", id: "46", data: "unknown" },
+ ]);
+ const events = new CatalogEvents(transport, { types: ["notebook"] });
+ const received: CatalogEvent<"notebook">[] = [];
+ events.subscribe((event) => received.push(event));
+ await vi.waitFor(() => expect(events.cursor).toBe("46"));
+ expect(received.map((event) => event.event)).toEqual([
+ "notebook",
+ "ready",
+ "notebook",
+ ]);
+ expectTypeOf<CatalogEvent<"notebook">["event"]>().toEqualTypeOf<
+ "notebook" | "notebook.removed" | "ready" | "reset"
+ >();
+ expectTypeOf<CatalogEventsInit>().not.toHaveProperty("runId");
+ expectTypeOf<CatalogEventsInit["types"]>().toEqualTypeOf<
+ | readonly ("host" | "project" | "notebook" | "runtime" | "attachment")[]
+ | undefined
+ >();
+ events.close();
+ });
+
+ it("delivers only catalog events by default", async () => {
+ const cell = fixtureEvents("notebook-events.sse").find(
+ (event) => event.event === "cell",
+ )!;
+ const { transport } = scripted([
+ ...snapshot,
+ { ...cell, id: "46" },
+ { event: "host.removed", id: "47", data: {} },
+ ]);
+ const events = new CatalogEvents(transport);
+ const received: CatalogEvent[] = [];
+ events.subscribe((event) => received.push(event));
+ await vi.waitFor(() => expect(events.cursor).toBe("47"));
+ expect(received).toEqual(snapshot);
+ events.close();
+ });
+
+ it("rejects invalid catalog records", async () => {
+ const { transport } = scripted([
+ { event: "project", data: { project: { id: "p1" } } },
+ ]);
+ const events = new CatalogEvents(transport);
+ await expect(events.closed).rejects.toThrow("invalid project event");
+ expect(events.status).toBe("closed");
+ });
+
+ it("aborts the transport and closes pending iteration", async () => {
+ const controller = new AbortController();
+ const { transport } = scripted([]);
+ const events = new CatalogEvents(transport, { signal: controller.signal });
+ const iterator = events[Symbol.asyncIterator]();
+ const next = iterator.next();
+ controller.abort();
+ await expect(next).resolves.toEqual({ done: true, value: undefined });
+ await expect(events.closed).resolves.toBeUndefined();
+ });
+});
diff --git a/packages/client/src/__tests__/catalog-reducer.test.ts b/packages/client/src/__tests__/catalog-reducer.test.ts
new file mode 100644
index 0000000000..d652a78144
--- /dev/null
+++ b/packages/client/src/__tests__/catalog-reducer.test.ts
@@ -0,0 +1,92 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import type { CatalogEvent } from "../index.ts";
+import { describe, expect, it } from "vitest";
+import { createCatalogReducer, type CatalogResource } from "../index.ts";
+import { fixtureEvents } from "./fixtures.ts";
+import { notebooks, projects } from "./catalog-resources.ts";
+
+const snapshot = fixtureEvents("events.sse") as CatalogEvent[];
+const record = snapshot.find((event) => event.event === "notebook")!.data
+ .notebook;
+const ready = snapshot.findIndex((event) => event.event === "ready");
+
+describe("catalog reducer", () => {
+ it("composes caller resources and discards their state on reset", () => {
+ const reducer = createCatalogReducer({ notebooks, projects });
+ const partial = snapshot
+ .slice(0, ready)
+ .reduce(reducer.reduce, reducer.initial);
+ expect(partial).toEqual({
+ phase: "snapshot",
+ resources: {
+ notebooks: [record],
+ projects: [
+ snapshot.find((event) => event.event === "project")!.data.project,
+ ],
+ },
+ });
+ const live = snapshot.slice(ready).reduce(reducer.reduce, partial);
+ expect(live.phase).toBe("live");
+ expect(live.resources.notebooks[0].updated_at).toBe("2026-10-01T09:21:02Z");
+ expect(live.resources.projects).toBe(partial.resources.projects);
+ const reset = fixtureEvents("events-reset.sse") as CatalogEvent[];
+ expect(reducer.reduce(live, reset[0])).toBe(reducer.initial);
+ expect(reset.reduce(reducer.reduce, live)).toEqual(live);
+ expect(reducer.initial).toEqual({
+ phase: "snapshot",
+ resources: { notebooks: [], projects: [] },
+ });
+ });
+
+ it("dispatches notebook records and removals without enforcing one identity", () => {
+ const reducer = createCatalogReducer({ notebooks, projects });
+ const first = snapshot.reduce(reducer.reduce, reducer.initial);
+ const other = { ...record, id: "n2" };
+ const both = reducer.reduce(first, {
+ event: "notebook",
+ data: { notebook: other },
+ });
+ expect(both.resources.notebooks.map((entry) => entry.id)).toEqual([
+ "n1",
+ "n2",
+ ]);
+ const removed = reducer.reduce(both, {
+ event: "notebook.removed",
+ data: { id: "n1" },
+ });
+ expect(removed).toEqual({
+ phase: "live",
+ resources: { notebooks: [other], projects: first.resources.projects },
+ });
+ expect(first.resources.notebooks).toHaveLength(1);
+ });
+
+ it("preserves state when no handler changes it", () => {
+ const reducer = createCatalogReducer({ notebooks });
+ const state = snapshot.reduce(reducer.reduce, reducer.initial);
+ expect(
+ reducer.reduce(state, {
+ event: "host",
+ data: { host: { operations: [] } },
+ }),
+ ).toBe(state);
+ expect(
+ reducer.reduce(state, { event: "ready", id: "next", data: {} }),
+ ).toBe(state);
+ });
+
+ it("passes snapshot and replay phases to resource handlers", () => {
+ const phases: CatalogResource<readonly string[], "notebook"> = {
+ initial: [],
+ on: { ready: (state, _event, context) => [...state, context.phase] },
+ };
+ const reducer = createCatalogReducer({ phases });
+ const readyEvent: CatalogEvent = { event: "ready", id: "1", data: {} };
+ const live = reducer.reduce(reducer.initial, readyEvent);
+ const resumed = reducer.reduce(live, readyEvent);
+ expect(resumed.resources.phases).toEqual(["snapshot", "live"]);
+ const reset = reducer.reduce(resumed, { event: "reset", data: {} });
+ expect(reducer.reduce(reset, readyEvent)).toEqual(live);
+ });
+});
diff --git a/packages/client/src/__tests__/catalog-resources.ts b/packages/client/src/__tests__/catalog-resources.ts
new file mode 100644
index 0000000000..2dddce6293
--- /dev/null
+++ b/packages/client/src/__tests__/catalog-resources.ts
@@ -0,0 +1,28 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import type { NotebookOutput, ProjectOutput } from "../protocol.ts";
+import type { CatalogResource } from "../index.ts";
+
+/** An example application keeps just the records it uses. */
+export const notebooks: CatalogResource<readonly NotebookOutput[], "notebook"> =
+ {
+ initial: [],
+ on: {
+ notebook: (state, { data }) => [
+ ...state.filter((entry) => entry.id !== data.notebook.id),
+ data.notebook,
+ ],
+ "notebook.removed": (state, { data }) =>
+ state.filter((entry) => entry.id !== data.id),
+ },
+ };
+
+export const projects: CatalogResource<readonly ProjectOutput[], "project"> = {
+ initial: [],
+ on: {
+ project: (state, { data }) => [
+ ...state.filter((entry) => entry.id !== data.project.id),
+ data.project,
+ ],
+ },
+};
diff --git a/packages/client/src/__tests__/client.test.ts b/packages/client/src/__tests__/client.test.ts
new file mode 100644
index 0000000000..cd913026c1
--- /dev/null
+++ b/packages/client/src/__tests__/client.test.ts
@@ -0,0 +1,137 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { describe, expect, expectTypeOf, it, vi } from "vitest";
+import { z } from "zod";
+import { Client, NotebookClient } from "../index.ts";
+import type * as Protocol from "../protocol.ts";
+import { fixtureEvents } from "./fixtures.ts";
+
+const record = fixtureEvents("events.sse").find(
+ (event) => event.event === "notebook",
+)!.data.notebook;
+
+function connect(response: () => Response) {
+ const fetch = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) =>
+ response(),
+ );
+ const client = new Client(
+ "http://localhost/prefix/api/marimo/v1/?session_id=s1",
+ {
+ token: "secret",
+ headers: { "X-Example": "1" },
+ fetch,
+ },
+ );
+ const sent = (index = 0) => new Request(...fetch.mock.calls[index]);
+ return { client, fetch, sent };
+}
+
+describe("Client", () => {
+ it("creates a notebook with the shared request conventions", async () => {
+ const { client, sent } = connect(() =>
+ Response.json(record, { status: 201 }),
+ );
+ const input = { project_id: "p1", path: "forecasts.py" };
+ const result = await client.createNotebook(input, {
+ idempotencyKey: "create-1",
+ });
+ expectTypeOf(result).toEqualTypeOf<
+ | {
+ readonly ok: true;
+ readonly status: number;
+ readonly data: Protocol.NotebookOutput;
+ }
+ | {
+ readonly ok: false;
+ readonly status: number;
+ readonly problem: Protocol.ProblemOutput;
+ }
+ >();
+ expect(result).toEqual({ ok: true, status: 201, data: record });
+ const request = sent();
+ expect(request.url).toBe(
+ "http://localhost/prefix/api/marimo/v1/notebooks?session_id=s1",
+ );
+ 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);
+ });
+
+ it("constructs notebook clients without fetching or retaining their records", async () => {
+ const { client, fetch, sent } = connect(
+ () => new Response(null, { status: 204 }),
+ );
+ const entry = { ...record, id: "n/1?#%" };
+ const notebook = client.notebook(entry);
+ expect(notebook).toBeInstanceOf(NotebookClient);
+ expect(fetch).not.toHaveBeenCalled();
+ entry.id = "changed";
+ client.url.host = "elsewhere.example";
+ await notebook.delete();
+ expect(sent().url).toBe(
+ "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,
+ );
+ });
+
+ it.each(["", ".", ".."])("rejects an invalid notebook id %j", (id) => {
+ const { client, fetch } = connect(() => new Response());
+ expect(() => client.notebook(id)).toThrow("valid notebook_id");
+ expect(fetch).not.toHaveBeenCalled();
+ });
+
+ it("validates creation requests and returns host problems", async () => {
+ const problem = {
+ type: "tag:marimo.io,2026:host/conflict",
+ title: "Conflict",
+ status: 409,
+ };
+ const { client, fetch } = connect(() =>
+ Response.json(problem, {
+ status: 409,
+ headers: { "Content-Type": "application/problem+json" },
+ }),
+ );
+ await expect(
+ client.createNotebook({ project_id: "" }),
+ ).rejects.toBeInstanceOf(z.ZodError);
+ expect(fetch).not.toHaveBeenCalled();
+ expect(
+ await client.createNotebook({ project_id: "p1", path: "forecasts.py" }),
+ ).toEqual({
+ ok: false,
+ status: 409,
+ problem,
+ });
+ });
+
+ it("opens independent catalog streams with inherited connection options", async () => {
+ const { client, sent, fetch } = connect(
+ () =>
+ new Response("id: 41\nevent: ready\ndata: {}\n\n", {
+ headers: { "Content-Type": "text/event-stream" },
+ }),
+ );
+ const first = client.events({ types: ["notebook"], cursor: "40" });
+ const second = client.events();
+ await vi.waitFor(() => expect(second.cursor).toBe("41"));
+ expect(fetch).toHaveBeenCalledTimes(2);
+ expect(sent().url).toBe(
+ "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();
+ expect(second.status).not.toBe("closed");
+ second.close();
+ await Promise.all([first.closed, second.closed]);
+ });
+});
diff --git a/packages/client/src/__tests__/notebook-events.test.ts b/packages/client/src/__tests__/notebook-events.test.ts
index 0c639e7108..573ce10166 100644
--- a/packages/client/src/__tests__/notebook-events.test.ts
+++ b/packages/client/src/__tests__/notebook-events.test.ts
@@ -5,7 +5,7 @@ import NodeUrl from "node:url";
import { afterEach, describe, expect, expectTypeOf, it, vi } from "vitest";
import { NotebookClient } from "../notebook/client.ts";
import { NotebookEvents } from "../notebook/events.ts";
-import type { NotebookEvent } from "../notebook/stream.ts";
+import type { NotebookEvent } from "../notebook/events.ts";
import { type NotebookTransport, StreamStopped } from "../transport/frame.ts";
import { ServerSentEventStream } from "../transport/sse.ts";
diff --git a/packages/client/src/__tests__/reducer.test.ts b/packages/client/src/__tests__/reducer.test.ts
index 3a4c47ddbf..8f2e2e7eb2 100644
--- a/packages/client/src/__tests__/reducer.test.ts
+++ b/packages/client/src/__tests__/reducer.test.ts
@@ -2,7 +2,7 @@
import { describe, expect, it } from "vitest";
import type * as Protocol from "../protocol.ts";
-import { createReducer, type Resource } from "../reducer.ts";
+import { createNotebookReducer, type NotebookResource } from "../index.ts";
import { fixtureEvents } from "./fixtures.ts";
interface CellIds {
@@ -10,7 +10,7 @@ interface CellIds {
}
/** A resource whose events are complete on their own. */
-const cells: Resource<CellIds, "cell"> = {
+const cells: NotebookResource<CellIds, "cell"> = {
initial: { ids: [] },
on: {
cell: (state, event) =>
@@ -35,7 +35,7 @@ function publish(state: Revisions): Revisions {
}
/** A resource assembled from groups of events, like a document from its cells. */
-const revisions: Resource<Revisions, "cell" | "document"> = {
+const revisions: NotebookResource<Revisions, "cell" | "document"> = {
initial: { pending: [], published: [] },
on: {
cell: (state, event) => ({
@@ -54,7 +54,7 @@ const revisions: Resource<Revisions, "cell" | "document"> = {
};
function createTestReducer() {
- return createReducer({ cells, revisions });
+ return createNotebookReducer({ cells, revisions });
}
function replay(
@@ -167,7 +167,7 @@ describe("notebook reducer", () => {
});
it("limits handlers to the events of a resource's kinds", () => {
- const documents: Resource<null, "document"> = {
+ const documents: NotebookResource<null, "document"> = {
initial: null,
on: {
document: (state) => state,
@@ -178,7 +178,7 @@ describe("notebook reducer", () => {
};
expect(documents.initial).toBeNull();
// @ts-expect-error The catalog's kinds never reach a notebook stream.
- const hosts: Resource<null, "host"> = { initial: null, on: {} };
+ const hosts: NotebookResource<null, "host"> = { initial: null, on: {} };
expect(hosts.initial).toBeNull();
});
});
diff --git a/packages/client/src/catalog/events.ts b/packages/client/src/catalog/events.ts
new file mode 100644
index 0000000000..c733faacf2
--- /dev/null
+++ b/packages/client/src/catalog/events.ts
@@ -0,0 +1,32 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { type CatalogKind, catalogKinds } from "../kinds.ts";
+import { Events, type EventsInit } from "../transport/events.ts";
+import type { Transport } from "../transport/frame.ts";
+import type { StreamEvent } from "../transport/stream.ts";
+
+/** An event delivered for the requested catalog kinds, plus ready and reset. */
+export type CatalogEvent<K extends CatalogKind = CatalogKind> = StreamEvent<K>;
+
+/** How a catalog stream reaches its host and what it follows. */
+export interface CatalogEventsInit<
+ K extends CatalogKind = CatalogKind,
+> extends EventsInit<K> {}
+
+/**
+ * The host's catalog, followed across reconnects without retaining its objects.
+ *
+ * `ready` ends the snapshot of what the host currently knows; projects may
+ * still be indexing. On `reset`, discard accumulated state before applying
+ * the fresh snapshot. Each instance has its own connection and cursor.
+ */
+export class CatalogEvents<
+ const K extends CatalogKind = CatalogKind,
+> extends Events<K> {
+ public constructor(
+ source: string | URL | Transport,
+ init: CatalogEventsInit<K> = {},
+ ) {
+ super(source, init, catalogKinds);
+ }
+}
diff --git a/packages/client/src/client.ts b/packages/client/src/client.ts
new file mode 100644
index 0000000000..3f384eb5d3
--- /dev/null
+++ b/packages/client/src/client.ts
@@ -0,0 +1,68 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { CatalogEvents, type CatalogEventsInit } 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 MutationOptions,
+ request,
+ resolve,
+ type Result,
+ 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 };
+ }
+
+ /** The host API's base URL. Each read returns a copy. */
+ public get url(): URL {
+ return new URL(this.#target.url);
+ }
+
+ /** Follow the catalog with this client's connection and an independent cursor. */
+ public events<const K extends CatalogKind = CatalogKind>(
+ options: Omit<CatalogEventsInit<K>, keyof Connection> = {},
+ ): CatalogEvents<K> {
+ return new CatalogEvents<K>(below(this.#target.url, "/events"), {
+ ...this.#target.connection,
+ ...options,
+ });
+ }
+
+ /**
+ * Address a notebook by id or catalog record, sharing this connection.
+ *
+ * Makes no request and retains no metadata. The id belongs to this host.
+ */
+ public notebook(
+ notebook: Protocol.NotebookId | Pick<Protocol.NotebookOutput, "id">,
+ ): NotebookClient {
+ const id = typeof notebook === "string" ? notebook : notebook.id;
+ return new NotebookClient(
+ resolve(this.#target, "/notebooks/{notebook_id}", { notebook_id: id }),
+ this.#target.connection,
+ );
+ }
+
+ /** Create a notebook. Its record also arrives on the catalog stream. */
+ public createNotebook(
+ notebook: Protocol.CreateNotebookRequest,
+ options?: MutationOptions,
+ ): Promise<Result<Protocol.NotebookOutput>> {
+ return request(this.#target, "notebook.create", {
+ body: notebook,
+ options,
+ });
+ }
+}
diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts
index ea6eb5aeb8..3628f5b56e 100644
--- a/packages/client/src/index.ts
+++ b/packages/client/src/index.ts
@@ -1,7 +1,37 @@
/* Copyright 2026 Marimo. All rights reserved. */
+export { Client, type ClientInit } from "./client.ts";
+export {
+ CatalogEvents,
+ type CatalogEventsInit,
+ type CatalogEvent,
+} from "./catalog/events.ts";
+export type { CatalogKind, NotebookKind } from "./kinds.ts";
export { NotebookClient, type NotebookClientInit } from "./notebook/client.ts";
-export { NotebookEvents, type NotebookEventsInit } from "./notebook/events.ts";
-export type { NotebookEvent } from "./notebook/stream.ts";
+export {
+ NotebookEvents,
+ type NotebookEventsInit,
+ type NotebookEvent,
+} from "./notebook/events.ts";
export type { Result } from "./request.ts";
-export { type NotebookTransport, StreamStopped } from "./transport/frame.ts";
+export {
+ type Transport,
+ type NotebookTransport,
+ StreamStopped,
+} from "./transport/frame.ts";
+
+export {
+ createCatalogReducer,
+ type CatalogReducer,
+ type CatalogReducerState,
+ type CatalogResource,
+ type CatalogResourceEvent,
+} from "./reducers/catalog.ts";
+export {
+ createNotebookReducer,
+ type NotebookReducer,
+ type NotebookReducerState,
+ type NotebookResource,
+ type NotebookResourceEvent,
+} from "./reducers/notebook.ts";
+export type { HandlerContext } from "./reducers/resources.ts";
diff --git a/packages/client/src/kinds.ts b/packages/client/src/kinds.ts
new file mode 100644
index 0000000000..d2d0aa158a
--- /dev/null
+++ b/packages/client/src/kinds.ts
@@ -0,0 +1,19 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { ObjectType } from "./protocol.ts";
+
+export const catalogKinds = [
+ "host",
+ "project",
+ "notebook",
+ "runtime",
+ "attachment",
+] as const satisfies readonly ObjectType[];
+
+export type CatalogKind = (typeof catalogKinds)[number];
+
+export const notebookKinds = ObjectType.options.filter(
+ (kind) => kind !== "host" && kind !== "project",
+);
+
+export type NotebookKind = (typeof notebookKinds)[number];
diff --git a/packages/client/src/notebook/client.ts b/packages/client/src/notebook/client.ts
index 22e2915f9a..a17afd050f 100644
--- a/packages/client/src/notebook/client.ts
+++ b/packages/client/src/notebook/client.ts
@@ -1,7 +1,7 @@
/* Copyright 2026 Marimo. All rights reserved. */
import type * as Protocol from "../protocol.ts";
-import type { Kind } from "../reducer.ts";
+import type { NotebookKind } from "../kinds.ts";
import {
below,
type Connection,
@@ -63,7 +63,7 @@ export class NotebookClient {
* The stream is served below the notebook's URL over server-sent events,
* and shares this client's connection.
*/
- public events<const K extends string = Kind>(
+ public events<const K extends string = NotebookKind>(
options: Omit<NotebookEventsInit<K>, keyof Connection> = {},
): NotebookEvents<K> {
return new NotebookEvents<K>(below(this.#url, "/events"), {
diff --git a/packages/client/src/notebook/events.ts b/packages/client/src/notebook/events.ts
index 52f103de43..8965f436c9 100644
--- a/packages/client/src/notebook/events.ts
+++ b/packages/client/src/notebook/events.ts
@@ -1,281 +1,40 @@
/* Copyright 2026 Marimo. All rights reserved. */
+import { type NotebookKind, notebookKinds } from "../kinds.ts";
import type * as Protocol from "../protocol.ts";
-import type { Kind } from "../reducer.ts";
-import type { Connection } from "../request.ts";
-import { type NotebookTransport, StreamStopped } from "../transport/frame.ts";
-import { sse } from "../transport/sse.ts";
-import {
- type NotebookEvent,
- NotebookStream,
- type NotebookStreamInit,
- report,
-} from "./stream.ts";
-
-/** Attempts in a row without an event before the stream gives up. */
-const ATTEMPTS = 10;
-
-/** The delay before reconnecting, which grows with each attempt in a row. */
-function delay(attempt: number): number {
- return Math.min(1000 * 1.3 ** attempt, 10_000);
-}
-
-/** Whether a stream is receiving events. */
-type Status = "connecting" | "connected" | "closed";
-
-/** How a `NotebookEvents` reaches its host and what it follows. */
-export interface NotebookEventsInit<K extends string = Kind>
- extends Connection, NotebookStreamInit<K> {
- /**
- * Follow one run instead of the whole notebook.
- *
- * Applies to a stream at a URL. A transport filters its own requests.
- */
+import { Events, type EventsInit } from "../transport/events.ts";
+import type { NotebookTransport } from "../transport/frame.ts";
+import type { StreamEvent } from "../transport/stream.ts";
+
+/** An event delivered for the requested notebook kinds, plus ready and reset. */
+export type NotebookEvent<K extends string = NotebookKind> = StreamEvent<K>;
+
+/** How a notebook stream reaches its host and what it follows. */
+export interface NotebookEventsInit<
+ K extends string = NotebookKind,
+> extends EventsInit<K> {
+ /** Follow one run. A custom transport filters its own requests. */
readonly runId?: Protocol.RunId;
- /** Aborting closes the stream. */
- readonly signal?: AbortSignal;
- /**
- * Called when `status` changes.
- *
- * Reconnecting shows as `connecting` after `connected`.
- */
- readonly onStatus?: (status: Status) => void;
-}
-
-function sleep(ms: number, signal: AbortSignal): Promise<void> {
- return new Promise((resolve) => {
- const timer = setTimeout(done, ms);
- signal.addEventListener("abort", done, { once: true });
- function done() {
- clearTimeout(timer);
- signal.removeEventListener("abort", done);
- resolve();
- }
- });
}
/**
* A notebook stream, followed across reconnects.
*
- * Given a URL, it follows the stream there over server-sent events. Given a
- * `NotebookTransport`, 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
- * attempts. It stops after ten attempts in a row without a message.
- * - When it cannot resume, it delivers `reset` and a fresh snapshot follows.
- * The caller discards what it built on `reset`.
+ * Starts with a snapshot ending in `ready`, then delivers changes. A dropped
+ * connection resumes from its cursor. On `reset`, discard accumulated state
+ * before applying the fresh snapshot. A custom transport may replace SSE.
*/
export class NotebookEvents<
- const K extends string = Kind,
-> implements AsyncIterable<NotebookEvent<K>> {
- /**
- * Settles when the stream closes.
- *
- * Resolves after `close()` or an abort. Rejects with `StreamStopped` when
- * the host refuses the stream, sends an invalid event, or cannot be reached.
- */
- public readonly closed: Promise<void>;
- readonly #stream: NotebookStream<K>;
- #status: Status = "connecting";
- readonly #controller = new AbortController();
- readonly #onStatus: ((status: Status) => void) | undefined;
- #settle: { resolve(): void; reject(error: unknown): void } | undefined;
- #release: (() => void) | undefined;
-
+ const K extends string = NotebookKind,
+> extends Events<K> {
public constructor(
source: string | URL | NotebookTransport,
init: NotebookEventsInit<K> = {},
) {
- let transport: NotebookTransport;
- if (typeof source === "function") {
- transport = source;
- } else {
- const url = new URL(source);
- if (init.types !== undefined) {
- url.searchParams.set("types", init.types.join(","));
- }
- if (init.runId !== undefined) {
- url.searchParams.set("run_id", init.runId);
- }
- transport = sse(url, init);
- }
- this.#stream = new NotebookStream<K>({
- types: init.types,
- cursor: init.cursor,
- });
- this.#onStatus = init.onStatus;
- this.closed = new Promise((resolve, reject) => {
- this.#settle = { resolve, reject };
- });
- // A caller that never awaits `closed` should not see an unhandled rejection.
- this.closed.catch(() => undefined);
- if (init.signal?.aborted) {
- this.close();
- return;
- }
- const signal = init.signal;
- if (signal !== undefined) {
- const abort = () => this.close();
- signal.addEventListener("abort", abort, { once: true });
- this.#release = () => signal.removeEventListener("abort", abort);
- }
- void this.#run(transport);
- }
-
- /** Whether the stream is receiving events. */
- public get status(): Status {
- return this.#status;
- }
-
- /**
- * The id of the last event the stream received.
- *
- * Null during a snapshot and after `reset`.
- */
- public get cursor(): string | null {
- return this.#stream.cursor;
- }
-
- /**
- * Call `listener` with each event, in order.
- *
- * Returns a function that stops calling it. A listener that throws does not
- * interrupt the stream.
- */
- public subscribe(listener: (event: NotebookEvent<K>) => void): () => void {
- return this.#stream.subscribe(listener);
- }
-
- /** Stop following the stream. */
- public close(): void {
- this.#finish()?.resolve();
- }
-
- /**
- * Iterate over events until the stream closes.
- *
- * Leaving the loop early closes the stream.
- */
- public [Symbol.asyncIterator](): AsyncIterator<NotebookEvent<K>> {
- const queue: NotebookEvent<K>[] = [];
- const waiting: (() => void)[] = [];
- const wake = () => waiting.splice(0).forEach((resolve) => resolve());
- let ended: { error?: unknown } | undefined;
- const unsubscribe = this.subscribe((event) => {
- queue.push(event);
- wake();
- });
- this.closed.then(
- () => {
- ended = {};
- wake();
- },
- (error: unknown) => {
- ended = { error };
- wake();
- },
- );
- const done = () => {
- unsubscribe();
- this.close();
- return { done: true as const, value: undefined };
- };
- return {
- next: async () => {
- for (;;) {
- const event = queue.shift();
- if (event !== undefined) {
- return { done: false, value: event };
- }
- if (ended !== undefined) {
- if (ended.error !== undefined) {
- unsubscribe();
- throw ended.error;
- }
- return done();
- }
- // Wait for the next event or for the stream to close.
- await new Promise<void>((resolve) => waiting.push(resolve));
- }
- },
- return: async () => done(),
- };
- }
-
- async #run(transport: NotebookTransport) {
- // Start after the constructor returns, so listeners added right after it
- // receive the first events.
- await Promise.resolve();
- const { signal } = this.#controller;
- let attempt = 0;
- while (!signal.aborted) {
- try {
- const cursor = this.#stream.resume();
- await transport(
- { cursor, signal },
- {
- open: () => {
- if (this.#settle !== undefined) {
- this.#setStatus("connected");
- }
- },
- message: (message) => {
- if (this.#settle === undefined) {
- return;
- }
- attempt = 0;
- try {
- this.#stream.receive(message);
- } catch (error) {
- // The transport may call this from its own event listener,
- // so stop here instead of relying on it to pass the error on.
- this.#finish()?.reject(error);
- }
- },
- },
- );
- } catch (error) {
- this.#finish()?.reject(error);
- return;
- }
- if (signal.aborted) {
- return;
- }
- this.#setStatus("connecting");
- attempt += 1;
- if (attempt > ATTEMPTS) {
- this.#finish()?.reject(
- new StreamStopped("The host could not be reached"),
- );
- return;
- }
- await sleep(delay(attempt), signal);
- }
- }
-
- #setStatus(status: Status) {
- if (this.#status === status) {
- return;
- }
- this.#status = status;
- try {
- this.#onStatus?.(status);
- } catch (error) {
- report(error);
- }
- }
-
- /** Close the stream once and return how to settle `closed`. */
- #finish() {
- const settle = this.#settle;
- if (settle === undefined) {
- return undefined;
+ if (typeof source !== "function" && init.runId !== undefined) {
+ source = new URL(source);
+ source.searchParams.set("run_id", init.runId);
}
- this.#settle = undefined;
- this.#release?.();
- this.#controller.abort();
- this.#setStatus("closed");
- return settle;
+ super(source, init, notebookKinds);
}
}
diff --git a/packages/client/src/reducers/catalog.ts b/packages/client/src/reducers/catalog.ts
new file mode 100644
index 0000000000..a109da4e1c
--- /dev/null
+++ b/packages/client/src/reducers/catalog.ts
@@ -0,0 +1,62 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import type { CatalogEvent } from "../catalog/events.ts";
+import type { CatalogKind } from "../kinds.ts";
+import {
+ composeResources,
+ type EventResource,
+ type HandlerContext,
+} from "./resources.ts";
+
+/** Catalog records, removals, and the end of a snapshot or replay. */
+export type CatalogResourceEvent<K extends CatalogKind = CatalogKind> = Exclude<
+ CatalogEvent<K>,
+ { event: "reset" }
+>;
+
+/** Pure catalog handlers. A reset returns every resource to its initial state. */
+export interface CatalogResource<
+ State,
+ K extends CatalogKind = CatalogKind,
+> extends EventResource<State, CatalogResourceEvent<K>> {}
+
+/** The caller's state for a catalog stream. */
+export interface CatalogReducerState<States> {
+ readonly phase: HandlerContext["phase"];
+ readonly resources: States;
+}
+
+/** A pure reducer over the events of a catalog stream. */
+export interface CatalogReducer<States> {
+ readonly initial: CatalogReducerState<States>;
+ reduce(
+ state: CatalogReducerState<States>,
+ event: CatalogEvent,
+ ): CatalogReducerState<States>;
+}
+
+/** Compose resources into a catalog reducer. The caller owns and updates state. */
+export function createCatalogReducer<States extends object>(resources: {
+ readonly [Name in keyof States]: CatalogResource<States[Name]>;
+}): CatalogReducer<States> {
+ const handlers = composeResources<States, CatalogResourceEvent>(resources);
+ const initial: CatalogReducerState<States> = {
+ phase: "snapshot",
+ resources: handlers.initial,
+ };
+ return {
+ initial,
+ reduce(state, event) {
+ if (event.event === "reset") {
+ return initial;
+ }
+ const next = handlers.reduce(state.resources, event, {
+ phase: state.phase,
+ });
+ const phase = event.event === "ready" ? "live" : state.phase;
+ return next === state.resources && phase === state.phase
+ ? state
+ : { phase, resources: next };
+ },
+ };
+}
diff --git a/packages/client/src/reducer.ts b/packages/client/src/reducers/notebook.ts
similarity index 60%
rename from packages/client/src/reducer.ts
rename to packages/client/src/reducers/notebook.ts
index b6d6fc04ef..1e82c5545f 100644
--- a/packages/client/src/reducer.ts
+++ b/packages/client/src/reducers/notebook.ts
@@ -1,9 +1,12 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import type * as Protocol from "./protocol.ts";
-
-/** A kind of object a notebook stream carries. */
-export type Kind = Exclude<Protocol.ObjectTypeOutput, "host" | "project">;
+import type * as Protocol from "../protocol.ts";
+import type { NotebookKind } from "../kinds.ts";
+import {
+ composeResources,
+ type EventResource,
+ type HandlerContext,
+} from "./resources.ts";
/**
* Events the reducer handles itself.
@@ -18,29 +21,11 @@ type ControlName = "reset" | "notebook" | "notebook.removed";
* Each kind contributes its record and removal events. `ready` marks the end
* of the snapshot and belongs to every kind.
*/
-export type ResourceEvent<K extends Kind = Kind> = Extract<
- Exclude<Protocol.EventOutput, { event: ControlName }>,
- { event: K | `${K}.removed` | "ready" }
->;
-
-/** What a handler may know about the stream beyond the event. */
-export interface HandlerContext {
- /** `snapshot` until `ready` arrives and `live` after it. */
- readonly phase: "snapshot" | "live";
-}
-
-/**
- * A pure handler for each event the resource reads.
- *
- * A handler returns `state` when the event does not apply to it.
- */
-type EventHandlers<State, K extends Kind> = {
- readonly [Name in ResourceEvent<K>["event"]]?: (
- state: State,
- event: Extract<ResourceEvent<K>, { event: Name }>,
- context: HandlerContext,
- ) => State;
-};
+export type NotebookResourceEvent<K extends NotebookKind = NotebookKind> =
+ Extract<
+ Exclude<Protocol.EventOutput, { event: ControlName }>,
+ { event: K | `${K}.removed` | "ready" }
+ >;
/**
* One kind of object assembled from its events.
@@ -48,13 +33,13 @@ type EventHandlers<State, K extends Kind> = {
* The reducer returns a resource to `initial` on `reset` and when the
* notebook is removed.
*/
-export interface Resource<State, K extends Kind = Kind> {
- readonly initial: State;
- readonly on: EventHandlers<State, K>;
-}
+export interface NotebookResource<
+ State,
+ K extends NotebookKind = NotebookKind,
+> extends EventResource<State, NotebookResourceEvent<K>> {}
/** The state of one notebook stream. */
-export interface ReducerState<States> {
+export interface NotebookReducerState<States> {
readonly phase: HandlerContext["phase"];
/**
* The notebook the stream describes.
@@ -69,22 +54,22 @@ export interface ReducerState<States> {
}
/** A pure reducer over the events of one notebook stream. */
-export interface Reducer<States> {
- readonly initial: ReducerState<States>;
+export interface NotebookReducer<States> {
+ readonly initial: NotebookReducerState<States>;
/**
* Apply one event.
*
* Throws on an object from another notebook.
*/
reduce(
- state: ReducerState<States>,
+ state: NotebookReducerState<States>,
event: Protocol.EventOutput,
- ): ReducerState<States>;
+ ): NotebookReducerState<States>;
}
/** A resource for each entry of a state map under the same name. */
type Resources<States> = {
- readonly [Name in keyof States]: Resource<States[Name]>;
+ readonly [Name in keyof States]: NotebookResource<States[Name]>;
};
/**
@@ -93,7 +78,7 @@ type Resources<States> = {
* Undefined for objects that do not name one.
*/
function notebookIdOf(
- event: ResourceEvent,
+ event: NotebookResourceEvent,
): Protocol.NotebookIdOutput | undefined {
switch (event.event) {
case "document":
@@ -114,14 +99,12 @@ function notebookIdOf(
}
/** Compose resources into one reducer over a notebook stream. */
-export function createReducer<States extends object>(
+export function createNotebookReducer<States extends object>(
resources: Resources<States>,
-): Reducer<States> {
- const names = Object.keys(resources) as (keyof States & string)[];
- const initialResources = Object.fromEntries(
- names.map((name) => [name, resources[name].initial]),
- ) as States;
- const initial: ReducerState<States> = {
+): NotebookReducer<States> {
+ const handlers = composeResources<States, NotebookResourceEvent>(resources);
+ const initialResources = handlers.initial;
+ const initial: NotebookReducerState<States> = {
phase: "snapshot",
notebookId: null,
notebook: null,
@@ -129,9 +112,9 @@ export function createReducer<States extends object>(
};
function identify(
- state: ReducerState<States>,
+ state: NotebookReducerState<States>,
notebookId: Protocol.NotebookIdOutput,
- ): ReducerState<States> {
+ ): NotebookReducerState<States> {
if (state.notebookId === notebookId) {
return state;
}
@@ -141,37 +124,21 @@ export function createReducer<States extends object>(
return { ...state, notebookId };
}
- function clear(state: ReducerState<States>): ReducerState<States> {
+ function clear(
+ state: NotebookReducerState<States>,
+ ): NotebookReducerState<States> {
return state.resources === initialResources && state.notebook === null
? state
: { ...state, notebook: null, resources: initialResources };
}
function fanOut(
- state: ReducerState<States>,
- event: ResourceEvent,
- ): ReducerState<States> {
- const context: HandlerContext = { phase: state.phase };
- let next = state.resources;
- for (const name of names) {
- type State = States[typeof name];
- // Handlers are keyed by the event name they accept.
- const handler = resources[name].on[event.event] as
- | ((
- state: State,
- event: ResourceEvent,
- context: HandlerContext,
- ) => State)
- | undefined;
- if (handler === undefined) {
- continue;
- }
- const before = next[name];
- const after = handler(before, event, context);
- if (after !== before) {
- next = { ...next, [name]: after };
- }
- }
+ state: NotebookReducerState<States>,
+ event: NotebookResourceEvent,
+ ): NotebookReducerState<States> {
+ const next = handlers.reduce(state.resources, event, {
+ phase: state.phase,
+ });
return next === state.resources ? state : { ...state, resources: next };
}
diff --git a/packages/client/src/reducers/resources.ts b/packages/client/src/reducers/resources.ts
new file mode 100644
index 0000000000..aca39d0166
--- /dev/null
+++ b/packages/client/src/reducers/resources.ts
@@ -0,0 +1,58 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+/** What a handler may know about the stream beyond the event. */
+export interface HandlerContext {
+ /** `snapshot` until `ready` arrives and `live` after it. */
+ readonly phase: "snapshot" | "live";
+}
+
+/** Pure handlers for a resource's events. */
+export interface EventResource<State, Event extends { event: string }> {
+ readonly initial: State;
+ readonly on: {
+ readonly [Name in Event["event"]]?: (
+ state: State,
+ event: Extract<Event, { event: Name }>,
+ context: HandlerContext,
+ ) => State;
+ };
+}
+
+/** Compose resource handlers without retaining their current state. */
+export function composeResources<
+ States extends object,
+ Event extends { event: string },
+>(resources: {
+ readonly [Name in keyof States]: EventResource<States[Name], Event>;
+}) {
+ const names = Object.keys(resources) as (keyof States & string)[];
+ const initial = Object.fromEntries(
+ names.map((name) => [name, resources[name].initial]),
+ ) as States;
+
+ return {
+ initial,
+ reduce(state: States, event: Event, context: HandlerContext): States {
+ let next = state;
+ for (const name of names) {
+ // The handler's key identifies the event it accepts.
+ const handler = resources[name].on[event.event as Event["event"]] as
+ | ((
+ state: States[typeof name],
+ event: Event,
+ context: HandlerContext,
+ ) => States[typeof name])
+ | undefined;
+ if (handler === undefined) {
+ continue;
+ }
+ const before = next[name];
+ const after = handler(before, event, context);
+ if (after !== before) {
+ next = { ...next, [name]: after };
+ }
+ }
+ return next;
+ },
+ };
+}
diff --git a/packages/client/src/request.ts b/packages/client/src/request.ts
index 9ae6d9ff1e..144b0aa364 100644
--- a/packages/client/src/request.ts
+++ b/packages/client/src/request.ts
@@ -146,7 +146,7 @@ export function below(url: URL, suffix: string): URL {
}
/** The URL an operation's path resolves to below the target. */
-function resolve<Prefix extends string>(
+export function resolve<Prefix extends string>(
target: Target<Prefix>,
path: string,
params: Readonly<Record<string, string>>,
diff --git a/packages/client/src/transport/events.ts b/packages/client/src/transport/events.ts
new file mode 100644
index 0000000000..f3873886ac
--- /dev/null
+++ b/packages/client/src/transport/events.ts
@@ -0,0 +1,275 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import type * as Protocol from "../protocol.ts";
+import type { Connection } from "../request.ts";
+import { type Transport, StreamStopped } from "./frame.ts";
+import { sse } from "./sse.ts";
+import {
+ type StreamEvent,
+ EventStream,
+ type EventStreamInit,
+ report,
+} from "./stream.ts";
+
+/** Attempts in a row without an event before the stream gives up. */
+const ATTEMPTS = 10;
+
+/** The delay before reconnecting, which grows with each attempt in a row. */
+function delay(attempt: number): number {
+ return Math.min(1000 * 1.3 ** attempt, 10_000);
+}
+
+/** Whether a stream is receiving events. */
+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> {
+ /** Aborting closes the stream. */
+ readonly signal?: AbortSignal;
+ /**
+ * Called when `status` changes.
+ *
+ * Reconnecting shows as `connecting` after `connected`.
+ */
+ readonly onStatus?: (status: Status) => void;
+}
+
+function sleep(ms: number, signal: AbortSignal): Promise<void> {
+ return new Promise((resolve) => {
+ const timer = setTimeout(done, ms);
+ signal.addEventListener("abort", done, { once: true });
+ function done() {
+ clearTimeout(timer);
+ signal.removeEventListener("abort", done);
+ resolve();
+ }
+ });
+}
+
+/**
+ * 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.
+ *
+ * - It starts with a snapshot that ends in `ready`, then delivers changes.
+ * - After a dropped connection it resumes from its cursor, backing off between
+ * attempts. It stops after ten attempts in a row without a message.
+ * - When it cannot resume, it delivers `reset` and a fresh snapshot follows.
+ * The caller discards what it built on `reset`.
+ */
+export class Events<
+ const K extends string = Protocol.ObjectTypeOutput,
+> implements AsyncIterable<StreamEvent<K>> {
+ /**
+ * Settles when the stream closes.
+ *
+ * Resolves after `close()` or an abort. Rejects with `StreamStopped` when
+ * the host refuses the stream, sends an invalid event, or cannot be reached.
+ */
+ public readonly closed: Promise<void>;
+ readonly #stream: EventStream<K>;
+ #status: Status = "connecting";
+ readonly #controller = new AbortController();
+ readonly #onStatus: ((status: Status) => void) | undefined;
+ #settle: { resolve(): void; reject(error: unknown): void } | undefined;
+ #release: (() => void) | undefined;
+
+ public constructor(
+ source: string | URL | Transport,
+ init: EventsInit<K>,
+ kinds: readonly string[],
+ ) {
+ let transport: Transport;
+ if (typeof source === "function") {
+ transport = source;
+ } else {
+ const url = new URL(source);
+ if (init.types !== undefined) {
+ url.searchParams.set("types", init.types.join(","));
+ }
+ transport = sse(url, init);
+ }
+ this.#stream = new EventStream<K>(
+ {
+ types: init.types,
+ cursor: init.cursor,
+ },
+ kinds,
+ );
+ this.#onStatus = init.onStatus;
+ this.closed = new Promise((resolve, reject) => {
+ this.#settle = { resolve, reject };
+ });
+ // A caller that never awaits `closed` should not see an unhandled rejection.
+ this.closed.catch(() => undefined);
+ if (init.signal?.aborted) {
+ this.close();
+ return;
+ }
+ const signal = init.signal;
+ if (signal !== undefined) {
+ const abort = () => this.close();
+ signal.addEventListener("abort", abort, { once: true });
+ this.#release = () => signal.removeEventListener("abort", abort);
+ }
+ void this.#run(transport);
+ }
+
+ /** Whether the stream is receiving events. */
+ public get status(): Status {
+ return this.#status;
+ }
+
+ /**
+ * The id of the last event the stream received.
+ *
+ * Null during a snapshot and after `reset`.
+ */
+ public get cursor(): string | null {
+ return this.#stream.cursor;
+ }
+
+ /**
+ * Call `listener` with each event, in order.
+ *
+ * Returns a function that stops calling it. A listener that throws does not
+ * interrupt the stream.
+ */
+ public subscribe(listener: (event: StreamEvent<K>) => void): () => void {
+ return this.#stream.subscribe(listener);
+ }
+
+ /** Stop following the stream. */
+ public close(): void {
+ this.#finish()?.resolve();
+ }
+
+ /**
+ * Iterate over events until the stream closes.
+ *
+ * Leaving the loop early closes the stream.
+ */
+ public [Symbol.asyncIterator](): AsyncIterator<StreamEvent<K>> {
+ const queue: StreamEvent<K>[] = [];
+ const waiting: (() => void)[] = [];
+ const wake = () => waiting.splice(0).forEach((resolve) => resolve());
+ let ended: { error?: unknown } | undefined;
+ const unsubscribe = this.subscribe((event) => {
+ queue.push(event);
+ wake();
+ });
+ this.closed.then(
+ () => {
+ ended = {};
+ wake();
+ },
+ (error: unknown) => {
+ ended = { error };
+ wake();
+ },
+ );
+ const done = () => {
+ unsubscribe();
+ this.close();
+ return { done: true as const, value: undefined };
+ };
+ return {
+ next: async () => {
+ for (;;) {
+ const event = queue.shift();
+ if (event !== undefined) {
+ return { done: false, value: event };
+ }
+ if (ended !== undefined) {
+ if (ended.error !== undefined) {
+ unsubscribe();
+ throw ended.error;
+ }
+ return done();
+ }
+ // Wait for the next event or for the stream to close.
+ await new Promise<void>((resolve) => waiting.push(resolve));
+ }
+ },
+ return: async () => done(),
+ };
+ }
+
+ async #run(transport: Transport) {
+ // Start after the constructor returns, so listeners added right after it
+ // receive the first events.
+ await Promise.resolve();
+ const { signal } = this.#controller;
+ let attempt = 0;
+ while (!signal.aborted) {
+ try {
+ const cursor = this.#stream.resume();
+ await transport(
+ { cursor, signal },
+ {
+ open: () => {
+ if (this.#settle !== undefined) {
+ this.#setStatus("connected");
+ }
+ },
+ message: (message) => {
+ if (this.#settle === undefined) {
+ return;
+ }
+ attempt = 0;
+ try {
+ this.#stream.receive(message);
+ } catch (error) {
+ // The transport may call this from its own event listener,
+ // so stop here instead of relying on it to pass the error on.
+ this.#finish()?.reject(error);
+ }
+ },
+ },
+ );
+ } catch (error) {
+ this.#finish()?.reject(error);
+ return;
+ }
+ if (signal.aborted) {
+ return;
+ }
+ this.#setStatus("connecting");
+ attempt += 1;
+ if (attempt > ATTEMPTS) {
+ this.#finish()?.reject(
+ new StreamStopped("The host could not be reached"),
+ );
+ return;
+ }
+ await sleep(delay(attempt), signal);
+ }
+ }
+
+ #setStatus(status: Status) {
+ if (this.#status === status) {
+ return;
+ }
+ this.#status = status;
+ try {
+ this.#onStatus?.(status);
+ } catch (error) {
+ report(error);
+ }
+ }
+
+ /** Close the stream once and return how to settle `closed`. */
+ #finish() {
+ const settle = this.#settle;
+ if (settle === undefined) {
+ return undefined;
+ }
+ this.#settle = undefined;
+ this.#release?.();
+ this.#controller.abort();
+ this.#setStatus("closed");
+ return settle;
+ }
+}
diff --git a/packages/client/src/transport/frame.ts b/packages/client/src/transport/frame.ts
index 2e8ee8c230..0144db5d4b 100644
--- a/packages/client/src/transport/frame.ts
+++ b/packages/client/src/transport/frame.ts
@@ -35,7 +35,7 @@ export class StreamStopped extends Error {
public override readonly name = "StreamStopped";
}
-/** Where one connection of a notebook stream starts. */
+/** Where one connection of a host stream starts. */
export interface Attempt {
/** Where to resume, or null to start with a snapshot. */
readonly cursor: string | null;
@@ -52,16 +52,16 @@ export interface Handlers {
}
/**
- * Open one connection to a notebook stream and report it until it ends.
+ * Open one connection to a host stream and report it until it ends.
*
- * `NotebookEvents` calls it again for each attempt. It resolves when the
+ * The event stream calls it again for each attempt. It resolves when the
* connection ended and another attempt makes sense. It rejects when the
* stream should stop, preferably with a `StreamStopped` that says why, and
* `closed` rejects with the same error. It sends the cursor however its host
* expects, and leaves reconnecting, validation, and the cursor's value to
- * `NotebookEvents`.
+ * the event stream.
*/
-export type NotebookTransport = (
- attempt: Attempt,
- handlers: Handlers,
-) => Promise<void>;
+export type Transport = (attempt: Attempt, handlers: Handlers) => Promise<void>;
+
+/** A custom transport for a notebook stream. */
+export type NotebookTransport = Transport;
diff --git a/packages/client/src/transport/sse.ts b/packages/client/src/transport/sse.ts
index 35ec6ce9e5..92be9b1c9c 100644
--- a/packages/client/src/transport/sse.ts
+++ b/packages/client/src/transport/sse.ts
@@ -2,7 +2,7 @@
import * as Protocol from "../protocol.ts";
import { type Connection, isType } from "../request.ts";
-import { type Frame, type NotebookTransport, StreamStopped } from "./frame.ts";
+import { type Frame, type Transport, StreamStopped } from "./frame.ts";
/** Hosts send a comment every fifteen seconds while nothing else happens. */
const SILENCE_MS = 45_000;
@@ -81,7 +81,7 @@ const RETRY_STATUSES = new Set([408, 429]);
* `Problem`, except for statuses that ask the client to try again. Other
* failures and 45 seconds of silence are retried.
*/
-export function sse(url: URL, connection: Connection): NotebookTransport {
+export function sse(url: URL, connection: Connection): Transport {
return async ({ cursor, signal }, { open, message }) => {
const headers = new Headers(connection.headers);
headers.set("Accept", "text/event-stream");
diff --git a/packages/client/src/notebook/stream.ts b/packages/client/src/transport/stream.ts
similarity index 76%
rename from packages/client/src/notebook/stream.ts
rename to packages/client/src/transport/stream.ts
index 15860d508e..e472105fc2 100644
--- a/packages/client/src/notebook/stream.ts
+++ b/packages/client/src/transport/stream.ts
@@ -1,8 +1,7 @@
/* Copyright 2026 Marimo. All rights reserved. */
import * as Protocol from "../protocol.ts";
-import type { Kind } from "../reducer.ts";
-import { type Frame, isFrame, StreamStopped } from "../transport/frame.ts";
+import { type Frame, isFrame, 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
@@ -10,25 +9,25 @@ type ExtensionEvent<Name extends string> = Name extends unknown
: never;
/**
- * An event a notebook stream delivers for the requested kinds.
+ * An event a host stream delivers for the requested kinds.
*
* Each kind brings its record and removal events. `ready` and `reset` arrive
* for every stream. A kind the protocol does not define arrives with its data
* unvalidated.
*/
-export type NotebookEvent<K extends string = Kind> =
+export type StreamEvent<K extends string = Protocol.ObjectTypeOutput> =
| Extract<
Protocol.EventOutput,
{ event: K | `${K}.removed` | "ready" | "reset" }
>
| ExtensionEvent<Exclude<K, Protocol.ObjectTypeOutput>>;
-/** What a `NotebookStream` delivers and where it starts. */
-export interface NotebookStreamInit<K extends string = Kind> {
+/** What an `EventStream` delivers and where it starts. */
+export interface EventStreamInit<K extends string = Protocol.ObjectTypeOutput> {
/**
* The kinds to deliver.
*
- * Omit it to deliver every kind the protocol defines. Name a kind the
+ * Omit it to deliver every kind this stream carries. Name a kind the
* protocol does not define, such as `marimo`, to deliver it as well.
*/
readonly types?: readonly K[];
@@ -36,6 +35,7 @@ export interface NotebookStreamInit<K extends string = Kind> {
* Resume after this event id instead of starting with a snapshot.
*
* The caller holds the state it built through that id.
+ * Use the same host, stream, and type filter that produced that state.
*/
readonly cursor?: string;
}
@@ -53,7 +53,7 @@ export function report(error: unknown): void {
}
/**
- * The protocol's rules for following a notebook stream, without a connection.
+ * The protocol's rules for following a host stream, without a connection.
*
* A connection calls `resume()` when it starts, to learn the cursor to send,
* and `receive()` with each message. The stream validates events, tracks the
@@ -67,23 +67,23 @@ export function report(error: unknown): void {
* - Kinds that were not requested keep their place in the stream without
* being delivered.
*/
-export class NotebookStream<const K extends string = Kind> {
+export class EventStream<const K extends string = Protocol.ObjectTypeOutput> {
#cursor: string | null;
/** Whether events since the last reset have no cursor to resume from. */
#rebuilding = false;
- readonly #wanted: ReadonlySet<string> | null;
- readonly #listeners = new Set<(event: NotebookEvent<K>) => void>();
+ readonly #wanted: ReadonlySet<string>;
+ readonly #listeners = new Set<(event: StreamEvent<K>) => void>();
- public constructor(init: NotebookStreamInit<K> = {}) {
+ public constructor(init: EventStreamInit<K>, kinds: readonly string[]) {
this.#cursor = init.cursor ?? null;
- this.#wanted =
- init.types === undefined
- ? null
- : new Set([
- "ready",
- "reset",
- ...init.types.flatMap((kind) => [kind, `${kind}.removed`]),
- ]);
+ this.#wanted = new Set([
+ "ready",
+ "reset",
+ ...(init.types ?? kinds).flatMap((kind) => {
+ const removed = `${kind}.removed`;
+ return PROTOCOL_EVENTS.has(removed) ? [kind, removed] : [kind];
+ }),
+ ]);
}
/**
@@ -101,7 +101,7 @@ export class NotebookStream<const K extends string = Kind> {
* Returns a function that stops calling it. A listener that throws does not
* interrupt the stream.
*/
- public subscribe(listener: (event: NotebookEvent<K>) => void): () => void {
+ public subscribe(listener: (event: StreamEvent<K>) => void): () => void {
this.#listeners.add(listener);
return () => this.#listeners.delete(listener);
}
@@ -132,7 +132,7 @@ export class NotebookStream<const K extends string = Kind> {
}
#accept(frame: Frame) {
- let event: NotebookEvent<string>;
+ let event: StreamEvent<string>;
if (PROTOCOL_EVENTS.has(frame.event)) {
const parsed = Protocol.Event.safeParse(frame);
if (!parsed.success) {
@@ -154,16 +154,12 @@ export class NotebookStream<const K extends string = Kind> {
} else if (this.#cursor === null) {
this.#rebuilding = true;
}
- const wanted =
- this.#wanted === null
- ? PROTOCOL_EVENTS.has(event.event)
- : this.#wanted.has(event.event);
- if (!wanted) {
+ if (!this.#wanted.has(event.event)) {
return;
}
for (const listener of this.#listeners) {
try {
- listener(event as NotebookEvent<K>);
+ listener(event as StreamEvent<K>);
} catch (error) {
report(error);
}