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.

Read attachments from the host stream (#11351)

Trevor Manzf96702e7b534
diff --git a/frontend/src/components/editor/chrome/wrapper/__tests__/attachment-status.test.tsx b/frontend/src/components/editor/chrome/wrapper/__tests__/attachment-status.test.tsx
index 5fffb274ff..898e8b77d1 100644
--- a/frontend/src/components/editor/chrome/wrapper/__tests__/attachment-status.test.tsx
+++ b/frontend/src/components/editor/chrome/wrapper/__tests__/attachment-status.test.tsx
@@ -8,13 +8,13 @@ import {
screen,
waitFor,
} from "@testing-library/react";
-import { createStore, Provider } from "jotai";
+import { atom, createStore, Provider } from "jotai";
import { userEvent } from "storybook/test";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { PAIR_CONFIG } from "@/__tests__/fixtures/pair-config";
import { TooltipProvider } from "@/components/ui/tooltip";
import { toast } from "@/components/ui/use-toast";
-import { type Attachment, attachmentsAtom } from "@/core/attachments/state";
+import type { Attachment } from "@/core/attachments/state";
import { pairConfigAtom } from "@/core/config/pair";
import {
type StableSessionId,
@@ -22,13 +22,16 @@ import {
} from "@/core/kernel/session";
import { API } from "@/core/network/api";
import { connectionAtom } from "@/core/network/connection";
-import { WebSocketClosedReason, ConnectionState } from "@/core/websocket/types";
+import { notebookClientAtom } from "@/core/websocket/state";
+import { ConnectionState } from "@/core/websocket/types";
import { Deferred } from "@/utils/Deferred";
import { AttachmentStatus } from "../footer-items/attachment-status";
vi.mock("@/components/ui/use-toast", () => ({ toast: vi.fn() }));
vi.mock("@/core/network/api", () => ({ API: { post: vi.fn() } }));
+const attachmentsAtom = atom<Attachment[]>([]);
+
const AGENT: Attachment = {
id: "a1",
kind: "agent",
@@ -41,6 +44,12 @@ function renderStatus(attachments: Attachment[] = [AGENT], preview = true) {
const store = createStore();
store.set(connectionAtom, { state: ConnectionState.OPEN });
store.set(pairConfigAtom, { ...PAIR_CONFIG, hostEnabled: preview });
+ store.set(notebookClientAtom, {
+ connectionAtom: atom({ state: ConnectionState.OPEN }),
+ documentAtom: atom(null),
+ attachmentsAtom,
+ reconnect: async () => undefined,
+ });
store.set(attachmentsAtom, attachments);
store.set(stableSessionIdAtom, "stable/test" as StableSessionId);
return {
@@ -342,21 +351,6 @@ describe("AttachmentStatus", () => {
).toBeDisabled();
});
- it.each([
- { state: ConnectionState.CONNECTING },
- { state: ConnectionState.CLOSING },
- { state: ConnectionState.NOT_STARTED },
- {
- state: ConnectionState.CLOSED,
- code: WebSocketClosedReason.KERNEL_DISCONNECTED,
- reason: "offline",
- },
- ])("hides connected claims while the browser is %j", (connection) => {
- const { store, container } = renderStatus();
- act(() => store.set(connectionAtom, connection));
- expect(container).toBeEmptyDOMElement();
- });
-
it("removes detached agents when the list is replaced", () => {
const { store, container } = renderStatus([
AGENT,
diff --git a/frontend/src/components/editor/errors/__tests__/send-error-report-button.test.tsx b/frontend/src/components/editor/errors/__tests__/send-error-report-button.test.tsx
index 8f7bd0d0f1..8404d1350b 100644
--- a/frontend/src/components/editor/errors/__tests__/send-error-report-button.test.tsx
+++ b/frontend/src/components/editor/errors/__tests__/send-error-report-button.test.tsx
@@ -8,7 +8,7 @@ import {
screen,
waitFor,
} from "@testing-library/react";
-import { createStore, Provider, useAtomValue } from "jotai";
+import { atom, createStore, Provider, useAtomValue } from "jotai";
import type React from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { MockNotebook } from "@/__mocks__/notebook";
@@ -16,7 +16,7 @@ import { cellId } from "@/__tests__/branded";
import { PAIR_CONFIG } from "@/__tests__/fixtures/pair-config";
import { TooltipProvider } from "@/components/ui/tooltip";
import { toast } from "@/components/ui/use-toast";
-import { type Attachment, attachmentsAtom } from "@/core/attachments/state";
+import type { Attachment } from "@/core/attachments/state";
import { exportedForTesting, notebookAtom } from "@/core/cells/cells";
import {
type CellOutputMessage,
@@ -32,7 +32,8 @@ import {
} from "@/core/kernel/session";
import { API } from "@/core/network/api";
import { connectionAtom } from "@/core/network/connection";
-import { WebSocketClosedReason, ConnectionState } from "@/core/websocket/types";
+import { notebookClientAtom } from "@/core/websocket/state";
+import { ConnectionState } from "@/core/websocket/types";
import { Deferred } from "@/utils/Deferred";
import { HTTPError } from "@/utils/errors";
import { MarimoErrorOutput } from "../../output/MarimoErrorOutput";
@@ -48,6 +49,8 @@ vi.mock("@/components/editor/chrome/wrapper/useOpenAiAssistant", () => ({
const CELL_ID = cellId("test-cell");
const STABLE_ID = "stable/test" as StableSessionId;
+const attachmentsAtom = atom<Attachment[]>([]);
+
const AGENT: Attachment = {
id: "a1",
kind: "agent",
@@ -93,6 +96,12 @@ function renderButton({
const store = createStore();
store.set(connectionAtom, { state: ConnectionState.OPEN });
store.set(pairConfigAtom, { ...PAIR_CONFIG, hostEnabled: preview });
+ store.set(notebookClientAtom, {
+ connectionAtom: atom({ state: ConnectionState.OPEN }),
+ documentAtom: atom(null),
+ attachmentsAtom,
+ reconnect: async () => undefined,
+ });
store.set(attachmentsAtom, attachments);
store.set(stableSessionIdAtom, stableId);
const wrapper = ({ children }: { children: React.ReactNode }) => (
@@ -177,26 +186,6 @@ describe("SendErrorReportButton", () => {
expect(screen.getByRole("button")).toBeDisabled();
});
- it.each([
- { state: ConnectionState.CONNECTING },
- { state: ConnectionState.CLOSING },
- { state: ConnectionState.NOT_STARTED },
- {
- state: ConnectionState.CLOSED,
- code: WebSocketClosedReason.KERNEL_DISCONNECTED,
- reason: "offline",
- },
- ])(
- "does not send from a stale snapshot while the browser is %j",
- (connection) => {
- const { store } = renderButton();
- act(() => store.set(connectionAtom, connection));
- expect(screen.getByRole("button")).toBeDisabled();
- send();
- expect(API.post).not.toHaveBeenCalled();
- },
- );
-
it.each([
[new HTTPError(409, "Conflict"), "No agent attached"],
[new HTTPError(500, "Server error"), "Could not send error"],
diff --git a/frontend/src/core/attachments/state.ts b/frontend/src/core/attachments/state.ts
index 43902402b0..84e1e86aba 100644
--- a/frontend/src/core/attachments/state.ts
+++ b/frontend/src/core/attachments/state.ts
@@ -1,17 +1,14 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import type { components } from "@marimo-team/marimo-api";
import { atom } from "jotai";
-import { isConnectedAtom } from "@/core/network/connection";
+import type { Attachment } from "@/core/host/protocol";
+import { notebookClientAtom } from "@/core/websocket/state";
-export type Attachment = components["schemas"]["Attachment"];
+export type { Attachment } from "@/core/host/protocol";
-export const attachmentsAtom = atom<Attachment[]>([]);
export const agentAttachmentsAtom = atom((get) => {
- if (!get(isConnectedAtom)) {
- return [];
- }
- return get(attachmentsAtom).filter(
+ const notebook = get(notebookClientAtom);
+ return (notebook ? get(notebook.attachmentsAtom) : []).filter(
(attachment) => attachment.kind === "agent",
);
});
diff --git a/frontend/src/core/host/__tests__/attachments.test.ts b/frontend/src/core/host/__tests__/attachments.test.ts
new file mode 100644
index 0000000000..127a2743d5
--- /dev/null
+++ b/frontend/src/core/host/__tests__/attachments.test.ts
@@ -0,0 +1,57 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { describe, expect, it } from "vitest";
+import { attachments } from "../resources/attachments";
+import { createStream } from "../stream";
+import { fixtureEvents } from "./fixtures";
+
+const stream = createStream({ attachments });
+const snapshot = fixtureEvents("notebook-events.sse");
+const records = snapshot.flatMap((event) =>
+ event.event === "attachment" ? [event.data.attachment] : [],
+);
+const confirmed = () => snapshot.reduce(stream.reduce, stream.initial);
+
+describe("attachment resource", () => {
+ it("collects snapshot records, replaces by id, and removes attachments", () => {
+ const state = confirmed();
+ expect(state.resources.attachments).toEqual(records);
+ const [browser, agent] = records;
+ const renamed = { ...agent, name: "Renamed agent" };
+ const updated = stream.reduce(state, {
+ event: "attachment",
+ id: "98",
+ data: { attachment: renamed },
+ });
+ expect(updated.resources.attachments).toEqual([browser, renamed]);
+ expect(state.resources.attachments).toEqual(records);
+
+ const removed = stream.reduce(updated, {
+ event: "attachment.removed",
+ id: "99",
+ data: { id: browser.id, time: "2026-10-01T09:30:00Z" },
+ });
+ expect(removed.resources.attachments).toEqual([renamed]);
+ const repeated = stream.reduce(removed, {
+ event: "attachment.removed",
+ id: "100",
+ data: { id: browser.id, time: "2026-10-01T09:30:00Z" },
+ });
+ expect(repeated.resources.attachments).toBe(removed.resources.attachments);
+ });
+
+ it("retains records for replay and rebuilds them after reset", () => {
+ const state = confirmed();
+ expect(stream.resume(state)).toBe(state);
+ const reset = stream.reduce(state, { event: "reset", data: {} });
+ expect(reset.resources.attachments).toEqual([]);
+ const replacement = snapshot
+ .filter(
+ (event) =>
+ event.event !== "attachment" ||
+ event.data.attachment.id === records[0].id,
+ )
+ .reduce(stream.reduce, reset);
+ expect(replacement.resources.attachments).toEqual([records[0]]);
+ });
+});
diff --git a/frontend/src/core/host/__tests__/notebook-client.test.ts b/frontend/src/core/host/__tests__/notebook-client.test.ts
index 68bbaf9153..6ae20a2b57 100644
--- a/frontend/src/core/host/__tests__/notebook-client.test.ts
+++ b/frontend/src/core/host/__tests__/notebook-client.test.ts
@@ -8,7 +8,7 @@ import { Deferred } from "@/utils/Deferred";
import { jsonParseWithSpecialChar } from "@/utils/json/json-parser";
import { classifyCloseEvent } from "../../websocket/connection-state";
import { createNotebookClient } from "../notebook-client";
-import { fixtureMessages } from "./fixtures";
+import { fixtureEvents, fixtureMessages } from "./fixtures";
function notebookMessage(id: string) {
const notebook = {
@@ -301,3 +301,133 @@ describe("NotebookClient lifetime", () => {
second.abort();
});
});
+
+async function open() {
+ const url = vi.fn(() => "ws://localhost/ws?session_id=first&cursor=999");
+ const setupResult = setup(url);
+ const lifetime = new AbortController();
+ setupResult.connect(lifetime.signal);
+ setupResult.healthy.resolve();
+ await setupResult.healthy.promise;
+ setupResult.events.dispatchEvent(new Event("open"));
+ return { ...setupResult, lifetime, url };
+}
+
+describe("NotebookClient attachments", () => {
+ const [browser, agent] = fixtureEvents("notebook-events.sse").flatMap(
+ (event) => (event.event === "attachment" ? [event.data.attachment] : []),
+ );
+
+ it("publishes a complete snapshot and applies live changes independently of kernel readiness", async () => {
+ const { client, store, receive, lifetime } = await open();
+ const snapshot = fixtureMessages("notebook-events.sse");
+ const readyIndex = snapshot.findIndex((event) => event.event === "ready");
+ snapshot.slice(0, readyIndex).forEach(receive);
+ expect(store.get(client.attachmentsAtom)).toEqual([]);
+ snapshot.slice(readyIndex).forEach(receive);
+ expect(store.get(client.attachmentsAtom)).toEqual([browser, agent]);
+ const renamed = { ...agent, name: "Renamed agent" };
+ receive({ event: "attachment", id: "98", data: { attachment: renamed } });
+ receive({
+ event: "attachment.removed",
+ id: "99",
+ data: { id: browser.id },
+ });
+ expect(store.get(client.attachmentsAtom)).toEqual([renamed]);
+ receive({ data: { op: "kernel-ready", resumed: false } });
+ expect(store.get(client.attachmentsAtom)).toEqual([renamed]);
+ receive({ event: "attachment.removed", id: "100", data: { id: agent.id } });
+ expect(store.get(client.attachmentsAtom)).toEqual([]);
+ lifetime.abort();
+ });
+
+ it("resumes attachments alongside an incomplete document and waits for replay ready", async () => {
+ const { client, store, receive, events, urls, lifetime } = await open();
+ expect(urls[0].searchParams.has("cursor")).toBe(false);
+ fixtureMessages("notebook-events.sse").forEach(receive);
+ const confirmed = store.get(client.documentAtom);
+ const edits = fixtureMessages("edits.sse");
+ edits.slice(0, 3).forEach(receive);
+ const renamed = { ...agent, name: "Renamed agent" };
+ receive({ event: "attachment", id: "112a", data: { attachment: renamed } });
+ expect(store.get(client.attachmentsAtom)).toEqual([browser, renamed]);
+ events.dispatchEvent(new CloseEvent("close"));
+ expect(store.get(client.attachmentsAtom)).toEqual([]);
+ expect(urls.at(-1)!.searchParams.get("cursor")).toBe("112a");
+ events.dispatchEvent(new Event("open"));
+ expect(store.get(client.attachmentsAtom)).toEqual([]);
+ expect(store.get(client.documentAtom)).toBe(confirmed);
+ edits.slice(3).forEach(receive);
+ receive({
+ event: "attachment.removed",
+ id: "115",
+ data: { id: browser.id },
+ });
+ expect(store.get(client.attachmentsAtom)).toEqual([]);
+ receive({ event: "ready", id: "116", data: {} });
+ expect(store.get(client.attachmentsAtom)).toEqual([renamed]);
+ const revisions = fixtureEvents("edits.sse").flatMap((event) =>
+ event.event === "document" ? [event.data.document] : [],
+ );
+ expect(store.get(client.documentAtom)?.revision).toEqual(revisions.at(-1));
+ lifetime.abort();
+ });
+
+ it("replaces stale attachments with an empty snapshot after reset", async () => {
+ const { client, store, receive, lifetime } = await open();
+ fixtureMessages("notebook-events.sse").forEach(receive);
+ receive({ event: "reset", data: {} });
+ expect(store.get(client.attachmentsAtom)).toEqual([]);
+ fixtureMessages("notebook-events.sse")
+ .filter((event) => event.event !== "attachment")
+ .forEach(receive);
+ expect(store.get(client.attachmentsAtom)).toEqual([]);
+ lifetime.abort();
+ });
+
+ it.each(["close", "error", "malformed", "removed", "abort", "identity"])(
+ "clears presence on %s and ignores messages after disposal",
+ async (reason) => {
+ const { client, store, receive, events, url, lifetime } = await open();
+ fixtureMessages("notebook-events.sse").forEach(receive);
+ expect(store.get(client.attachmentsAtom)).toEqual([browser, agent]);
+ switch (reason) {
+ case "close":
+ events.dispatchEvent(
+ new CloseEvent("close", { reason: "MARIMO_UNAUTHORIZED" }),
+ );
+ break;
+ case "error":
+ events.dispatchEvent(new Event("error"));
+ break;
+ case "malformed":
+ receive({ event: "attachment", id: "98", data: {} });
+ break;
+ case "removed":
+ receive({ event: "notebook.removed", id: "98", data: { id: "n1" } });
+ break;
+ case "identity":
+ url.mockReturnValue(
+ "ws://localhost/api/marimo/v1/notebooks/n2/events/ws",
+ );
+ events.dispatchEvent(new CloseEvent("close"));
+ receive({ event: "ready", id: "98", data: {} });
+ break;
+ default:
+ lifetime.abort();
+ }
+ expect(store.get(client.attachmentsAtom)).toEqual([]);
+ lifetime.abort();
+ fixtureMessages("notebook-events.sse").forEach(receive);
+ expect(store.get(client.attachmentsAtom)).toEqual([]);
+ },
+ );
+
+ it("keeps legacy sessions empty", async () => {
+ const { client, store, receive, lifetime } = await open();
+ receive({ data: { op: "kernel-ready" } });
+ receive({ data: { op: "reconnected" } });
+ expect(store.get(client.attachmentsAtom)).toEqual([]);
+ lifetime.abort();
+ });
+});
diff --git a/frontend/src/core/host/events.ts b/frontend/src/core/host/events.ts
index 50817ee107..bf9c814e05 100644
--- a/frontend/src/core/host/events.ts
+++ b/frontend/src/core/host/events.ts
@@ -15,6 +15,7 @@ export const NOTEBOOK_EVENT_TYPES = [
"notebook",
"document",
"cell",
+ "attachment",
"marimo",
] as const satisfies readonly (Protocol.ObjectType | "marimo")[];
diff --git a/frontend/src/core/host/notebook-client.ts b/frontend/src/core/host/notebook-client.ts
index 51fbe73eee..6d0eec7ac0 100644
--- a/frontend/src/core/host/notebook-client.ts
+++ b/frontend/src/core/host/notebook-client.ts
@@ -11,6 +11,8 @@ import {
TransportReadyState,
} from "./connection";
import { parseNotebookEvent } from "./events";
+import type { Attachment } from "./protocol";
+import { attachments } from "./resources/attachments";
import { type Document, document } from "./resources/document";
import { createStream } from "./stream";
@@ -26,6 +28,8 @@ export interface NotebookClient {
* retains the last document. Partial updates are not exposed.
*/
readonly documentAtom: Atom<Document | null>;
+ /** Live attachments, empty until the stream is ready or while disconnected. */
+ readonly attachmentsAtom: Atom<readonly Attachment[]>;
/** Attempt to restore a closed connection after checking host health. */
reconnect(): Promise<void>;
}
@@ -60,15 +64,23 @@ export function createNotebookClient(store: ReturnType<typeof createStore>) {
state: ConnectionState.NOT_STARTED,
});
// One atom holds the whole stream, which resource atoms derive from.
- const stream = createStream({ document });
+ const stream = createStream({ document, attachments });
const streamAtom = atom(stream.initial);
+ // A resumed stream is live, but presence waits for this connection's ready.
+ const readyAtom = atom(false);
const documentAtom = atom(
(get) => get(streamAtom).resources.document.current,
);
+ const attachmentsAtom = atom((get) =>
+ get(readyAtom) && get(connectionAtom).state === ConnectionState.OPEN
+ ? get(streamAtom).resources.attachments
+ : attachments.initial,
+ );
let reconnect: (() => Promise<void>) | undefined;
const client: NotebookClient = {
connectionAtom,
documentAtom,
+ attachmentsAtom,
reconnect: async () => reconnect?.(),
};
@@ -111,14 +123,17 @@ export function createNotebookClient(store: ReturnType<typeof createStore>) {
? stream.resume(store.get(streamAtom))
: stream.initial;
streamKey = key;
+ store.set(readyAtom, false);
store.set(streamAtom, state);
if (state.cursor !== null) {
next.searchParams.set("cursor", state.cursor);
}
return next.toString();
});
- const setStatus = (status: ConnectionStatus) =>
+ const setStatus = (status: ConnectionStatus) => {
+ store.set(readyAtom, false);
store.set(connectionAtom, status);
+ };
const disconnected = {
state: ConnectionState.CLOSED,
code: ConnectionClosedReason.KERNEL_DISCONNECTED,
@@ -174,6 +189,9 @@ export function createNotebookClient(store: ReturnType<typeof createStore>) {
try {
event = parseNotebookEvent(decodeJson(message.data));
store.set(streamAtom, stream.reduce(store.get(streamAtom), event));
+ if (event.event === "ready" || event.event === "reset") {
+ store.set(readyAtom, event.event === "ready");
+ }
} catch (error) {
Logger.error("Failed to decode notebook message", error);
if (messageFormat === "session") {
diff --git a/frontend/src/core/host/resources/attachments.ts b/frontend/src/core/host/resources/attachments.ts
new file mode 100644
index 0000000000..3fec205768
--- /dev/null
+++ b/frontend/src/core/host/resources/attachments.ts
@@ -0,0 +1,19 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import type { Attachment } from "../protocol";
+import type { Resource } from "./resource";
+
+/** Attachment records retained with the stream's resume cursor. */
+export const attachments: Resource<readonly Attachment[]> = {
+ initial: [],
+ on: {
+ attachment: (state, { data: { attachment } }) =>
+ state.some((item) => item.id === attachment.id)
+ ? state.map((item) => (item.id === attachment.id ? attachment : item))
+ : [...state, attachment],
+ "attachment.removed": (state, { data }) =>
+ state.some((item) => item.id === data.id)
+ ? state.filter((item) => item.id !== data.id)
+ : state,
+ },
+};
diff --git a/frontend/src/core/islands/__tests__/bootstrap.test.ts b/frontend/src/core/islands/__tests__/bootstrap.test.ts
index 9dd765f891..fb21cf3f2f 100644
--- a/frontend/src/core/islands/__tests__/bootstrap.test.ts
+++ b/frontend/src/core/islands/__tests__/bootstrap.test.ts
@@ -3,8 +3,6 @@
import { createStore } from "jotai";
import { afterEach, describe, expect, it, vi } from "vitest";
import { RuntimeState } from "@/core/kernel/RuntimeState";
-import { attachmentsAtom } from "@/core/attachments/state";
-import { Logger } from "@/utils/Logger";
import { initializeIslands } from "../bootstrap";
import type { IslandsPyodideBridge } from "../bridge";
import { islandsHydratedAtom, islandsPendingInitialRunsAtom } from "../state";
@@ -50,30 +48,6 @@ describe("initializeIslands", () => {
expect(store.get(islandsHydratedAtom)).toBe(false);
store.set(islandsPendingInitialRunsAtom, new Set([1, 2]));
- const errors = vi.spyOn(Logger, "error");
- consumeMessage?.({
- sessionGeneration: 1,
- message: JSON.stringify({
- op: "attachments",
- data: {
- op: "attachments",
- attachments: [
- {
- id: "a1",
- kind: "agent",
- name: "Pi",
- since: "2026-10-14T00:00:00Z",
- notebook_id: "nb-test",
- identity: "pi-thread",
- },
- ],
- },
- }) as IslandsKernelMessage["message"],
- });
- expect(errors).not.toHaveBeenCalled();
- expect(store.get(attachmentsAtom)).toEqual([]);
- expect(store.get(islandsPendingInitialRunsAtom)).toEqual(new Set([1, 2]));
-
consumeMessage?.(completedRun(1));
expect(store.get(islandsHydratedAtom)).toBe(false);
diff --git a/frontend/src/core/islands/bootstrap.ts b/frontend/src/core/islands/bootstrap.ts
index 5b0fd1e801..0267d9c9f5 100644
--- a/frontend/src/core/islands/bootstrap.ts
+++ b/frontend/src/core/islands/bootstrap.ts
@@ -209,7 +209,6 @@ function handleMessage(
case "cache-info":
case "kernel-startup-error":
case "notebook-document-transaction":
- case "attachments":
return;
case "completed-run":
diff --git a/frontend/src/core/runtime/__tests__/runtime.test.ts b/frontend/src/core/runtime/__tests__/runtime.test.ts
index 0854a5fd6d..0ca285380c 100644
--- a/frontend/src/core/runtime/__tests__/runtime.test.ts
+++ b/frontend/src/core/runtime/__tests__/runtime.test.ts
@@ -78,7 +78,7 @@ describe("RuntimeManager", () => {
"wss://example.com/nested/api/marimo/v1/notebooks/nb_123/events/ws",
params: {
file: "notebook.py",
- types: "marimo",
+ types: "notebook,document,cell,attachment,marimo",
session_id: sessionId,
access_token: "test-token",
},
diff --git a/frontend/src/core/runtime/runtime.ts b/frontend/src/core/runtime/runtime.ts
index 5edc973139..12d24db6f6 100644
--- a/frontend/src/core/runtime/runtime.ts
+++ b/frontend/src/core/runtime/runtime.ts
@@ -3,14 +3,13 @@
import { Deferred } from "@/utils/Deferred";
import { Logger } from "@/utils/Logger";
import { KnownQueryParams } from "../constants";
+import { NOTEBOOK_EVENT_TYPES } from "../host/events";
import { isIslands } from "../islands/utils";
import { getSessionId, type SessionId } from "../kernel/session";
import { isStaticNotebook } from "../static/static-state";
import { isWasm } from "../wasm/utils";
import type { RuntimeConfig } from "./types";
-const HOST_EVENT_TYPES = ["marimo"];
-
export class RuntimeManager {
private initialHealthyCheck = new Deferred<void>();
private config: RuntimeConfig;
@@ -165,7 +164,7 @@ export class RuntimeManager {
const url = this.formatWsURL(path, searchParams);
if (notebookId) {
// TODO(MO-8034): Separate host options from notebook query params.
- url.searchParams.set("types", HOST_EVENT_TYPES.join(","));
+ url.searchParams.set("types", NOTEBOOK_EVENT_TYPES.join(","));
}
return url;
}
@@ -177,6 +176,8 @@ export class RuntimeManager {
* (see `headers()`) instead of the URL.
*/
public getSseURL(sessionId: SessionId): URL {
+ // TODO: Migrate editor SSE to the host event stream. Until then, host
+ // state such as attachments is unavailable on this legacy connection.
const url = this.formatHttpURL({
path: "/sse",
searchParams: this.getSessionSearchParams(sessionId),
diff --git a/frontend/src/core/websocket/__tests__/useNotebookClient.hook.test.tsx b/frontend/src/core/websocket/__tests__/useNotebookClient.hook.test.tsx
index b123b635bb..c78b81c7d0 100644
--- a/frontend/src/core/websocket/__tests__/useNotebookClient.hook.test.tsx
+++ b/frontend/src/core/websocket/__tests__/useNotebookClient.hook.test.tsx
@@ -9,6 +9,9 @@ import { ConnectionState } from "../types";
import { createConnectionTransport } from "../transports/create";
import type { IConnectionTransport } from "../transports/transport";
import { useNotebookClient } from "../useNotebookClient";
+import { fixtureMessages } from "../../host/__tests__/fixtures";
+import { agentAttachmentsAtom } from "../../attachments/state";
+import { notebookClientAtom } from "../state";
vi.mock("../transports/create", () => ({ createConnectionTransport: vi.fn() }));
@@ -30,6 +33,10 @@ function makeTransport() {
};
return {
transport,
+ receive: (message: unknown) =>
+ events.dispatchEvent(
+ new MessageEvent("message", { data: JSON.stringify(message) }),
+ ),
notify: () =>
events.dispatchEvent(
new MessageEvent("message", {
@@ -72,6 +79,29 @@ beforeEach(() => {
});
describe("useNotebookClient", () => {
+ it("exposes host presence to the UI without waiting for kernel-ready", async () => {
+ const transport = makeTransport();
+ vi.mocked(createConnectionTransport).mockReturnValue(transport.transport);
+ const { result, store, unmount } = setup();
+ await act(async () => Promise.resolve());
+ expect(store.get(notebookClientAtom)).toBe(result.current);
+ act(() =>
+ fixtureMessages("notebook-events.sse").forEach(transport.receive),
+ );
+ expect(store.get(agentAttachmentsAtom)).toEqual([
+ {
+ id: "a2",
+ notebook_id: "n1",
+ kind: "agent",
+ name: "Notebook CLI",
+ since: "2026-10-01T09:20:03Z",
+ },
+ ]);
+ unmount();
+ expect(store.get(notebookClientAtom)).toBeNull();
+ expect(store.get(agentAttachmentsAtom)).toEqual([]);
+ });
+
it("uses current callbacks and URL providers without reconnecting on a rerender", async () => {
const first = makeTransport();
vi.mocked(createConnectionTransport).mockReturnValue(first.transport);
diff --git a/frontend/src/core/websocket/__tests__/useNotebookSession.hook.test.tsx b/frontend/src/core/websocket/__tests__/useNotebookSession.hook.test.tsx
index 2e319b4787..a531d6d38e 100644
--- a/frontend/src/core/websocket/__tests__/useNotebookSession.hook.test.tsx
+++ b/frontend/src/core/websocket/__tests__/useNotebookSession.hook.test.tsx
@@ -41,11 +41,6 @@ import { Logger } from "@/utils/Logger";
import { Deferred } from "@/utils/Deferred";
import { cellId } from "@/__tests__/branded";
import { alertAtom, getPackageAlert } from "@/core/alerts/state";
-import {
- type Attachment,
- attachmentsAtom,
- agentAttachmentsAtom,
-} from "@/core/attachments/state";
import { notebookAtom } from "@/core/cells/cells";
import { AppConfigSchema } from "@/core/config/config-schema";
import { ConnectionNotice } from "@/components/editor/alerts/connection-notice";
@@ -239,28 +234,6 @@ describe("useNotebookSession messages", () => {
});
}
- it("replaces attachment snapshots, including the last detach", () => {
- const agent: Attachment = {
- id: "a1",
- kind: "agent",
- name: "Pi",
- since: "2026-10-14T00:00:00Z",
- notebook_id: "nb-test",
- identity: "pi-thread",
- };
- const client: Attachment = {
- id: "c1",
- kind: "client",
- name: null,
- since: "2026-10-14T00:00:01Z",
- notebook_id: "nb-test",
- };
- for (const attachments of [[agent, client], [client], []]) {
- receive({ data: { op: "attachments", attachments } });
- expect(store.get(attachmentsAtom)).toEqual(attachments);
- }
- });
-
it.each(["{broken", "null"])(
"reports a malformed legacy frame and continues applying notifications: %s",
(data) => {
@@ -408,150 +381,6 @@ it.each(["kernel-ready", "reconnected"])(
},
);
-describe("attachment snapshots across browser connections", () => {
- const agent: Attachment = {
- id: "a1",
- kind: "agent",
- name: "Pi",
- since: "2026-10-14T00:00:00Z",
- notebook_id: "nb-test",
- identity: "pi-thread",
- };
-
- function connectedSession() {
- const store = createStore();
- store.set(connectionAtom, { state: ConnectionState.OPEN });
- store.set(attachmentsAtom, [agent]);
- const transport = makeTransport(WebSocket.OPEN);
- vi.mocked(createConnectionTransport).mockReturnValue(transport);
- vi.mocked(useRuntimeManager).mockReturnValue(makeRuntimeManager());
- renderConnectionHook(store);
- const options = getTransportHandlers();
- const receive = (data: NotificationPayload["data"]) =>
- act(() => {
- options.onMessage(
- new MessageEvent("message", {
- data: JSON.stringify({ op: data.op, data }),
- }),
- );
- });
- return { store, transport, options, receive };
- }
-
- it.each([
- "MARIMO_NO_FILE_KEY",
- "MARIMO_NO_SESSION_ID",
- "MARIMO_NO_SESSION",
- "MARIMO_SHUTDOWN",
- "MARIMO_KERNEL_STARTUP_ERROR",
- "MARIMO_UNAUTHORIZED",
- "MARIMO_KIOSK_NOT_ALLOWED",
- "MARIMO_TRANSPORT_EXHAUSTED",
- ])("clears cached attachments on %s", (reason) => {
- const { store, transport, options } = connectedSession();
- act(() => options.onClose(new CloseEvent("close", { reason })));
- expect(store.get(attachmentsAtom)).toEqual([]);
- expect(store.get(agentAttachmentsAtom)).toEqual([]);
- expect(store.get(connectionAtom).state).toBe(ConnectionState.CLOSED);
- expect(transport.reconnect).not.toHaveBeenCalled();
- });
-
- it("clears the snapshot on transport error", () => {
- const { store, options } = connectedSession();
- act(() => options.onError(new Event("error")));
- expect(store.get(attachmentsAtom)).toEqual([]);
- expect(store.get(agentAttachmentsAtom)).toEqual([]);
- });
-
- it("waits for a fresh snapshot after a transient reconnect", async () => {
- const { store, transport, options, receive } = connectedSession();
- act(() => options.onClose(new CloseEvent("close")));
- expect(store.get(attachmentsAtom)).toEqual([]);
- expect(store.get(connectionAtom).state).toBe(ConnectionState.CONNECTING);
- expect(transport.reconnect).toHaveBeenCalledOnce();
-
- await act(async () => options.onOpen(new Event("open")));
- receive({ op: "reconnected" });
- expect(store.get(connectionAtom).state).toBe(ConnectionState.OPEN);
- expect(store.get(agentAttachmentsAtom)).toEqual([]);
-
- const refreshed = { ...agent, id: "a2", name: "Codex" };
- receive({ op: "attachments", attachments: [refreshed] });
- expect(store.get(agentAttachmentsAtom)).toEqual([refreshed]);
- receive({ op: "attachments", attachments: [] });
- expect(store.get(agentAttachmentsAtom)).toEqual([]);
- });
-
- it("keeps a fresh snapshot hidden until the session is ready", async () => {
- const { store, options, receive } = connectedSession();
- act(() => options.onClose(new CloseEvent("close")));
- await act(async () => options.onOpen(new Event("open")));
- receive({ op: "attachments", attachments: [agent] });
- expect(store.get(attachmentsAtom)).toEqual([agent]);
- expect(store.get(agentAttachmentsAtom)).toEqual([]);
- receive({ op: "reconnected" });
- expect(store.get(agentAttachmentsAtom)).toEqual([agent]);
- });
-
- it("invalidates an old snapshot when a new transport opens", async () => {
- const { store, options } = connectedSession();
- await act(async () => options.onOpen(new Event("open")));
- expect(store.get(attachmentsAtom)).toEqual([]);
- expect(store.get(agentAttachmentsAtom)).toEqual([]);
- });
-});
-
-it.each([true, false])(
- "keeps attachments only when kernel-ready resumes the session: %s",
- (resumed) => {
- const store = createStore();
- const attachments: Attachment[] = [
- {
- id: "a1",
- kind: "agent",
- name: "Pi",
- since: "2026-10-14T00:00:00Z",
- notebook_id: "nb-test",
- identity: "pi-thread",
- },
- ];
- store.set(attachmentsAtom, attachments);
- vi.mocked(createConnectionTransport).mockReturnValue(
- makeTransport(WebSocket.OPEN),
- );
- vi.mocked(useRuntimeManager).mockReturnValue(makeRuntimeManager());
- renderConnectionHook(store);
- const options = getTransportHandlers();
- act(() =>
- options.onMessage(
- new MessageEvent("message", {
- data: JSON.stringify({
- op: "kernel-ready",
- data: {
- op: "kernel-ready",
- cell_ids: [],
- codes: [],
- names: [],
- configs: [],
- layout: null,
- resumed,
- ui_values: {},
- last_executed_code: {},
- last_execution_time: {},
- app_config: { width: "normal" },
- kiosk: false,
- capabilities: { terminal: false },
- auto_instantiated: true,
- consumer_capabilities: { edit: true, interact: true },
- },
- }),
- }),
- ),
- );
- expect(store.get(attachmentsAtom)).toEqual(resumed ? attachments : []);
- },
-);
-
describe("connection notice", () => {
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());
diff --git a/frontend/src/core/websocket/state.ts b/frontend/src/core/websocket/state.ts
new file mode 100644
index 0000000000..0aaa71538a
--- /dev/null
+++ b/frontend/src/core/websocket/state.ts
@@ -0,0 +1,7 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { atom } from "jotai";
+import type { NotebookClient } from "../host/notebook-client";
+
+/** The client owned by the mounted notebook session. */
+export const notebookClientAtom = atom<NotebookClient | null>(null);
diff --git a/frontend/src/core/websocket/useNotebookClient.ts b/frontend/src/core/websocket/useNotebookClient.ts
index 7764ae06dc..08d4fffbe0 100644
--- a/frontend/src/core/websocket/useNotebookClient.ts
+++ b/frontend/src/core/websocket/useNotebookClient.ts
@@ -14,6 +14,7 @@ import {
type NotebookConnection,
} from "../host/notebook-client";
import { classifyCloseEvent } from "./connection-state";
+import { notebookClientAtom } from "./state";
import {
createConnectionTransport,
type ConnectionTransportOptions,
@@ -41,6 +42,7 @@ export function useNotebookClient(options: Options): NotebookClient {
useEffect(() => {
const lifetime = new AbortController();
+ store.set(notebookClientAtom, controller.client);
controller.connect({
createTransport: (url) =>
createConnectionTransport({
@@ -61,9 +63,15 @@ export function useNotebookClient(options: Options): NotebookClient {
decodeJson: jsonParseWithSpecialChar,
classifyClose: classifyCloseEvent,
});
- return () => lifetime.abort();
+ return () => {
+ lifetime.abort();
+ if (store.get(notebookClientAtom) === controller.client) {
+ store.set(notebookClientAtom, null);
+ }
+ };
}, [
controller,
+ store,
sessionId,
isStatic,
transportType,
diff --git a/frontend/src/core/websocket/useNotebookSession.tsx b/frontend/src/core/websocket/useNotebookSession.tsx
index 53055bdab5..040d7dce40 100644
--- a/frontend/src/core/websocket/useNotebookSession.tsx
+++ b/frontend/src/core/websocket/useNotebookSession.tsx
@@ -5,7 +5,6 @@ import { useAtom, useAtomValue, useSetAtom, useStore } from "jotai";
import { useLayoutEffect } from "react";
import { useErrorBoundary } from "react-error-boundary";
import { toast } from "@/components/ui/use-toast";
-import { attachmentsAtom } from "@/core/attachments/state";
import { getNotebook, useCellActions } from "@/core/cells/cells";
import { applyTransactionChanges } from "@/core/cells/document-changes";
import { AUTOCOMPLETER } from "@/core/codemirror/completion/Autocompleter";
@@ -140,7 +139,6 @@ export function useNotebookSession(opts: {
const transportType = useAtomValue(connectionTransportTypeAtom);
const setCacheInfo = useSetAtom(cacheInfoAtom);
const setKernelStartupError = useSetAtom(kernelStartupErrorAtom);
- const setAttachments = useSetAtom(attachmentsAtom);
const {
setNamespaces: setStorageNamespaces,
filterFromVariables: filterStorageFromVariables,
@@ -148,9 +146,6 @@ export function useNotebookSession(opts: {
const handleNotification = (msg: NotificationPayload) => {
switch (msg.data.op) {
- case "attachments":
- setAttachments(msg.data.attachments);
- return;
case "reload":
reloadSafe();
return;
@@ -185,7 +180,6 @@ export function useNotebookSession(opts: {
existingCells,
});
if (!msg.data.resumed) {
- setAttachments([]);
// A freshly started kernel may expose a different environment
// (e.g. new env vars); re-run discovery instead of reusing stale
// suggestions from the previous kernel instance.
@@ -452,7 +446,6 @@ export function useNotebookSession(opts: {
if (status.state === ConnectionState.NOT_STARTED) {
return;
}
- setAttachments([]);
if (status.state === ConnectionState.OPEN) {
updateStartupProgress(null);
return; // kernel-ready, not the socket, establishes session readiness.
@@ -487,7 +480,6 @@ export function useNotebookSession(opts: {
notebook,
store,
setConnection,
- setAttachments,
setKernelStartupError,
updateStartupProgress,
]);
diff --git a/marimo/_messaging/notification.py b/marimo/_messaging/notification.py
index fb1d130bf4..5f31cb422a 100644
--- a/marimo/_messaging/notification.py
+++ b/marimo/_messaging/notification.py
@@ -17,7 +17,6 @@ import msgspec
from marimo import _loggers as loggers
from marimo._ast.app_config import _AppConfig
from marimo._ast.cell import CellConfig, RuntimeStateType
-from marimo._core.protocol import Attachment
from marimo._data._external_storage.models import (
StorageEntry,
StorageNamespace,
@@ -104,17 +103,6 @@ class ExecutionNotification(Notification, tag="execution"):
caused_by: str | None = None
-class AttachmentsNotification(Notification, tag="attachments"):
- """Replace the current list of attachments on this Session.
-
- Args:
- attachments (list[Attachment]): Full list of live attachments.
- """
-
- name: ClassVar[str] = "attachments"
- attachments: list[Attachment]
-
-
class CellNotification(Notification, tag="cell-op"):
"""Updates a cell's state in the frontend.
@@ -1174,5 +1162,4 @@ NotificationMessage = (
| NotebookDocumentTransactionNotification
# Consumer
| ConsumerCapabilitiesNotification
- | AttachmentsNotification
)
diff --git a/marimo/_server/api/endpoints/ws/session_handler.py b/marimo/_server/api/endpoints/ws/session_handler.py
index 8c393c2d4b..7796180074 100644
--- a/marimo/_server/api/endpoints/ws/session_handler.py
+++ b/marimo/_server/api/endpoints/ws/session_handler.py
@@ -13,7 +13,6 @@ from marimo._cli.upgrade import check_for_updates
from marimo._config.settings import GLOBAL_SETTINGS
from marimo._messaging.notification import (
AlertNotification,
- AttachmentsNotification,
BannerNotification,
EnvironmentOperationNotification,
EnvironmentStateNotification,
@@ -25,7 +24,6 @@ from marimo._messaging.serde import (
deserialize_kernel_notification_name,
serialize_kernel_message,
)
-from marimo._server.api.deps import AppStateBase
from marimo._server.api.endpoints.ws.ws_kernel_ready import (
build_kernel_ready,
is_rtc_available,
@@ -93,7 +91,6 @@ class SessionHandler(SessionConsumer, abc.ABC):
self.doc_manager = doc_manager
self.status = ConnectionState.CONNECTING
self._session: Session | None = None
- self._app_state: AppStateBase | None = None
self.cancel_close_handle: asyncio.TimerHandle | None = None
# Messages from the kernel are put in this queue
# to be sent to the frontend
@@ -151,7 +148,6 @@ class SessionHandler(SessionConsumer, abc.ABC):
WebSocketDisconnect: If the connection is rejected; carries the
close code and reason.
"""
- self._app_state = AppStateBase.from_app(connection.app)
startup = asyncio.create_task(
SessionConnector(
manager=self.manager,
@@ -369,17 +365,6 @@ class SessionHandler(SessionConsumer, abc.ABC):
self, session: Session, *, include_notebook: bool = True
) -> None:
"""Replay retained state to this client."""
- # Send after kernel-ready/reconnected and before later live deltas.
- notebook = (
- self._app_state.notebook_for_session(session)
- if self._app_state is not None
- else None
- )
- self._serialize_and_notify(
- AttachmentsNotification(
- attachments=[] if notebook is None else notebook.attachments
- )
- )
notifications = session.session_view.snapshot_notifications(
include_notebook=include_notebook
)
diff --git a/marimo/_server/host/bridge.py b/marimo/_server/host/bridge.py
index 8a0359c1d9..bc426e85ef 100644
--- a/marimo/_server/host/bridge.py
+++ b/marimo/_server/host/bridge.py
@@ -20,7 +20,6 @@ from marimo._core.errors import (
from marimo._core.executions import Executions
from marimo._core.host import Host
from marimo._core.notebook import Notebook
-from marimo._messaging.notification import AttachmentsNotification
from marimo._runtime.commands import RenameNotebookCommand
from marimo._server.host import OPERATIONS, document as documents
from marimo._server.host.analysis import HostAnalyzer
@@ -117,7 +116,7 @@ class SessionBridge(SessionEventListener):
self.host, manager.workspace, self._initialize_notebook
)
self._unsubscribe = self.host.subscribe(
- self._on_host_event, types={"notebook", "attachment"}
+ self._on_host_event, types={"notebook"}
)
async def open(self) -> None:
@@ -131,11 +130,6 @@ class SessionBridge(SessionEventListener):
self._manager.event_bus.unsubscribe(self)
self._unsubscribe()
- def session_for_notebook(self, notebook_id: str) -> Session | None:
- """Return the current session for a host notebook."""
- backend = self._backends.get(protocol.NotebookId(notebook_id))
- return None if backend is None else backend.session
-
def notebook_for_session(self, session: Session) -> Notebook | None:
"""Return the host notebook that owns this session's runtime."""
for notebook_id, backend in self._backends.items():
@@ -681,33 +675,10 @@ class SessionBridge(SessionEventListener):
isinstance(event.event, protocol.NotebookRemovedEvent)
and event.notebook_id is not None
):
- session = self.session_for_notebook(event.notebook_id)
- if session is not None:
- session.notify(
- AttachmentsNotification(attachments=[]),
- from_consumer_id=None,
- )
self._backends.pop(event.notebook_id, None)
self._file_texts.pop(event.notebook_id, None)
self._rebaselining.pop(event.notebook_id, None)
self._mirrored.pop(event.notebook_id, None)
- elif (
- isinstance(
- event.event,
- (protocol.AttachmentEvent, protocol.AttachmentRemovedEvent),
- )
- and event.notebook_id is not None
- ):
- session = self.session_for_notebook(event.notebook_id)
- try:
- notebook = self.host.peek_notebook(event.notebook_id)
- except NotFound:
- return
- if session is not None and notebook is not None:
- session.notify(
- AttachmentsNotification(attachments=notebook.attachments),
- from_consumer_id=None,
- )
async def _adopt(self, session: Session) -> None:
path = session.app_file_manager.path
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index 1c5725810d..297460da96 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -264,72 +264,6 @@ components:
required: []
title: AnthropicConfig
type: object
- Attachment:
- properties:
- id:
- description: Identifies an attachment. Unique within the host.
- minLength: 1
- type: string
- identity:
- description: 'The opaque client identity supplied by `Marimo-Attachment-Identity`.
-
- Omitted when none was supplied. Consumers can group attachments
-
- with the same identity within a host. It does not identify an
-
- individual connection or change its lifetime.
-
- '
- maxLength: 128
- minLength: 1
- pattern: ^[!-~]+$
- type: string
- kind:
- description: What kind of thing is attached, supplied by `Marimo-Attachment-Kind`,
- such as `browser`, `editor`, or `agent`. Defaults to `client` when the
- header is omitted. Clients accept kinds they do not recognize.
- pattern: ^[a-z0-9-]+$
- type: string
- name:
- anyOf:
- - description: A label to show people, supplied by `Marimo-Attachment-Name`,
- such as the browser or editor's name. Null when the header is omitted
- or empty.
- maxLength: 256
- type: string
- - type: 'null'
- notebook_id:
- description: Identifies a notebook. Unique within the host and unchanged
- while the notebook exists.
- minLength: 1
- type: string
- since:
- description: When it attached.
- type: string
- required:
- - id
- - kind
- - name
- - notebook_id
- - since
- title: Attachment
- type: object
- AttachmentsNotification:
- description: "Replace the current list of attachments on this Session.\n\n \
- \ Args:\n attachments (list[Attachment]): Full list of live attachments."
- properties:
- attachments:
- items:
- $ref: '#/components/schemas/Attachment'
- type: array
- op:
- enum:
- - attachments
- required:
- - op
- - attachments
- title: AttachmentsNotification
- type: object
AutoExportAsIPYNBRequest:
properties:
download:
@@ -4283,12 +4217,10 @@ components:
- $ref: '#/components/schemas/ActiveLineNotification'
- $ref: '#/components/schemas/NotebookDocumentTransactionNotification'
- $ref: '#/components/schemas/ConsumerCapabilitiesNotification'
- - $ref: '#/components/schemas/AttachmentsNotification'
discriminator:
mapping:
active-line: '#/components/schemas/ActiveLineNotification'
alert: '#/components/schemas/AlertNotification'
- attachments: '#/components/schemas/AttachmentsNotification'
banner: '#/components/schemas/BannerNotification'
cache-cleared: '#/components/schemas/CacheClearedNotification'
cache-info: '#/components/schemas/CacheInfoNotification'
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index 97897c363e..0e618b1c42 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -3984,36 +3984,6 @@ export interface components {
AnthropicConfig: {
api_key?: string;
};
- /** Attachment */
- Attachment: {
- /** @description Identifies an attachment. Unique within the host. */
- id: string;
- /** @description The opaque client identity supplied by `Marimo-Attachment-Identity`.
- * Omitted when none was supplied. Consumers can group attachments
- * with the same identity within a host. It does not identify an
- * individual connection or change its lifetime.
- * */
- identity?: string;
- /** @description What kind of thing is attached, supplied by `Marimo-Attachment-Kind`, such as `browser`, `editor`, or `agent`. Defaults to `client` when the header is omitted. Clients accept kinds they do not recognize. */
- kind: string;
- name: string | null;
- /** @description Identifies a notebook. Unique within the host and unchanged while the notebook exists. */
- notebook_id: string;
- /** @description When it attached. */
- since: string;
- };
- /**
- * AttachmentsNotification
- * @description Replace the current list of attachments on this Session.
- *
- * Args:
- * attachments (list[Attachment]): Full list of live attachments.
- */
- AttachmentsNotification: {
- attachments: components["schemas"]["Attachment"][];
- /** @enum {unknown} */
- op: "attachments";
- };
/** AutoExportAsIPYNBRequest */
AutoExportAsIPYNBRequest: {
download: boolean;
@@ -6364,8 +6334,7 @@ export interface components {
| components["schemas"]["FocusCellNotification"]
| components["schemas"]["ActiveLineNotification"]
| components["schemas"]["NotebookDocumentTransactionNotification"]
- | components["schemas"]["ConsumerCapabilitiesNotification"]
- | components["schemas"]["AttachmentsNotification"];
+ | components["schemas"]["ConsumerCapabilitiesNotification"];
/**
* OpenAiConfig
* @description Configuration options for OpenAI or OpenAI-compatible services.
diff --git a/tests/_server/api/endpoints/test_kiosk.py b/tests/_server/api/endpoints/test_kiosk.py
index 2f41490a81..650216c8bd 100644
--- a/tests/_server/api/endpoints/test_kiosk.py
+++ b/tests/_server/api/endpoints/test_kiosk.py
@@ -47,10 +47,6 @@ async def test_connect_kiosk_with_session(client: TestClient) -> None:
),
)
- attachments = other_websocket.receive_json()
- assert attachments["op"] == "attachments"
- assert attachments["data"]["attachments"] == []
-
for _ in range(2):
assert (
other_websocket.receive_json()["op"] == "environment-state"
diff --git a/tests/_server/api/endpoints/test_resume_session.py b/tests/_server/api/endpoints/test_resume_session.py
index 3f7b03fd80..6cc8077180 100644
--- a/tests/_server/api/endpoints/test_resume_session.py
+++ b/tests/_server/api/endpoints/test_resume_session.py
@@ -316,7 +316,7 @@ def test_resume_session_after_file_change(client: TestClient) -> None:
with client.websocket_connect(_create_ws_url("123")) as websocket:
data = websocket.receive_json()
assert_kernel_ready_response(data, create_response({}))
- for op in ("attachments", "environment-state", "environment-state"):
+ for op in ("environment-state", "environment-state"):
assert websocket.receive_json()["op"] == op
session = get_session(client, SessionId("123"))
@@ -395,10 +395,6 @@ def test_environment_restored_after_disconnect(
with client:
with client.websocket_connect(_create_ws_url("123")) as websocket:
assert_kernel_ready_response(websocket.receive_json())
- assert websocket.receive_json() == {
- "op": "attachments",
- "data": {"op": "attachments", "attachments": []},
- }
for source in ("kernel", "server"):
assert websocket.receive_json() == {
"op": "environment-state",
@@ -471,10 +467,6 @@ def test_environment_restored_after_disconnect(
assert websocket.receive_json()["op"] == "banner"
else:
assert websocket.receive_json()["op"] == "alert"
- assert websocket.receive_json() == {
- "op": "attachments",
- "data": {"op": "attachments", "attachments": []},
- }
assert websocket.receive_json() == json.loads(
format_wire_message(
expected.name, serialize_kernel_message(expected)
diff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.py
index 6730af736b..4e72a50af9 100644
--- a/tests/_server/api/endpoints/test_ws.py
+++ b/tests/_server/api/endpoints/test_ws.py
@@ -5,17 +5,14 @@ import asyncio
from contextlib import contextmanager
from pathlib import Path
from typing import TYPE_CHECKING, Any
-from unittest.mock import AsyncMock, MagicMock, Mock, patch
+from unittest.mock import AsyncMock, MagicMock, patch
-import msgspec
import pytest
from starlette.websockets import WebSocketDisconnect, WebSocketState
from marimo._config.config import ExperimentalConfig
from marimo._config.manager import MarimoConfigManager
-from marimo._core.host import Host
from marimo._messaging.notification import (
- CellNotification,
EnvironmentOperationNotification,
KernelReadyNotification,
OperationSucceeded,
@@ -28,17 +25,10 @@ from marimo._server.api.endpoints.ws.ws_connection_validator import (
from marimo._server.api.endpoints.ws.ws_session_connector import ConnectionType
from marimo._server.api.endpoints.ws_endpoint import WebSocketHandler
from marimo._server.codes import WebSocketCodes
-from marimo._server.host.context import HostContext
from marimo._server.session_manager import SessionManager
from marimo._session.model import ConnectionState, SessionMode
-from marimo._types.ids import CellId_t, SessionId
+from marimo._types.ids import SessionId
from marimo._utils.parse_dataclass import parse_raw
-from tests._core.conftest import (
- ScriptedBackend,
- add_notebook,
- project,
- record,
-)
from tests._server.api.endpoints.ws_helpers import (
HEADERS,
assert_kernel_ready_response,
@@ -204,60 +194,6 @@ def test_disconnect_then_reconnect_then_refresh(client: TestClient) -> None:
assert manager.sessions[SessionId("456")].stable_id == stable_id
[email protected]("attachment_state", ["attached", "detached", "empty"])
[email protected]("url", [WS_URL, OTHER_WS_URL])
-async def test_reconnect_restores_current_attachments(
- client: TestClient, attachment_state: str, url: str
-) -> None:
- manager = get_session_manager(client)
- with client.websocket_connect(WS_URL) as websocket:
- assert_kernel_ready_response(websocket.receive_json())
- session = manager.sessions[SessionId("123")]
- host = Host(operations=[])
- host.update_project(project())
- notebook = await add_notebook(host, record(), ScriptedBackend())
- bridge = Mock()
- bridge.notebook_for_session.return_value = notebook
- client.app.state.host_context = HostContext(bridge, "host-token", 2718)
- attachment = None
- if attachment_state != "empty":
- attachment = notebook.attach(
- kind="agent", identity="agent-1", name="Test Agent"
- )
- if attachment_state == "detached":
- notebook.detach(attachment.id)
- session.session_view.add_notification(
- StartupProgressNotification(
- phase="starting-kernel", logs="Done\n", log_mode="replace"
- )
- )
- session.session_view.add_notification(
- CellNotification(cell_id=CellId_t("replay-marker"), status="idle")
- )
-
- last_op = "startup-progress" if url == WS_URL else "cell-op"
- expected_attachments = []
- if attachment_state == "attached":
- assert attachment is not None
- expected_attachments = [
- msgspec.json.decode(msgspec.json.encode(attachment))
- ]
- with client.websocket_connect(url) as websocket:
- messages = [websocket.receive_json()]
- while messages[-1]["op"] != last_op:
- messages.append(websocket.receive_json())
- snapshots = [m for m in messages if m["op"] == "attachments"]
- assert snapshots == [
- {
- "op": "attachments",
- "data": {
- "op": "attachments",
- "attachments": expected_attachments,
- },
- }
- ]
-
-
def test_completed_startup_is_restored_on_reconnect_and_refresh(
client: TestClient,
) -> None:
@@ -515,7 +451,6 @@ async def test_connects_to_existing_session_with_same_file(
data = websocket1.receive_json()
assert_parse_ready_response(data)
for op in (
- "attachments",
"environment-state",
"environment-state",
):
@@ -544,7 +479,6 @@ async def test_connects_to_existing_session_with_same_file(
data2 = websocket2.receive_json()
assert_parse_ready_response(data2)
for op in (
- "attachments",
"environment-state",
"environment-state",
):
diff --git a/tests/_server/host/test_editor_websocket.py b/tests/_server/host/test_editor_websocket.py
index 6f2859f4de..da2a652ca8 100644
--- a/tests/_server/host/test_editor_websocket.py
+++ b/tests/_server/host/test_editor_websocket.py
@@ -8,6 +8,7 @@ from typing import TYPE_CHECKING, Any
import msgspec
import pytest
+from dirty_equals import IsStr
from starlette.websockets import WebSocketDisconnect
from marimo._messaging.cell_output import CellChannel, CellOutput
@@ -122,6 +123,49 @@ def test_editor_starts_and_runs_through_the_host_socket(
assert sum("host socket" in str(output) for output in consoles) == 1
+def test_editor_receives_native_attachment_snapshots_and_changes(
+ client: TestClient, editor_host: SessionBridge
+) -> None:
+ assert client.portal is not None
+ (notebook_id,) = editor_host.host.notebooks
+ notebook = client.portal.call(editor_host.host.notebook, notebook_id)
+ agent = client.portal.call(
+ lambda: notebook.attach(kind="agent", name="Test Agent")
+ )
+ url = f"{socket_url(editor_host)}&types=attachment"
+ with client.websocket_connect(url) as socket:
+ snapshot = socket_snapshot(socket)
+ assert [event["event"] for event in snapshot] == [
+ "attachment",
+ "attachment",
+ "ready",
+ ]
+ assert snapshot[0]["data"]["attachment"] == msgspec.to_builtins(agent)
+ client.portal.call(notebook.detach, agent.id)
+ removed = socket.receive_json()
+ assert removed == {
+ "event": "attachment.removed",
+ "id": IsStr,
+ "data": {"id": agent.id, "time": IsStr},
+ }
+ replacement = client.portal.call(
+ lambda: notebook.attach(kind="agent", name="Replacement")
+ )
+ attached = socket.receive_json()
+ assert attached["event"] == "attachment"
+ assert attached["data"]["attachment"] == msgspec.to_builtins(
+ replacement
+ )
+ client.portal.call(notebook.detach, replacement.id)
+ with client.websocket_connect(url) as socket:
+ snapshot = socket_snapshot(socket)
+ assert [event["event"] for event in snapshot] == [
+ "attachment",
+ "ready",
+ ]
+ assert snapshot[0]["data"]["attachment"]["kind"] == "client"
+
+
def test_reconnect_keeps_state_and_refresh_replays_it(
client: TestClient, editor_host: SessionBridge
) -> None:
diff --git a/tests/_server/host/test_host_bridge.py b/tests/_server/host/test_host_bridge.py
index aa2ec62691..d55b8f0c7a 100644
--- a/tests/_server/host/test_host_bridge.py
+++ b/tests/_server/host/test_host_bridge.py
@@ -7,7 +7,6 @@ import asyncio
import threading
from types import SimpleNamespace
from typing import TYPE_CHECKING
-from unittest.mock import Mock
import pytest
from starlette.datastructures import State
@@ -16,7 +15,6 @@ from marimo._core import protocol
from marimo._core.errors import Conflict, DecisionRequired, EditConflict
from marimo._core.stream import RoutedEvent
from marimo._messaging.notification import (
- AttachmentsNotification,
CompletedRunNotification,
ExecutionNotification,
StartupProgressNotification,
@@ -1048,7 +1046,7 @@ async def test_session_notifications_join_the_notebook_stream_once(
async def test_session_notebook_lookup_boundaries(
manager: FakeManager, tmp_path: Path
) -> None:
- prepare(manager, tmp_path, "a.py", "unopened.py")
+ prepare(manager, tmp_path, "a.py")
saved = FakeSession(str(tmp_path / "a.py"))
unsaved = FakeSession(None)
outside = FakeSession(str(tmp_path.parent / "outside.py"))
@@ -1057,61 +1055,17 @@ async def test_session_notebook_lookup_boundaries(
await bridge.open()
notebook = bridge.notebook_for_session(saved) # type: ignore[arg-type]
assert notebook is not None
- assert bridge.session_for_notebook(notebook.id) is saved
assert bridge.notebook_for_session(unsaved) is None # type: ignore[arg-type]
assert bridge.notebook_for_session(outside) is None # type: ignore[arg-type]
assert (
bridge.notebook_for_session(FakeSession(str(tmp_path / "a.py")))
is None
) # type: ignore[arg-type]
- unopened = bridge.index.notebook_for(str(tmp_path / "unopened.py"))
- assert unopened is not None
- assert bridge.session_for_notebook(unopened.id) is None
- assert bridge.session_for_notebook("missing") is None
saved.close()
- assert bridge.session_for_notebook(notebook.id) is None
assert bridge.notebook_for_session(saved) is None # type: ignore[arg-type]
bridge.close()
-async def test_attachment_feed_uses_full_current_state_and_unsubscribes(
- manager: FakeManager, tmp_path: Path
-) -> None:
- prepare(manager, tmp_path, "a.py", "b.py")
- first = FakeSession(str(tmp_path / "a.py"))
- second = FakeSession(str(tmp_path / "b.py"))
- first.notify = Mock() # type: ignore[attr-defined]
- second.notify = Mock() # type: ignore[attr-defined]
- manager.sessions.update(first=first, second=second)
- bridge = SessionBridge(manager) # type: ignore[arg-type]
- await bridge.open()
- notebook = bridge.notebook_for_session(first) # type: ignore[arg-type]
- assert notebook is not None
- assert notebook.attachments == []
- agent = notebook.attach(identity="codex", kind="agent", name="Codex")
- client = notebook.attach(kind="client")
- notebook.detach(agent.id)
- notebook.detach("missing")
- assert first.notify.call_args_list == [ # type: ignore[attr-defined]
- (
- (AttachmentsNotification(attachments=[agent]),),
- {"from_consumer_id": None},
- ),
- (
- (AttachmentsNotification(attachments=[agent, client]),),
- {"from_consumer_id": None},
- ),
- (
- (AttachmentsNotification(attachments=[client]),),
- {"from_consumer_id": None},
- ),
- ]
- second.notify.assert_not_called() # type: ignore[attr-defined]
- bridge.close()
- notebook.detach(client.id)
- assert first.notify.call_count == 3 # type: ignore[attr-defined]
-
-
@pytest.mark.parametrize("mode", ["edit", "run"])
def test_app_state_without_host_has_no_notebook(mode: str) -> None:
state = AppStateBase(
@@ -1149,23 +1103,3 @@ async def test_bridge_supplies_metadata_for_the_current_session(
assert backend._run.task is not None
await backend._run.task
bridge.close()
-
-
-async def test_removing_notebook_clears_browser_attachments(
- manager: FakeManager, tmp_path: Path
-) -> None:
- prepare(manager, tmp_path, "a.py")
- session = FakeSession(str(tmp_path / "a.py"))
- session.notify = Mock() # type: ignore[attr-defined]
- manager.sessions["browser"] = session
- bridge = SessionBridge(manager) # type: ignore[arg-type]
- await bridge.open()
- notebook = bridge.notebook_for_session(session) # type: ignore[arg-type]
- assert notebook is not None
- notebook.attach(identity="codex", kind="agent", name="Codex")
- bridge.host.remove_notebook(notebook.id)
- session.notify.assert_called_with( # type: ignore[attr-defined]
- AttachmentsNotification(attachments=[]), from_consumer_id=None
- )
- assert bridge.session_for_notebook(notebook.id) is None
- bridge.close()
diff --git a/tests/_server/host/test_host_websocket.py b/tests/_server/host/test_host_websocket.py
index 094530f957..1d04e2fd57 100644
--- a/tests/_server/host/test_host_websocket.py
+++ b/tests/_server/host/test_host_websocket.py
@@ -149,15 +149,6 @@ def test_snapshot_is_private_and_precedes_updates_during_accept(
) as second:
assert socket_snapshot(second)[:-1] == initial
live = second.receive_json()
- attachment_update = first.receive_json()
- assert (
- attachment_update["data"]["marimo"]["op"]
- == "attachments"
- )
- assert (
- len(attachment_update["data"]["marimo"]["attachments"])
- == 2
- )
assert first.receive_json() == live
assert live == {
"id": live["id"],
@@ -285,12 +276,7 @@ def test_reconnect_replays_original_events_then_continues_live(
url += f"&cursor={cursor}"
with client.websocket_connect(url, headers=headers) as socket:
replay = socket_snapshot(socket)
- assert replay[0] == missed
- assert [
- event["data"]["marimo"]["op"] for event in replay[1:-1]
- ] == ["attachments", "attachments"]
- assert replay[1]["data"]["marimo"]["attachments"] == []
- assert len(replay[2]["data"]["marimo"]["attachments"]) == 1
+ assert replay[:-1] == [missed]
client.portal.call(
session.notify, CompletedRunNotification(run_id="live")
)
diff --git a/tests/_session/state/test_session_view.py b/tests/_session/state/test_session_view.py
index e408edad7a..33927364b8 100644
--- a/tests/_session/state/test_session_view.py
+++ b/tests/_session/state/test_session_view.py
@@ -1,7 +1,6 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
-from datetime import datetime, timezone
from typing import Any, Literal
from unittest.mock import patch
@@ -9,7 +8,6 @@ import msgspec
import pytest
from marimo._ast.cell import RuntimeStateType
-from marimo._core.protocol import Attachment, NotebookId
from marimo._data.models import (
Database,
DataSourceConnection,
@@ -21,7 +19,6 @@ from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._messaging.errors import UnknownError
from marimo._messaging.msgspec_encoder import asdict as serialize
from marimo._messaging.notification import (
- AttachmentsNotification,
CellNotification,
DatasetsNotification,
DataSourceConnectionsNotification,
@@ -88,54 +85,6 @@ initial_status: RuntimeStateType = "running"
updated_status: RuntimeStateType = "running"
-def test_attachment_replay_starts_without_a_notification(
- session_view: SessionView,
-) -> None:
- assert not any(
- isinstance(notification, AttachmentsNotification)
- for notification in session_view.snapshot_notifications()
- )
-
-
[email protected]("clear", [False, True])
-def test_attachment_changes_are_not_retained_for_replay(
- session_view: SessionView, *, clear: bool
-) -> None:
- agent = Attachment(
- id="a1",
- kind="agent",
- name="Claude Code",
- since=datetime(2026, 1, 1, tzinfo=timezone.utc),
- notebook_id=NotebookId("nb-test"),
- )
- other = Attachment(
- id="a2",
- kind="agent",
- name="Codex",
- since=datetime(2026, 1, 2, tzinfo=timezone.utc),
- notebook_id=NotebookId("nb-test"),
- )
- client = Attachment(
- id="c1",
- kind="client",
- name=None,
- since=datetime(2026, 1, 3, tzinfo=timezone.utc),
- notebook_id=NotebookId("nb-test"),
- )
- session_view.add_raw_notification(
- serialize_kernel_message(
- AttachmentsNotification(attachments=[agent, other, client])
- )
- )
- latest = AttachmentsNotification(attachments=[] if clear else [other])
- session_view.add_raw_notification(serialize_kernel_message(latest))
-
- assert not any(
- isinstance(notification, AttachmentsNotification)
- for notification in session_view.snapshot_notifications()
- )
-
-
def test_session_view_cell_notification(session_view: SessionView) -> None:
# Create initial CellNotification
initial_cell_notification = CellNotification(
diff --git a/tests/_session/test_notification_ordering.py b/tests/_session/test_notification_ordering.py
index d13f040f78..40e6980ceb 100644
--- a/tests/_session/test_notification_ordering.py
+++ b/tests/_session/test_notification_ordering.py
@@ -11,10 +11,7 @@ import pytest
from marimo._ast.app import App, InternalApp
from marimo._config.manager import get_default_config_manager
-from marimo._core.host import Host
from marimo._messaging.notification import (
- AttachmentsNotification,
- CellNotification,
EnvironmentOperation,
EnvironmentOperationNotification,
EnvironmentState,
@@ -40,9 +37,8 @@ from marimo._session.model import ConnectionState, SessionMode
from marimo._session.notebook import AppFileManager
from marimo._session.session import SessionImpl
from marimo._session.state.session_view import SessionView
-from marimo._types.ids import CellId_t, ConsumerId, SessionId
+from marimo._types.ids import ConsumerId, SessionId
from marimo._utils.distributor import QueueDistributor
-from tests._core.conftest import ScriptedBackend, add_notebook, project, record
if TYPE_CHECKING:
from collections.abc import Iterator
@@ -118,49 +114,6 @@ def test_notification_is_retained_before_consumer_receives_it(
assert observed == [_state("Downloading\n")]
-async def test_attachment_change_follows_cell_op_and_updates_live_state_before_delivery(
- session_and_consumer: tuple[SessionImpl, Mock],
-) -> None:
- session, consumer = session_and_consumer
- host = Host(operations=[])
- host.update_project(project())
- notebook = await add_notebook(host, record(), ScriptedBackend())
- observed = []
-
- def receive(_message: KernelMessage) -> None:
- observed.append(
- (
- [
- notification
- for notification in session.get_current_state().snapshot_notifications()
- if isinstance(notification, CellNotification)
- ],
- notebook.attachments,
- )
- )
-
- consumer.notify.side_effect = receive
- cell_op = CellNotification(
- cell_id=CellId_t("cell-1"), status="running", timestamp=1.0
- )
- host.subscribe(
- lambda _event: session.notify(
- AttachmentsNotification(attachments=notebook.attachments),
- from_consumer_id=None,
- ),
- types={"attachment"},
- )
- session.notify(cell_op, from_consumer_id=None)
- agent = notebook.attach(kind="agent", name="Claude Code")
- attached = AttachmentsNotification(attachments=[agent])
-
- assert [
- deserialize_kernel_message(call.args[0])
- for call in consumer.notify.call_args_list
- ] == [cell_op, attached]
- assert observed == [([cell_op], []), ([cell_op], [agent])]
-
-
async def test_queued_kernel_messages_update_and_deliver_on_session_loop(
session_and_consumer: tuple[SessionImpl, Mock],
) -> None: