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.

feat(pair): send agent messages through host notebooks (#11225)

Kiran Gadhave5f59ef3661b9
diff --git a/frontend/src/components/editor/Output.tsx b/frontend/src/components/editor/Output.tsx
index b2a7bacfca..aedad0744b 100644
--- a/frontend/src/components/editor/Output.tsx
+++ b/frontend/src/components/editor/Output.tsx
@@ -66,7 +66,7 @@ export type OnRefactorWithAI = (opts: {
* Renders an output based on an OutputMessage.
*/
export const OutputRenderer: React.FC<{
- message: Pick<OutputMessage, "channel" | "data" | "mimetype">;
+ message: Pick<OutputMessage, "channel" | "data" | "mimetype" | "code">;
cellId?: CellId;
onRefactorWithAI?: OnRefactorWithAI;
wrapText?: boolean;
@@ -172,7 +172,9 @@ export const OutputRenderer: React.FC<{
case "application/vnd.marimo+error":
invariant(Array.isArray(data), "Expected array data");
- return <MarimoErrorOutput cellId={cellId} errors={data} />;
+ return (
+ <MarimoErrorOutput cellId={cellId} errors={data} code={message.code} />
+ );
case "application/vnd.marimo+traceback":
invariant(
@@ -183,6 +185,7 @@ export const OutputRenderer: React.FC<{
<MarimoTracebackOutput
onRefactorWithAI={onRefactorWithAI}
traceback={data}
+ code={message.code}
cellId={cellId}
/>
);
diff --git a/frontend/src/components/editor/chrome/panels/error-panel.tsx b/frontend/src/components/editor/chrome/panels/error-panel.tsx
index e4058332fb..ab8442c688 100644
--- a/frontend/src/components/editor/chrome/panels/error-panel.tsx
+++ b/frontend/src/components/editor/chrome/panels/error-panel.tsx
@@ -25,6 +25,7 @@ const ErrorsPanel: React.FC = () => {
<MarimoErrorOutput
key={error.cellId}
errors={error.output.data}
+ code={error.output.code}
cellId={error.cellId}
/>
</div>
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
new file mode 100644
index 0000000000..6d8c21b8fd
--- /dev/null
+++ b/frontend/src/components/editor/chrome/wrapper/__tests__/attachment-status.test.tsx
@@ -0,0 +1,167 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+// @vitest-environment jsdom
+
+import { act, fireEvent, render, screen } from "@testing-library/react";
+import { createStore, Provider } from "jotai";
+import { userEvent } from "storybook/test";
+import { describe, expect, it } from "vitest";
+import { PAIR_PREVIEW } from "@/__tests__/fixtures/pair-preview";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { type Attachment, attachmentsAtom } from "@/core/attachments/state";
+import { pairPreviewAtom } from "@/core/config/pair";
+import { connectionAtom } from "@/core/network/connection";
+import { WebSocketClosedReason, ConnectionState } from "@/core/websocket/types";
+import { AttachmentStatus } from "../footer-items/attachment-status";
+
+const AGENT: Attachment = {
+ id: "a1",
+ kind: "agent",
+ name: "Pi",
+ notebook_id: "nb-test",
+ identity: "pi-thread",
+ since: new Date().toISOString(),
+};
+
+function renderStatus(attachments: Attachment[] = [AGENT], preview = true) {
+ const store = createStore();
+ store.set(connectionAtom, { state: ConnectionState.OPEN });
+ store.set(pairPreviewAtom, preview ? PAIR_PREVIEW : undefined);
+ store.set(attachmentsAtom, attachments);
+ return {
+ store,
+ ...render(
+ <Provider store={store}>
+ <TooltipProvider>
+ <AttachmentStatus />
+ </TooltipProvider>
+ </Provider>,
+ ),
+ };
+}
+
+describe("AttachmentStatus", () => {
+ it("renders nothing outside the preview", () => {
+ expect(renderStatus([AGENT], false).container).toBeEmptyDOMElement();
+ });
+
+ it("renders nothing without agents", () => {
+ expect(
+ renderStatus([{ ...AGENT, kind: "client" }]).container,
+ ).toBeEmptyDOMElement();
+ });
+
+ it("lists each agent by its self-described name", () => {
+ renderStatus([
+ AGENT,
+ { ...AGENT, id: "a2", identity: "claude-thread", name: "Claude Code" },
+ { ...AGENT, id: "c1", kind: "client", name: "Browser" },
+ ]);
+ expect(screen.getAllByTestId("footer-attachment-status")).toHaveLength(2);
+ expect(screen.getByLabelText("Pi: Connected")).toBeInTheDocument();
+ expect(screen.getByLabelText("Claude Code: Connected")).toBeInTheDocument();
+ expect(screen.queryByText("Browser")).not.toBeInTheDocument();
+ fireEvent.click(screen.getByLabelText("Pi: Connected"));
+ expect(screen.getByText(/^Connected /)).toBeInTheDocument();
+ });
+
+ it("uses Agent when no name was supplied", () => {
+ renderStatus([{ ...AGENT, name: null }]);
+ expect(screen.getByLabelText("Agent: Connected")).toBeInTheDocument();
+ });
+
+ it("groups attachments by identity while retaining each connection row", () => {
+ renderStatus([
+ AGENT,
+ { ...AGENT, id: "a2", since: "2026-10-14T00:00:00Z" },
+ ]);
+ expect(screen.getAllByTestId("footer-attachment-status")).toHaveLength(1);
+ fireEvent.click(screen.getByLabelText("Pi: Connected"));
+ expect(screen.getAllByText(/^Connected /)).toHaveLength(2);
+ expect(screen.getByText("a1")).toBeInTheDocument();
+ expect(screen.getByText("a2")).toBeInTheDocument();
+ });
+
+ it("preserves an open popover when the same identity reconnects", () => {
+ const { store } = renderStatus();
+ fireEvent.click(screen.getByLabelText("Pi: Connected"));
+ act(() =>
+ store.set(attachmentsAtom, [
+ { ...AGENT, id: "a2", since: "2026-10-14T00:00:00Z" },
+ ]),
+ );
+ expect(
+ screen.getByRole("button", { name: "Pi: Connected" }),
+ ).toHaveAttribute("aria-expanded", "true");
+ expect(screen.queryByText("a1")).not.toBeInTheDocument();
+ expect(screen.getByText("a2")).toBeInTheDocument();
+ });
+
+ it("does not open a closed popover when the same identity reconnects", () => {
+ const { store } = renderStatus();
+ act(() => store.set(attachmentsAtom, [{ ...AGENT, id: "a2" }]));
+ expect(
+ screen.getByRole("button", { name: "Pi: Connected" }),
+ ).toHaveAttribute("aria-expanded", "false");
+ });
+
+ it("keeps anonymous attachments separate from matching client identities", () => {
+ renderStatus([
+ { ...AGENT, identity: undefined },
+ { ...AGENT, id: "a2", identity: undefined },
+ { ...AGENT, id: "a3", identity: "a1" },
+ ]);
+ expect(screen.getAllByTestId("footer-attachment-status")).toHaveLength(3);
+ });
+
+ it("accepts client identities that match object property names", () => {
+ renderStatus([
+ { ...AGENT, identity: "__proto__" },
+ { ...AGENT, id: "a2", identity: "constructor" },
+ ]);
+ expect(screen.getAllByTestId("footer-attachment-status")).toHaveLength(2);
+ });
+
+ it.each(["{Enter}", " "])("opens from the keyboard with %j", async (key) => {
+ const user = userEvent.setup();
+ renderStatus();
+ const button = screen.getByRole("button", { name: "Pi: Connected" });
+ expect(button.tagName).toBe("BUTTON");
+ expect(button).toHaveAttribute("type", "button");
+ await user.tab();
+ expect(button).toHaveFocus();
+ await user.keyboard(key);
+ expect(button).toHaveAttribute("aria-expanded", "true");
+ expect(screen.getByText(/^Connected /)).toBeInTheDocument();
+ await user.keyboard("{Escape}");
+ expect(button).toHaveAttribute("aria-expanded", "false");
+ expect(button).toHaveFocus();
+ });
+
+ 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,
+ { ...AGENT, id: "a2", identity: "claude-thread", name: "Claude Code" },
+ ]);
+ act(() => store.set(attachmentsAtom, [AGENT]));
+ expect(
+ screen.queryByLabelText("Claude Code: Connected"),
+ ).not.toBeInTheDocument();
+ act(() => store.set(attachmentsAtom, []));
+ expect(container).toBeEmptyDOMElement();
+ });
+});
diff --git a/frontend/src/components/editor/chrome/wrapper/footer-item.tsx b/frontend/src/components/editor/chrome/wrapper/footer-item.tsx
index e979aca49c..7337753f27 100644
--- a/frontend/src/components/editor/chrome/wrapper/footer-item.tsx
+++ b/frontend/src/components/editor/chrome/wrapper/footer-item.tsx
@@ -1,6 +1,7 @@
/* Copyright 2026 Marimo. All rights reserved. */
import type React from "react";
+import { Slot as SlotPrimitive } from "radix-ui";
import { forwardRef } from "react";
import { Tooltip } from "@/components/ui/tooltip";
import { cn } from "@/utils/cn";
@@ -8,36 +9,43 @@ import { cn } from "@/utils/cn";
type FooterItemProps = {
selected: boolean;
tooltip: React.ReactNode;
+ asChild?: boolean;
} & React.HTMLAttributes<HTMLDivElement>;
export const FooterItem: React.FC<FooterItemProps> = forwardRef<
HTMLDivElement,
FooterItemProps
->(({ children, tooltip, selected, className, ...rest }, ref) => {
- const content = (
- <div
- ref={ref}
- className={cn(
- "h-full flex items-center p-2 text-sm shadow-inset font-mono cursor-pointer rounded",
- !selected && "hover:bg-(--sage-3)",
- selected && "bg-(--sage-4)",
- className,
- )}
- {...rest}
- >
- {children}
- </div>
- );
-
- if (tooltip) {
- return (
- <Tooltip content={tooltip} side="top" delayDuration={200}>
- {content}
- </Tooltip>
+>(
+ (
+ { children, tooltip, selected, className, asChild = false, ...rest },
+ ref,
+ ) => {
+ const Component = asChild ? SlotPrimitive.Slot : "div";
+ const content = (
+ <Component
+ ref={ref}
+ className={cn(
+ "h-full flex items-center p-2 text-sm shadow-inset font-mono cursor-pointer rounded",
+ !selected && "hover:bg-(--sage-3)",
+ selected && "bg-(--sage-4)",
+ className,
+ )}
+ {...rest}
+ >
+ {children}
+ </Component>
);
- }
- return content;
-});
+ if (tooltip) {
+ return (
+ <Tooltip content={tooltip} side="top" delayDuration={200}>
+ {content}
+ </Tooltip>
+ );
+ }
+
+ return content;
+ },
+);
FooterItem.displayName = "FooterItem";
diff --git a/frontend/src/components/editor/chrome/wrapper/footer-items/attachment-status.tsx b/frontend/src/components/editor/chrome/wrapper/footer-items/attachment-status.tsx
new file mode 100644
index 0000000000..115a041bb8
--- /dev/null
+++ b/frontend/src/components/editor/chrome/wrapper/footer-items/attachment-status.tsx
@@ -0,0 +1,82 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { useAtomValue } from "jotai";
+import { BotIcon } from "lucide-react";
+import { useState } from "react";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import {
+ type Attachment,
+ agentAttachmentsAtom,
+ attachmentLabel,
+} from "@/core/attachments/state";
+import { pairPreviewAtom } from "@/core/config/pair";
+import { useTimeAgo } from "@/hooks/useFormatting";
+import { Objects } from "@/utils/objects";
+import { FooterItem } from "../footer-item";
+
+export function AttachmentStatus() {
+ const pairPreview = useAtomValue(pairPreviewAtom);
+ const agents = useAtomValue(agentAttachmentsAtom);
+ if (!pairPreview) {
+ return null;
+ }
+ const groups = Objects.groupBy(
+ agents,
+ (attachment) =>
+ attachment.identity
+ ? `identity:${attachment.identity}`
+ : `attachment:${attachment.id}`,
+ (attachment) => attachment,
+ );
+ return Object.entries(groups).map(([identity, attachments]) => (
+ <AttachmentStatusItem key={identity} attachments={attachments} />
+ ));
+}
+
+function AttachmentStatusItem({ attachments }: { attachments: Attachment[] }) {
+ const [open, setOpen] = useState(false);
+ const timeAgo = useTimeAgo();
+ const label = attachmentLabel(attachments[0]);
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild={true}>
+ <FooterItem
+ asChild={true}
+ tooltip={`${label}: connected`}
+ selected={open}
+ data-testid="footer-attachment-status"
+ aria-label={`${label}: Connected`}
+ >
+ <button type="button">
+ <span className="flex items-center gap-1.5">
+ <BotIcon className="w-4 h-4" />
+ <span className="max-w-48 truncate">{label}</span>
+ </span>
+ </button>
+ </FooterItem>
+ </PopoverTrigger>
+ <PopoverContent className="w-64 text-sm">
+ <h4 className="font-medium">{label}</h4>
+ <ul className="space-y-2">
+ {attachments.map((attachment) => (
+ <li key={attachment.id}>
+ <p
+ className="truncate text-xs text-muted-foreground"
+ title={attachment.id}
+ >
+ {attachment.id}
+ </p>
+ <p className="text-muted-foreground">
+ Connected {timeAgo(attachment.since)}
+ </p>
+ </li>
+ ))}
+ </ul>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/frontend/src/components/editor/chrome/wrapper/footer.tsx b/frontend/src/components/editor/chrome/wrapper/footer.tsx
index 846d6e7da6..572cdc115c 100644
--- a/frontend/src/components/editor/chrome/wrapper/footer.tsx
+++ b/frontend/src/components/editor/chrome/wrapper/footer.tsx
@@ -12,6 +12,7 @@ import { ShowInKioskMode } from "../../kiosk-mode";
import { panelLayoutAtom, useChromeActions, useChromeState } from "../state";
import { FooterItem } from "./footer-item";
import { AIStatusIcon } from "./footer-items/ai-status";
+import { AttachmentStatus } from "./footer-items/attachment-status";
import {
BackendConnectionStatus,
connectionStatusAtom,
@@ -107,6 +108,7 @@ export const Footer: React.FC = () => {
<div className="flex items-center shrink-0 min-w-0">
<MachineStats />
+ <AttachmentStatus />
<AIStatusIcon />
<CopilotStatusIcon />
<RTCStatus />
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
new file mode 100644
index 0000000000..a406ad2514
--- /dev/null
+++ b/frontend/src/components/editor/errors/__tests__/send-error-report-button.test.tsx
@@ -0,0 +1,434 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+// @vitest-environment jsdom
+
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { createStore, Provider, useAtomValue } from "jotai";
+import type React from "react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { MockNotebook } from "@/__mocks__/notebook";
+import { cellId } from "@/__tests__/branded";
+import { PAIR_PREVIEW } from "@/__tests__/fixtures/pair-preview";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { toast } from "@/components/ui/use-toast";
+import { type Attachment, attachmentsAtom } from "@/core/attachments/state";
+import { exportedForTesting, notebookAtom } from "@/core/cells/cells";
+import type {
+ CellOutputHandoff,
+ ErrorHandoffOutput,
+} from "@/core/cells/error-report";
+import { pairPreviewAtom } from "@/core/config/pair";
+import type { MarimoError, OutputMessage } from "@/core/kernel/messages";
+import {
+ type StableSessionId,
+ stableSessionIdAtom,
+} from "@/core/kernel/session";
+import { API } from "@/core/network/api";
+import { connectionAtom } from "@/core/network/connection";
+import { WebSocketClosedReason, ConnectionState } from "@/core/websocket/types";
+import { Deferred } from "@/utils/Deferred";
+import { HTTPError } from "@/utils/errors";
+import { MarimoErrorOutput } from "../../output/MarimoErrorOutput";
+import { MarimoTracebackOutput } from "../../output/MarimoTracebackOutput";
+import { OutputRenderer } from "../../Output";
+import { SendErrorReportButton } from "../send-error-report-button";
+
+vi.mock("@/components/ui/use-toast", () => ({ toast: vi.fn() }));
+vi.mock("@/core/network/api", () => ({ API: { post: vi.fn() } }));
+vi.mock("@/components/editor/chrome/wrapper/useOpenAiAssistant", () => ({
+ useOpenAiAssistant: () => vi.fn(),
+}));
+
+const CELL_ID = cellId("test-cell");
+const STABLE_ID = "stable/test" as StableSessionId;
+const AGENT: Attachment = {
+ id: "a1",
+ kind: "agent",
+ name: "Pi",
+ since: "2026-10-14T00:00:00Z",
+ notebook_id: "nb-test",
+ identity: "pi-thread",
+};
+const ROUTE = "/pair/notebooks/stable%2Ftest/messages";
+const MESSAGE = "df is not defined";
+const CODE = "df.head()";
+const REPORT: CellOutputHandoff<ErrorHandoffOutput> = {
+ type: "cell-output",
+ cell_id: CELL_ID,
+ code: CODE,
+ output: { type: "error", message: MESSAGE },
+};
+const ERRORS: MarimoError[] = [
+ {
+ type: "exception",
+ exception_type: "NameError",
+ raising_cell: null,
+ msg: MESSAGE,
+ traceback: null,
+ },
+];
+
+function renderButton({
+ preview = true,
+ attachments = [AGENT],
+ stableId = STABLE_ID,
+ content = <SendErrorReportButton getContent={() => REPORT} />,
+}: {
+ preview?: boolean;
+ attachments?: Attachment[];
+ stableId?: StableSessionId | null;
+ content?: React.ReactNode;
+} = {}) {
+ const store = createStore();
+ store.set(connectionAtom, { state: ConnectionState.OPEN });
+ store.set(pairPreviewAtom, preview ? PAIR_PREVIEW : undefined);
+ store.set(attachmentsAtom, attachments);
+ store.set(stableSessionIdAtom, stableId);
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <Provider store={store}>
+ <TooltipProvider>{children}</TooltipProvider>
+ </Provider>
+ );
+ return { store, ...render(content, { wrapper }) };
+}
+
+function send() {
+ fireEvent.click(screen.getByRole("button", { name: "Send error to agent" }));
+}
+
+describe("SendErrorReportButton", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(API.post).mockResolvedValue("");
+ });
+
+ it("hides outside the preview without building content", () => {
+ const getContent = vi.fn(() => REPORT);
+ expect(
+ renderButton({
+ preview: false,
+ content: <SendErrorReportButton getContent={getContent} />,
+ }).container,
+ ).toBeEmptyDOMElement();
+ expect(getContent).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { attachments: [] },
+ { attachments: [{ ...AGENT, kind: "client" as const }] },
+ { stableId: null },
+ ])("disables sending without an agent or stable ID: %j", (options) => {
+ renderButton(options);
+ expect(screen.getByRole("button")).toBeDisabled();
+ send();
+ expect(API.post).not.toHaveBeenCalled();
+ });
+
+ it("builds content on click and sends it to all agents", async () => {
+ const getContent = vi.fn(() => REPORT);
+ renderButton({
+ attachments: [AGENT, { ...AGENT, id: "a2", name: "Claude Code" }],
+ content: <SendErrorReportButton getContent={getContent} />,
+ });
+ expect(getContent).not.toHaveBeenCalled();
+ send();
+ await waitFor(() =>
+ expect(toast).toHaveBeenCalledWith({ title: "Sent to Pi, Claude Code" }),
+ );
+ expect(API.post).toHaveBeenCalledWith(ROUTE, REPORT);
+ expect(getContent).toHaveBeenCalledOnce();
+ });
+
+ it("prevents duplicate sends while a request is pending", async () => {
+ const deferred = new Deferred<string>();
+ vi.mocked(API.post).mockReturnValue(deferred.promise);
+ renderButton();
+ send();
+ expect(screen.getByRole("button")).toBeDisabled();
+ send();
+ expect(API.post).toHaveBeenCalledOnce();
+ await act(async () => deferred.resolve(""));
+ expect(screen.getByRole("button")).toBeEnabled();
+ });
+
+ it("disables the button after the last agent disconnects", () => {
+ const { store } = renderButton();
+ act(() => store.set(attachmentsAtom, []));
+ 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"],
+ ])("reports request failures and permits retry", async (error, title) => {
+ vi.mocked(API.post).mockRejectedValueOnce(error);
+ renderButton();
+ send();
+ await waitFor(() =>
+ expect(toast).toHaveBeenCalledWith({ variant: "danger", title }),
+ );
+ expect(screen.getByRole("button")).toBeEnabled();
+ send();
+ await waitFor(() =>
+ expect(toast).toHaveBeenCalledWith({ title: "Sent to Pi" }),
+ );
+ expect(API.post).toHaveBeenCalledTimes(2);
+ expect(API.post).toHaveBeenLastCalledWith(ROUTE, REPORT);
+ });
+
+ it("sends captured code and full traceback from the error output", async () => {
+ const traceback = "<pre>Traceback\nNameError: df is not defined</pre>";
+ renderButton({
+ content: (
+ <OutputRenderer
+ cellId={CELL_ID}
+ message={{
+ channel: "marimo-error",
+ mimetype: "application/vnd.marimo+error",
+ code: CODE,
+ data: [{ ...ERRORS[0], traceback }],
+ }}
+ />
+ ),
+ });
+ send();
+ await waitFor(() =>
+ expect(API.post).toHaveBeenCalledWith(ROUTE, {
+ ...REPORT,
+ output: {
+ type: "error",
+ message: MESSAGE,
+ traceback: "Traceback\nNameError: df is not defined",
+ },
+ }),
+ );
+ });
+
+ it("sends a formatter error beside a normal main output", async () => {
+ const { store } = renderButton({
+ content: (
+ <OutputRenderer
+ cellId={CELL_ID}
+ message={{
+ channel: "stderr",
+ mimetype: "application/vnd.marimo+traceback",
+ code: CODE,
+ data: "<pre>Traceback\nValueError: bad &lt;value&gt;</pre>",
+ }}
+ />
+ ),
+ });
+ store.set(
+ notebookAtom,
+ MockNotebook.notebookState({
+ cellData: { [CELL_ID]: { code: "later edit" } },
+ cellRuntime: {
+ [CELL_ID]: {
+ output: {
+ channel: "output",
+ mimetype: "text/plain",
+ data: "<Broken formatter>",
+ },
+ },
+ },
+ }),
+ );
+ send();
+ await waitFor(() =>
+ expect(API.post).toHaveBeenCalledWith(ROUTE, {
+ ...REPORT,
+ output: {
+ type: "error",
+ message: "ValueError: bad <value>",
+ traceback: "Traceback\nValueError: bad <value>",
+ },
+ }),
+ );
+ });
+
+ it("sends updated content after the error changes", async () => {
+ const { rerender } = renderButton();
+ const updated = {
+ ...REPORT,
+ output: { type: "error", message: "Another error" },
+ };
+ rerender(<SendErrorReportButton getContent={() => updated} />);
+ send();
+ await waitFor(() => expect(API.post).toHaveBeenCalledWith(ROUTE, updated));
+ });
+
+ it.each([
+ "Hello agent",
+ { lens: { selection: [1, 2], chart: "scatter" } },
+ [1, "two"],
+ null,
+ ])("accepts arbitrary producer content: %j", async (content) => {
+ renderButton({
+ content: <SendErrorReportButton getContent={() => content} />,
+ });
+ send();
+ await waitFor(() => expect(API.post).toHaveBeenCalledWith(ROUTE, content));
+ });
+
+ it.each([false, true])(
+ "retains failed code after edits and a queued run (%s)",
+ async (queue) => {
+ const output: OutputMessage = {
+ channel: "marimo-error",
+ mimetype: "application/vnd.marimo+error",
+ data: ERRORS,
+ code: CODE,
+ };
+ // Render from the store so reducer changes reach the button.
+ const StoreOutput = () => {
+ const message = useAtomValue(notebookAtom).cellRuntime[CELL_ID]?.output;
+ return message ? (
+ <OutputRenderer cellId={CELL_ID} message={message} />
+ ) : null;
+ };
+ const { store } = renderButton({ content: <StoreOutput /> });
+ const actions = exportedForTesting.createActions((action) => {
+ store.set(notebookAtom, (state) =>
+ exportedForTesting.reducer(state, action),
+ );
+ });
+ act(() => {
+ store.set(
+ notebookAtom,
+ MockNotebook.notebookState({
+ cellData: { [CELL_ID]: { code: CODE, lastCodeRun: CODE } },
+ cellRuntime: { [CELL_ID]: { output } },
+ }),
+ );
+ actions.updateCellCode({
+ cellId: CELL_ID,
+ code: "print('edited')",
+ formattingChange: false,
+ });
+ if (queue) {
+ actions.prepareForRun({ cellId: CELL_ID });
+ actions.handleCellMessage({
+ cell_id: CELL_ID,
+ status: "queued",
+ timestamp: 2,
+ });
+ }
+ });
+ send();
+ await waitFor(() => expect(API.post).toHaveBeenCalledWith(ROUTE, REPORT));
+ },
+ );
+
+ it("does not borrow an old console traceback for a cancelled descendant", async () => {
+ const cancelled: MarimoError[] = [
+ {
+ type: "exception",
+ exception_type: "ValueError",
+ msg: "Ancestor failed",
+ raising_cell: cellId("ancestor"),
+ traceback: null,
+ },
+ ];
+ const { store } = renderButton({
+ content: (
+ <MarimoErrorOutput cellId={CELL_ID} code="x + 1" errors={cancelled} />
+ ),
+ });
+ store.set(
+ notebookAtom,
+ MockNotebook.notebookState({
+ cellData: {
+ [CELL_ID]: { code: "unrelated edit", lastCodeRun: "older run" },
+ },
+ cellRuntime: {
+ [CELL_ID]: {
+ consoleOutputs: [
+ {
+ channel: "stderr",
+ mimetype: "application/vnd.marimo+traceback",
+ data: "<pre>Old unrelated traceback</pre>",
+ code: "older run",
+ },
+ ],
+ },
+ },
+ }),
+ );
+ send();
+ await waitFor(() =>
+ expect(API.post).toHaveBeenCalledWith(ROUTE, {
+ type: "cell-output",
+ cell_id: CELL_ID,
+ code: "x + 1",
+ output: { type: "error", message: "Ancestor failed" },
+ }),
+ );
+ });
+
+ it("sends an interruption with its attempted code", async () => {
+ renderButton({
+ content: (
+ <MarimoErrorOutput
+ cellId={CELL_ID}
+ code="slow()"
+ errors={[{ type: "interruption" }]}
+ />
+ ),
+ });
+ send();
+ await waitFor(() =>
+ expect(API.post).toHaveBeenCalledWith(ROUTE, {
+ type: "cell-output",
+ cell_id: CELL_ID,
+ code: "slow()",
+ output: {
+ type: "error",
+ message: "This cell was interrupted and needs to be re-run",
+ },
+ }),
+ );
+ });
+
+ it("hides error actions without a cell identity or message", () => {
+ renderButton({
+ content: (
+ <>
+ <MarimoErrorOutput cellId={undefined} errors={ERRORS} />
+ <MarimoErrorOutput cellId={CELL_ID} errors={[]} />
+ <MarimoTracebackOutput
+ cellId={undefined}
+ traceback="<pre>ValueError: bad</pre>"
+ />
+ </>
+ ),
+ });
+ expect(
+ screen.queryByRole("button", { name: "Send error to agent" }),
+ ).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/components/editor/errors/send-error-report-button.tsx b/frontend/src/components/editor/errors/send-error-report-button.tsx
new file mode 100644
index 0000000000..9902bc0c2f
--- /dev/null
+++ b/frontend/src/components/editor/errors/send-error-report-button.tsx
@@ -0,0 +1,66 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { useAtomValue } from "jotai";
+import { SendIcon } from "lucide-react";
+import { useState } from "react";
+import { Button } from "@/components/ui/button";
+import { toast } from "@/components/ui/use-toast";
+import {
+ agentAttachmentsAtom,
+ attachmentLabel,
+} from "@/core/attachments/state";
+import { pairPreviewAtom } from "@/core/config/pair";
+import { stableSessionIdAtom } from "@/core/kernel/session";
+import { API } from "@/core/network/api";
+import { HTTPError } from "@/utils/errors";
+
+export function SendErrorReportButton({
+ getContent,
+}: {
+ getContent: () => unknown;
+}) {
+ const pairPreview = useAtomValue(pairPreviewAtom);
+ const agents = useAtomValue(agentAttachmentsAtom);
+ const stableSessionId = useAtomValue(stableSessionIdAtom);
+ const [sending, setSending] = useState(false);
+
+ if (!pairPreview) {
+ return null;
+ }
+
+ const send = async () => {
+ if (sending || agents.length === 0 || !stableSessionId) {
+ return;
+ }
+ setSending(true);
+ try {
+ await API.post<unknown, string>(
+ `/pair/notebooks/${encodeURIComponent(stableSessionId)}/messages`,
+ getContent(),
+ );
+ toast({ title: `Sent to ${agents.map(attachmentLabel).join(", ")}` });
+ } catch (error) {
+ toast({
+ variant: "danger",
+ title:
+ error instanceof HTTPError && error.status === 409
+ ? "No agent attached"
+ : "Could not send error",
+ });
+ } finally {
+ setSending(false);
+ }
+ };
+
+ return (
+ <Button
+ size="xs"
+ variant="outline"
+ disabled={sending || agents.length === 0 || !stableSessionId}
+ onClick={send}
+ >
+ <SendIcon className="h-3 w-3 mr-2" />
+ Send error to agent
+ </Button>
+ );
+}
diff --git a/frontend/src/components/editor/output/MarimoErrorOutput.tsx b/frontend/src/components/editor/output/MarimoErrorOutput.tsx
index 8e6cf2316f..cd11e99a66 100644
--- a/frontend/src/components/editor/output/MarimoErrorOutput.tsx
+++ b/frontend/src/components/editor/output/MarimoErrorOutput.tsx
@@ -21,8 +21,10 @@ import { Button } from "@/components/ui/button";
import { Kbd } from "@/components/ui/kbd";
import { ExternalLink } from "@/components/ui/links";
import { Tooltip } from "@/components/ui/tooltip";
+import { buildErrorReport } from "@/core/cells/error-report";
import type { CellId } from "@/core/cells/ids";
import { resolvedMarimoConfigAtom } from "@/core/config/config";
+import { viewStateAtom } from "@/core/mode";
import { renderHTML } from "@/plugins/core/RenderHTML";
import { splitMangledLocals } from "@/utils/local-variables";
import type { MarimoError } from "../../../core/kernel/messages";
@@ -32,6 +34,7 @@ import { openPackageManager } from "../chrome/panels/packages-utils";
import { useChromeActions } from "../chrome/state";
import { AutoFixButton } from "../errors/auto-fix";
import { MangledSegments } from "../errors/mangled-local-chip";
+import { SendErrorReportButton } from "../errors/send-error-report-button";
import { CellLinkError } from "../links/cell-link";
import { processTextForUrls } from "./console/text-rendering";
@@ -93,6 +96,7 @@ const Tip = (props: {
interface Props {
cellId: CellId | undefined;
errors: MarimoError[];
+ code?: string;
className?: string;
}
@@ -102,6 +106,7 @@ interface Props {
export const MarimoErrorOutput = ({
errors,
cellId,
+ code,
className,
}: Props): JSX.Element => {
const chromeActions = useChromeActions();
@@ -111,6 +116,9 @@ export const MarimoErrorOutput = ({
// only helpful when outputs are displayed above the editor.
const showConsoleHint =
useAtomValue(resolvedMarimoConfigAtom).display.cell_output === "above";
+ // The editor shows tracebacks in the console area, so the inline copy is
+ // for views without a console: published apps and present mode.
+ const showInlineTraceback = useAtomValue(viewStateAtom).mode !== "edit";
let titleContents: string | null =
"This cell wasn't run because it has errors";
@@ -208,7 +216,6 @@ export const MarimoErrorOutput = ({
(e): e is Extract<MarimoError, { type: "sql-error" }> =>
e.type === "sql-error",
);
-
const openScratchpad = () => {
chromeActions.openApplication("scratchpad");
};
@@ -558,7 +565,9 @@ export const MarimoErrorOutput = ({
<p className="text-muted-foreground">
{processTextForUrls(error.msg, `exception-${idx}`)}
</p>
- {"traceback" in error && error.traceback ? (
+ {showInlineTraceback &&
+ "traceback" in error &&
+ error.traceback ? (
<CollapsibleTraceback traceback={error.traceback} />
) : (
showConsoleHint && (
@@ -572,9 +581,11 @@ export const MarimoErrorOutput = ({
<div>
{processTextForUrls(error.msg, `exception-${idx}`)}
<CellLinkError cellId={error.raising_cell} />
- {"traceback" in error && error.traceback && (
- <CollapsibleTraceback traceback={error.traceback} />
- )}
+ {showInlineTraceback &&
+ "traceback" in error &&
+ error.traceback && (
+ <CollapsibleTraceback traceback={error.traceback} />
+ )}
</div>
)}
</li>
@@ -728,6 +739,11 @@ export const MarimoErrorOutput = ({
>
{title}
<div className="flex flex-col gap-4">{renderMessages()}</div>
+ {cellId && errors.length > 0 && (
+ <SendErrorReportButton
+ getContent={() => buildErrorReport(cellId, { code, errors })}
+ />
+ )}
</Alert>
);
};
diff --git a/frontend/src/components/editor/output/MarimoTracebackOutput.tsx b/frontend/src/components/editor/output/MarimoTracebackOutput.tsx
index 2722d593f4..1b6a7cc688 100644
--- a/frontend/src/components/editor/output/MarimoTracebackOutput.tsx
+++ b/frontend/src/components/editor/output/MarimoTracebackOutput.tsx
@@ -22,6 +22,7 @@ import {
import { Kbd } from "@/components/ui/kbd";
import { Tooltip } from "@/components/ui/tooltip";
import { getCellEditorView } from "@/core/cells/cells";
+import { buildErrorReport } from "@/core/cells/error-report";
import type { CellId } from "@/core/cells/ids";
import { SCRATCH_CELL_ID } from "@/core/cells/ids";
import { toggleBreakpoint } from "@/core/codemirror/cells/debugger-state";
@@ -46,12 +47,14 @@ import {
import { useOpenAiAssistant } from "../chrome/wrapper/useOpenAiAssistant";
import { AIFixButton, buildFixInChatPrompt } from "../errors/auto-fix";
import { MangledSegments } from "../errors/mangled-local-chip";
+import { SendErrorReportButton } from "../errors/send-error-report-button";
import { CellLinkTraceback } from "../links/cell-link";
import type { OnRefactorWithAI } from "../Output";
interface Props {
cellId: CellId | undefined;
traceback: string;
+ code?: string;
onRefactorWithAI?: OnRefactorWithAI;
}
@@ -62,6 +65,7 @@ export const MarimoTracebackOutput = ({
onRefactorWithAI,
traceback,
cellId,
+ code,
}: Props): JSX.Element => {
const htmlTraceback = renderHTML({
html: traceback,
@@ -131,6 +135,11 @@ export const MarimoTracebackOutput = ({
</div>
)}
<div className="flex gap-2">
+ {cellId && lastTracebackLine && (
+ <SendErrorReportButton
+ getContent={() => buildErrorReport(cellId, { code, traceback })}
+ />
+ )}
{showAIFix && (
<AIFixButton
tooltip="Fix with AI"
diff --git a/frontend/src/components/editor/output/__tests__/ansi-reduce.test.ts b/frontend/src/components/editor/output/__tests__/ansi-reduce.test.ts
index 9987805a86..d3514f969b 100644
--- a/frontend/src/components/editor/output/__tests__/ansi-reduce.test.ts
+++ b/frontend/src/components/editor/output/__tests__/ansi-reduce.test.ts
@@ -7,6 +7,24 @@ import {
TerminalBuffer,
} from "../ansi-reduce";
+test("preserves source evidence through stateful output and serialization", () => {
+ const output = StatefulOutputMessage.create({
+ channel: "stderr",
+ mimetype: "application/vnd.marimo+traceback",
+ timestamp: 1,
+ data: "<pre>ValueError:",
+ code: "raise ValueError('failed code')",
+ }).appendData(" failed code</pre>");
+ expect(output.code).toBe("raise ValueError('failed code')");
+ expect(output.toJSON()).toEqual({
+ channel: "stderr",
+ mimetype: "application/vnd.marimo+traceback",
+ timestamp: 1,
+ data: "<pre>ValueError: failed code</pre>",
+ code: "raise ValueError('failed code')",
+ });
+});
+
describe("TerminalBuffer", () => {
test("writeChar writes single character", () => {
const buffer = new TerminalBuffer();
diff --git a/frontend/src/components/editor/output/ansi-reduce.ts b/frontend/src/components/editor/output/ansi-reduce.ts
index 5423a66c02..d1175a7b62 100644
--- a/frontend/src/components/editor/output/ansi-reduce.ts
+++ b/frontend/src/components/editor/output/ansi-reduce.ts
@@ -368,6 +368,7 @@ export class StatefulOutputMessage implements OutputMessage {
public readonly mimetype: OutputMessage["mimetype"];
public readonly channel: OutputMessage["channel"];
public readonly timestamp: OutputMessage["timestamp"];
+ public readonly code: OutputMessage["code"];
private ansiReducer = new AnsiReducer();
private _data: string;
@@ -383,6 +384,7 @@ export class StatefulOutputMessage implements OutputMessage {
message.channel,
message.timestamp,
ansiReducer,
+ message.code,
);
}
@@ -391,10 +393,12 @@ export class StatefulOutputMessage implements OutputMessage {
channel: OutputMessage["channel"],
timestamp: OutputMessage["timestamp"],
ansiReducer: AnsiReducer,
+ code: OutputMessage["code"],
) {
this.mimetype = mimetype;
this.channel = channel;
this.timestamp = timestamp;
+ this.code = code;
this.ansiReducer = ansiReducer;
this._data = this.ansiReducer.render();
}
@@ -406,6 +410,7 @@ export class StatefulOutputMessage implements OutputMessage {
this.channel,
this.timestamp,
this.ansiReducer,
+ this.code,
);
}
@@ -415,6 +420,7 @@ export class StatefulOutputMessage implements OutputMessage {
channel: this.channel,
timestamp: this.timestamp,
data: this.data,
+ ...(this.code === undefined ? {} : { code: this.code }),
};
}
}
diff --git a/frontend/src/core/attachments/state.ts b/frontend/src/core/attachments/state.ts
new file mode 100644
index 0000000000..43902402b0
--- /dev/null
+++ b/frontend/src/core/attachments/state.ts
@@ -0,0 +1,21 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import type { components } from "@marimo-team/marimo-api";
+import { atom } from "jotai";
+import { isConnectedAtom } from "@/core/network/connection";
+
+export type Attachment = components["schemas"]["Attachment"];
+
+export const attachmentsAtom = atom<Attachment[]>([]);
+export const agentAttachmentsAtom = atom((get) => {
+ if (!get(isConnectedAtom)) {
+ return [];
+ }
+ return get(attachmentsAtom).filter(
+ (attachment) => attachment.kind === "agent",
+ );
+});
+
+export function attachmentLabel(attachment: Attachment): string {
+ return attachment.name || "Agent";
+}
diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.ts
index 4fdd58e5bd..01fcf601a7 100644
--- a/frontend/src/core/cells/__tests__/cells.test.ts
+++ b/frontend/src/core/cells/__tests__/cells.test.ts
@@ -789,6 +789,58 @@ describe("cell reducer", () => {
`);
});
+ it("keeps error evidence after an edit and a new queued run", () => {
+ const code = "raise ValueError('old failure')";
+ const output: OutputMessage = {
+ channel: "marimo-error",
+ mimetype: "application/vnd.marimo+error",
+ data: [
+ {
+ type: "exception",
+ msg: "old failure",
+ exception_type: "ValueError",
+ raising_cell: null,
+ traceback: "<pre>ValueError: old failure</pre>",
+ },
+ ],
+ code,
+ timestamp: 1,
+ };
+ actions.handleCellMessage({
+ cell_id: firstCellId,
+ output,
+ console: {
+ channel: "stderr",
+ mimetype: "application/vnd.marimo+traceback",
+ data: "<pre>ValueError: old failure</pre>",
+ code,
+ timestamp: 1,
+ },
+ status: "idle",
+ stale_inputs: null,
+ timestamp: 1,
+ });
+ actions.updateCellCode({
+ cellId: firstCellId,
+ code: "print('new code')",
+ formattingChange: false,
+ });
+ actions.prepareForRun({ cellId: firstCellId });
+ actions.handleCellMessage({
+ cell_id: firstCellId,
+ output: null,
+ console: null,
+ status: "queued",
+ stale_inputs: null,
+ timestamp: 2,
+ });
+ const runtime = state.cellRuntime[firstCellId];
+ expect(state.cellData[firstCellId].lastCodeRun).toBe("print('new code')");
+ expect(runtime.output).toEqual(output);
+ expect(runtime.consoleOutputs[0].code).toBe(code);
+ expect(runtime.consoleOutputs[0].data).toContain("old failure");
+ });
+
it("can run cell and receive cell messages", () => {
// HAPPY PATH
/////////////////
diff --git a/frontend/src/core/cells/__tests__/error-report.test.ts b/frontend/src/core/cells/__tests__/error-report.test.ts
new file mode 100644
index 0000000000..c4c1092c4f
--- /dev/null
+++ b/frontend/src/core/cells/__tests__/error-report.test.ts
@@ -0,0 +1,89 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+// @vitest-environment jsdom
+
+import { describe, expect, it } from "vitest";
+import { cellId } from "@/__tests__/branded";
+import type { MarimoError } from "@/core/kernel/messages";
+import { buildErrorReport } from "../error-report";
+
+const CELL_ID = cellId("failed-cell");
+
+describe("buildErrorReport", () => {
+ it("retains every message and complete traceback without display limits", () => {
+ const traceback = `Traceback\n${"long frame\n".repeat(10_000)}ValueError: bad <value>`;
+ const errors: MarimoError[] = [
+ {
+ type: "exception",
+ msg: "bad <value>",
+ exception_type: "ValueError",
+ raising_cell: null,
+ traceback: `<pre>${traceback.replaceAll("<", "&lt;").replaceAll(">", "&gt;")}</pre>`,
+ },
+ { type: "syntax", msg: "another error" },
+ ];
+ expect(buildErrorReport(CELL_ID, { code: "failed()", errors })).toEqual({
+ type: "cell-output",
+ cell_id: CELL_ID,
+ code: "failed()",
+ output: {
+ type: "error",
+ message: "bad <value>\nanother error",
+ traceback,
+ },
+ });
+ });
+
+ it("leaves source unknown for a restored legacy exception", () => {
+ expect(
+ buildErrorReport(CELL_ID, {
+ errors: [
+ {
+ type: "exception",
+ exception_type: "exception",
+ msg: "legacy error",
+ raising_cell: null,
+ traceback: null,
+ },
+ ],
+ }),
+ ).toEqual({
+ type: "cell-output",
+ cell_id: CELL_ID,
+ output: { type: "error", message: "legacy error" },
+ });
+ });
+
+ it("preserves empty captured code", () => {
+ expect(
+ buildErrorReport(CELL_ID, {
+ code: "",
+ errors: [{ type: "syntax", msg: "invalid code" }],
+ }),
+ ).toEqual({
+ type: "cell-output",
+ cell_id: CELL_ID,
+ code: "",
+ output: { type: "error", message: "invalid code" },
+ });
+ });
+
+ it("keeps separate structured tracebacks in order", () => {
+ const errors: MarimoError[] = ["first", "second"].map((message) => ({
+ type: "exception",
+ exception_type: "ValueError",
+ raising_cell: null,
+ msg: message,
+ traceback: `<pre>Traceback\nValueError: ${message}</pre>`,
+ }));
+ expect(buildErrorReport(CELL_ID, { errors })).toEqual({
+ type: "cell-output",
+ cell_id: CELL_ID,
+ output: {
+ type: "error",
+ message: "first\nsecond",
+ traceback:
+ "Traceback\nValueError: first\n\nTraceback\nValueError: second",
+ },
+ });
+ });
+});
diff --git a/frontend/src/core/cells/__tests__/session.test.ts b/frontend/src/core/cells/__tests__/session.test.ts
index 6c8afdc65e..8a2889e4a1 100644
--- a/frontend/src/core/cells/__tests__/session.test.ts
+++ b/frontend/src/core/cells/__tests__/session.test.ts
@@ -183,6 +183,40 @@ describe("notebookStateFromSession", () => {
});
});
+ it("restores matching code from the session", () => {
+ const code = "raise ValueError('cached failure')";
+ const session = createSession([
+ createSessionCell(
+ "cell-1",
+ [
+ {
+ type: "error",
+ ename: "ValueError",
+ evalue: "cached failure",
+ traceback: ["Traceback\n", "ValueError: cached failure"],
+ code,
+ },
+ ],
+ [
+ {
+ type: "stream",
+ name: "stderr",
+ text: "<pre>ValueError: cached failure</pre>",
+ mimetype: "application/vnd.marimo+traceback",
+ code,
+ },
+ ],
+ ),
+ ]);
+ const state = notebookStateFromSession(session, null);
+ invariant(state, "state is null");
+ expect(state.cellRuntime[CELL_1].output).toMatchObject({
+ code,
+ data: [{ type: "unknown", msg: "cached failure" }],
+ });
+ expect(state.cellRuntime[CELL_1].consoleOutputs[0].code).toBe(code);
+ });
+
it("handles data output in session cell", () => {
const dataOutput = {
type: "data" as const,
diff --git a/frontend/src/core/cells/error-report.ts b/frontend/src/core/cells/error-report.ts
new file mode 100644
index 0000000000..356edd276c
--- /dev/null
+++ b/frontend/src/core/cells/error-report.ts
@@ -0,0 +1,55 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { describeError } from "@/core/errors/error-entries";
+import type { MarimoError } from "@/core/kernel/messages";
+import { sanitizeHtml } from "@/plugins/core/sanitize-html";
+import { parseHtmlContent } from "@/utils/dom";
+import type { CellId } from "./ids";
+
+export interface CellOutputHandoff<Output> {
+ type: "cell-output";
+ cell_id: CellId;
+ code?: string;
+ output: Output;
+}
+
+export interface ErrorHandoffOutput {
+ type: "error";
+ message: string;
+ traceback?: string;
+}
+
+export function buildErrorReport(
+ cellId: CellId,
+ evidence: { code?: string } & (
+ | { errors: MarimoError[] }
+ | { traceback: string }
+ ),
+): CellOutputHandoff<ErrorHandoffOutput> {
+ let message: string;
+ let traceback: string;
+ if ("errors" in evidence) {
+ message = evidence.errors.map(describeError).join("\n");
+ traceback = evidence.errors
+ .flatMap((error) =>
+ "traceback" in error && error.traceback
+ ? [parseHtmlContent(sanitizeHtml(error.traceback))]
+ : [],
+ )
+ .join("\n\n");
+ } else {
+ traceback = parseHtmlContent(sanitizeHtml(evidence.traceback));
+ message = traceback.split("\n").findLast((line) => line.length > 0) ?? "";
+ }
+
+ return {
+ type: "cell-output",
+ cell_id: cellId,
+ ...(evidence.code === undefined ? {} : { code: evidence.code }),
+ output: {
+ type: "error",
+ message,
+ ...(traceback ? { traceback } : {}),
+ },
+ };
+}
diff --git a/frontend/src/core/cells/session.ts b/frontend/src/core/cells/session.ts
index 13a7aec355..e5aab56199 100644
--- a/frontend/src/core/cells/session.ts
+++ b/frontend/src/core/cells/session.ts
@@ -223,6 +223,9 @@ function createCellRuntimeFromSession(
timestamp: DEFAULT_TIMESTAMP,
};
}
+ if (runtimeState.output && primaryOutput.code !== undefined) {
+ runtimeState.output.code = primaryOutput.code;
+ }
}
const consoleOutputs = sessionCell.console || [];
@@ -238,6 +241,9 @@ function createCellRuntimeFromSession(
data: consoleOutput.data,
mimetype: consoleOutput.mimetype,
timestamp: DEFAULT_TIMESTAMP,
+ ...(consoleOutput.code === undefined
+ ? {}
+ : { code: consoleOutput.code }),
};
}
// Handle StreamOutput (type: "stream")
@@ -246,6 +252,9 @@ function createCellRuntimeFromSession(
data: consoleOutput.text,
mimetype: consoleOutput.mimetype ?? "text/plain",
timestamp: DEFAULT_TIMESTAMP,
+ ...(consoleOutput.code === undefined
+ ? {}
+ : { code: consoleOutput.code }),
};
}),
};
diff --git a/frontend/src/core/islands/__tests__/bootstrap.test.ts b/frontend/src/core/islands/__tests__/bootstrap.test.ts
index fb21cf3f2f..9dd765f891 100644
--- a/frontend/src/core/islands/__tests__/bootstrap.test.ts
+++ b/frontend/src/core/islands/__tests__/bootstrap.test.ts
@@ -3,6 +3,8 @@
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";
@@ -48,6 +50,30 @@ 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 0267d9c9f5..5b0fd1e801 100644
--- a/frontend/src/core/islands/bootstrap.ts
+++ b/frontend/src/core/islands/bootstrap.ts
@@ -209,6 +209,7 @@ 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/websocket/__tests__/useMarimoKernelConnection.hook.test.tsx b/frontend/src/core/websocket/__tests__/useMarimoKernelConnection.hook.test.tsx
index 8a1e7b4021..e0ab860511 100644
--- a/frontend/src/core/websocket/__tests__/useMarimoKernelConnection.hook.test.tsx
+++ b/frontend/src/core/websocket/__tests__/useMarimoKernelConnection.hook.test.tsx
@@ -43,6 +43,11 @@ vi.mock("@/core/runtime/config", async () => {
import { MockNotebook } from "@/__mocks__/notebook";
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";
@@ -184,6 +189,46 @@ describe("useMarimoKernelConnection.reconnect()", () => {
});
describe("useMarimoKernelConnection messages", () => {
+ it("replaces attachment snapshots, including the last detach", () => {
+ const store = createStore();
+ vi.mocked(useConnectionTransport).mockReturnValue(
+ makeTransport(WebSocket.OPEN),
+ );
+ vi.mocked(useRuntimeManager).mockReturnValue(
+ makeRuntimeManager() as unknown as ReturnType<typeof useRuntimeManager>,
+ );
+ renderConnectionHook(store);
+ const options = vi.mocked(useConnectionTransport).mock.calls.at(-1)![0];
+ 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], []]) {
+ act(() =>
+ options.onMessage(
+ new MessageEvent("message", {
+ data: JSON.stringify({
+ op: "attachments",
+ data: { op: "attachments", attachments },
+ }),
+ }),
+ ),
+ );
+ expect(store.get(attachmentsAtom)).toEqual(attachments);
+ }
+ });
+
it("records completion of the initial run", () => {
const store = createStore();
vi.mocked(useConnectionTransport).mockClear();
@@ -211,6 +256,101 @@ describe("useMarimoKernelConnection messages", () => {
});
});
+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(useConnectionTransport).mockReturnValue(transport);
+ vi.mocked(useRuntimeManager).mockReturnValue(
+ makeRuntimeManager() as unknown as ReturnType<typeof useRuntimeManager>,
+ );
+ renderConnectionHook(store);
+ const options = vi.mocked(useConnectionTransport).mock.calls.at(-1)![0];
+ 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(["kernel-ready", "reconnected"])(
"waits for %s before marking the session connected",
async (op) => {
@@ -261,6 +401,59 @@ it.each(["kernel-ready", "reconnected"])(
},
);
+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(useConnectionTransport).mockReturnValue(
+ makeTransport(WebSocket.OPEN),
+ );
+ vi.mocked(useRuntimeManager).mockReturnValue(
+ makeRuntimeManager() as unknown as ReturnType<typeof useRuntimeManager>,
+ );
+ renderConnectionHook(store);
+ const options = vi.mocked(useConnectionTransport).mock.calls.at(-1)![0];
+ 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/useMarimoKernelConnection.tsx b/frontend/src/core/websocket/useMarimoKernelConnection.tsx
index 1897378eb4..07e6fcb356 100644
--- a/frontend/src/core/websocket/useMarimoKernelConnection.tsx
+++ b/frontend/src/core/websocket/useMarimoKernelConnection.tsx
@@ -5,6 +5,7 @@ import { useAtom, useAtomValue, useSetAtom } from "jotai";
import { useRef } 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";
@@ -236,6 +237,7 @@ export function useMarimoKernelConnection(opts: {
} = useAlertActions();
const setKioskMode = useSetAtom(kioskModeAtom);
const setStableSessionId = useSetAtom(stableSessionIdAtom);
+ const setAttachments = useSetAtom(attachmentsAtom);
const setCapabilities = useSetAtom(capabilitiesAtom);
const runtimeManager = useRuntimeManager();
const transportType = useAtomValue(connectionTransportTypeAtom);
@@ -252,6 +254,9 @@ export function useMarimoKernelConnection(opts: {
case "reload":
reloadSafe();
return;
+ case "attachments":
+ setAttachments(msg.data.attachments);
+ return;
case "startup-progress": {
const { phase } = msg.data;
updateStartupProgress(msg.data);
@@ -283,6 +288,7 @@ export function useMarimoKernelConnection(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.
@@ -561,6 +567,7 @@ export function useMarimoKernelConnection(opts: {
*/
onOpen: async () => {
updateStartupProgress(null);
+ setAttachments([]);
// If we are open, we can reset our reconnecting flag.
shouldTryReconnecting.current = true;
},
@@ -603,6 +610,7 @@ export function useMarimoKernelConnection(opts: {
*/
onClose: (e) => {
Logger.warn("WebSocket closed", e.code, e.reason);
+ setAttachments([]);
const decision = classifyCloseEvent(e);
setConnection((previous) => {
const status = decision.status;
@@ -641,6 +649,7 @@ export function useMarimoKernelConnection(opts: {
*/
onError: (e) => {
Logger.warn("WebSocket error", e);
+ setAttachments([]);
setConnection({
state: ConnectionState.CLOSED,
code: WebSocketClosedReason.KERNEL_DISCONNECTED,
diff --git a/marimo/_cli/pair/commands.py b/marimo/_cli/pair/commands.py
index d0edc349cd..1fe8290b8f 100644
--- a/marimo/_cli/pair/commands.py
+++ b/marimo/_cli/pair/commands.py
@@ -29,7 +29,7 @@ from marimo._cli.pair.client import (
)
from marimo._cli.pair.prompts import render_prompt
from marimo._server.ai.skills import utils as skills_utils
-from marimo._utils.env import is_env_true
+from marimo._utils.env import pair_preview_enabled
SKILL_NAME = "marimo-pair"
SKILL_FILE = "SKILL.md"
@@ -652,7 +652,7 @@ def prompt(
# With an auth token
claude "$(uvx marimo@latest pair prompt --url 'https://localhost:8000' --claude --with-token)"
"""
- preview = is_env_true("MARIMO_PAIR_NEXT")
+ preview = pair_preview_enabled()
if not preview:
selected_agents = {
"claude": claude,
diff --git a/marimo/_code_mode/_context.py b/marimo/_code_mode/_context.py
index ab19fb77e9..de6b0521da 100644
--- a/marimo/_code_mode/_context.py
+++ b/marimo/_code_mode/_context.py
@@ -1823,7 +1823,10 @@ class AsyncCodeModeContext:
for cell_id, cfg in resolved_configs.items():
if cell_id in self.graph.cells:
self.graph.cells[cell_id].configure(cfg.asdict())
- self._kernel.cell_metadata[cell_id] = CellMetadata(config=cfg)
+ metadata = self._kernel.cell_metadata.setdefault(
+ cell_id, CellMetadata()
+ )
+ metadata.config = cfg
# Build document transaction ops from the plan and broadcast
# a single NotebookDocumentTransactionNotification.
diff --git a/marimo/_core/notebook.py b/marimo/_core/notebook.py
index 6615010edd..3a1456a893 100644
--- a/marimo/_core/notebook.py
+++ b/marimo/_core/notebook.py
@@ -463,6 +463,11 @@ class Notebook:
# ---- attachments ---------------------------------------------------
+ @property
+ def attachments(self) -> list[protocol.Attachment]:
+ """Return the current attachments in creation order."""
+ return list(self._attachments.values())
+
def attach(
self,
*,
diff --git a/marimo/_export/exporter.py b/marimo/_export/exporter.py
index f8a2313b6c..f2c2f8df4d 100644
--- a/marimo/_export/exporter.py
+++ b/marimo/_export/exporter.py
@@ -291,6 +291,8 @@ class Exporter:
nb_cell["name"] = DEFAULT_CELL_NAME
for snapshot_cell in session_snapshot["cells"]:
snapshot_cell["console"] = []
+ for output in snapshot_cell["outputs"]:
+ output.pop("code", None)
return ""
return app_code
diff --git a/marimo/_messaging/cell_output.py b/marimo/_messaging/cell_output.py
index 944fe7aeaa..202fc78dbe 100644
--- a/marimo/_messaging/cell_output.py
+++ b/marimo/_messaging/cell_output.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import time
from enum import Enum
-from typing import Any
+from typing import Any, Literal
import msgspec
@@ -35,6 +35,12 @@ class CellOutput(msgspec.Struct):
mimetype: KnownMimeType
data: str | list[Error] | dict[str, Any]
timestamp: float = msgspec.field(default_factory=lambda: time.time())
+ # Source code associated with this output, omitted when unavailable.
+ code: str | msgspec.UnsetType = msgspec.UNSET
+ # Traceback MIME data can be plain text in code-mode requests.
+ traceback_format: Literal["text", "html"] | msgspec.UnsetType = (
+ msgspec.UNSET
+ )
def __repr__(self) -> str:
return f"CellOutput(channel={self.channel}, mimetype={self.mimetype}, timestamp={self.timestamp})"
@@ -54,12 +60,16 @@ class CellOutput(msgspec.Struct):
@staticmethod
def stderr(
- data: str, mimetype: ConsoleMimeType = "text/plain"
+ data: str,
+ mimetype: ConsoleMimeType = "text/plain",
+ *,
+ code: str | msgspec.UnsetType = msgspec.UNSET,
) -> CellOutput:
return CellOutput(
channel=CellChannel.STDERR,
mimetype=mimetype,
data=data,
+ code=code,
)
@staticmethod
@@ -79,9 +89,12 @@ class CellOutput(msgspec.Struct):
)
@staticmethod
- def errors(data: list[Error]) -> CellOutput:
+ def errors(
+ data: list[Error], *, code: str | msgspec.UnsetType = msgspec.UNSET
+ ) -> CellOutput:
return CellOutput(
channel=CellChannel.MARIMO_ERROR,
mimetype="application/vnd.marimo+error",
data=data,
+ code=code,
)
diff --git a/marimo/_messaging/console_output_worker.py b/marimo/_messaging/console_output_worker.py
index 7345e15048..5d02b5d9bc 100644
--- a/marimo/_messaging/console_output_worker.py
+++ b/marimo/_messaging/console_output_worker.py
@@ -6,6 +6,8 @@ import time
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Literal
+import msgspec
+
from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._messaging.context import RUN_ID_CTX, execution_id_for
from marimo._messaging.mimetypes import ConsoleMimeType
@@ -31,6 +33,7 @@ class ConsoleMsg:
mimetype: ConsoleMimeType
run_id: str | None = field(default_factory=lambda: RUN_ID_CTX.get(None))
execution_id: str | None = None
+ code: str | None = None
def __post_init__(self) -> None:
if self.execution_id is None:
@@ -52,6 +55,7 @@ def _write_console_output(
mimetype: ConsoleMimeType,
run_id: str | None = None,
execution_id: str | None = None,
+ code: str | None = None,
) -> None:
from marimo._messaging.notification import CellNotification
from marimo._messaging.notification_utils import broadcast_notification
@@ -65,6 +69,7 @@ def _write_console_output(
channel=stream_type,
mimetype=mimetype,
data=data,
+ code=code if code is not None else msgspec.UNSET,
),
),
stream,
@@ -77,6 +82,7 @@ def _can_merge_outputs(first: ConsoleMsg, second: ConsoleMsg) -> bool:
and first.mimetype == second.mimetype
and first.run_id == second.run_id
and first.execution_id == second.execution_id
+ and first.code == second.code
)
@@ -108,6 +114,7 @@ def _flush_outputs(
output.mimetype,
output.run_id,
output.execution_id,
+ output.code,
)
outputs_buffered_per_cell.clear()
diff --git a/marimo/_messaging/messages.py b/marimo/_messaging/messages.py
new file mode 100644
index 0000000000..29ed2ccde5
--- /dev/null
+++ b/marimo/_messaging/messages.py
@@ -0,0 +1,4 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+AGENT_MESSAGE_TYPE = "marimo.pair.agent-message"
diff --git a/marimo/_messaging/notification.py b/marimo/_messaging/notification.py
index 5f31cb422a..fb1d130bf4 100644
--- a/marimo/_messaging/notification.py
+++ b/marimo/_messaging/notification.py
@@ -17,6 +17,7 @@ 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,
@@ -103,6 +104,17 @@ 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.
@@ -1162,4 +1174,5 @@ NotificationMessage = (
| NotebookDocumentTransactionNotification
# Consumer
| ConsumerCapabilitiesNotification
+ | AttachmentsNotification
)
diff --git a/marimo/_messaging/notification_utils.py b/marimo/_messaging/notification_utils.py
index d2e79fbf06..803c8abe0e 100644
--- a/marimo/_messaging/notification_utils.py
+++ b/marimo/_messaging/notification_utils.py
@@ -10,6 +10,8 @@ import sys
from typing import TYPE_CHECKING
from uuid import uuid4
+import msgspec
+
from marimo import _loggers as loggers
from marimo._messaging.cell_output import CellOutput
from marimo._messaging.errors import (
@@ -218,6 +220,7 @@ class CellNotificationUtils:
clear_console: bool,
cell_id: CellId_t,
execution_id: str | None = None,
+ code: str | None = None,
) -> None:
# Import here to avoid circular dependency
from marimo._messaging.notification import CellNotification
@@ -265,7 +268,12 @@ class CellNotificationUtils:
broadcast_notification(
CellNotification(
cell_id=cell_id,
- output=CellOutput.errors(safe_errors),
+ output=CellOutput.errors(
+ safe_errors,
+ code=code
+ if code is not None and get_mode() == "edit"
+ else msgspec.UNSET,
+ ),
console=console,
status=None,
execution_id=execution_id,
diff --git a/marimo/_messaging/streams.py b/marimo/_messaging/streams.py
index 96fa20373e..84b5510737 100644
--- a/marimo/_messaging/streams.py
+++ b/marimo/_messaging/streams.py
@@ -394,7 +394,11 @@ class ThreadSafeStderr(Stderr):
self._stream.flush_console()
def _write_with_mimetype(
- self, data: str, mimetype: ConsoleMimeType
+ self,
+ data: str,
+ mimetype: ConsoleMimeType,
+ *,
+ code: str | None = None,
) -> int:
assert self._stream.cell_id is not None
if not isinstance(data, str):
@@ -416,6 +420,7 @@ class ThreadSafeStderr(Stderr):
cell_id=self._stream.cell_id,
data=data,
mimetype=mimetype,
+ code=code,
)
)
self._stream.console_msg_cv.notify()
diff --git a/marimo/_messaging/tracebacks.py b/marimo/_messaging/tracebacks.py
index 46c2d52e59..06db987bdb 100644
--- a/marimo/_messaging/tracebacks.py
+++ b/marimo/_messaging/tracebacks.py
@@ -4,6 +4,8 @@ from __future__ import annotations
import sys
import traceback as tb
+import msgspec
+
from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._messaging.context import is_code_mode_request
from marimo._messaging.notification import CellNotification
@@ -42,9 +44,12 @@ def _show_tracebacks_enabled() -> bool:
return True # no context → not in run mode, always show
-def write_traceback(traceback: str) -> None:
+def write_traceback(traceback: str, *, code: str | None = None) -> None:
in_run_mode = get_mode() == "run"
+ if in_run_mode:
+ code = None
code_mode = is_code_mode_request()
+ ctx = safe_get_context()
if isinstance(sys.stderr, Stderr) and not code_mode:
# In run mode, only forward to the frontend if show_tracebacks is on.
@@ -53,11 +58,11 @@ def write_traceback(traceback: str) -> None:
sys.stderr._write_with_mimetype(
_highlight_traceback(traceback),
mimetype="application/vnd.marimo+traceback",
+ code=code,
)
else:
# When stderr is not redirected (e.g., run mode with redirect_console_to_browser=False),
# send the traceback directly via the stream to ensure exceptions reach the frontend
- ctx = safe_get_context()
if ctx is not None and ctx.cell_id is not None:
# In run mode, only forward to the frontend if show_tracebacks is on.
if in_run_mode and not _show_tracebacks_enabled():
@@ -72,6 +77,8 @@ def write_traceback(traceback: str) -> None:
data=traceback
if code_mode
else _highlight_traceback(traceback),
+ code=code if code is not None else msgspec.UNSET,
+ traceback_format="text" if code_mode else "html",
),
),
ctx.stream,
diff --git a/marimo/_messaging/types.py b/marimo/_messaging/types.py
index 112660fddd..90bd1b2e68 100644
--- a/marimo/_messaging/types.py
+++ b/marimo/_messaging/types.py
@@ -92,9 +92,13 @@ class Stderr(io.TextIOBase, abc.ABC):
@abc.abstractmethod
def _write_with_mimetype(
- self, data: str, mimetype: ConsoleMimeType
+ self,
+ data: str,
+ mimetype: ConsoleMimeType,
+ *,
+ code: str | None = None,
) -> int:
- pass
+ """Write console output, optionally tagged with the source it came from."""
def write(self, s: str, /) -> int:
return self._write_with_mimetype(
diff --git a/marimo/_pyodide/streams.py b/marimo/_pyodide/streams.py
index a6de363ba1..f934a3c8d6 100644
--- a/marimo/_pyodide/streams.py
+++ b/marimo/_pyodide/streams.py
@@ -5,6 +5,8 @@ import asyncio
import sys
from typing import TYPE_CHECKING
+import msgspec
+
from marimo import _loggers
from marimo._messaging.cell_output import CellOutput
from marimo._messaging.mimetypes import ConsoleMimeType
@@ -114,7 +116,11 @@ class PyodideStderr(Stderr):
return False
def _write_with_mimetype(
- self, data: str, mimetype: ConsoleMimeType
+ self,
+ data: str,
+ mimetype: ConsoleMimeType,
+ *,
+ code: str | None = None,
) -> int:
assert self.stream.cell_id is not None
if not isinstance(data, str):
@@ -132,7 +138,11 @@ class PyodideStderr(Stderr):
broadcast_notification(
CellNotification(
cell_id=self.stream.cell_id,
- console=CellOutput.stderr(data, mimetype),
+ console=CellOutput.stderr(
+ data,
+ mimetype,
+ code=code if code is not None else msgspec.UNSET,
+ ),
),
self.stream,
)
diff --git a/marimo/_runtime/runner/cell_runner.py b/marimo/_runtime/runner/cell_runner.py
index b524ce42e2..6bda79b641 100644
--- a/marimo/_runtime/runner/cell_runner.py
+++ b/marimo/_runtime/runner/cell_runner.py
@@ -25,9 +25,10 @@ from marimo._messaging.errors import (
)
from marimo._messaging.notification import InterruptedNotification
from marimo._messaging.notification_utils import broadcast_notification
-from marimo._messaging.tracebacks import write_traceback
+from marimo._messaging.tracebacks import _highlight_traceback, write_traceback
from marimo._runtime import dataflow
from marimo._runtime.context.types import safe_get_context
+from marimo._runtime.context.utils import get_mode
from marimo._runtime.control_flow import MarimoInterrupt, MarimoStopError
from marimo._runtime.exceptions import (
MarimoMissingRefError,
@@ -522,6 +523,14 @@ class Runner:
elif isinstance(unwrapped_exception, MarimoStopError):
output = unwrapped_exception.output
exception = unwrapped_exception
+ if (
+ isinstance(exception, MarimoExceptionRaisedError)
+ and unwrapped_exception is not None
+ and get_mode() == "edit"
+ ):
+ exception.traceback = _highlight_traceback(
+ "".join(traceback.format_exception(unwrapped_exception))
+ )
return RunResult(
output=output, exception=exception
), unwrapped_exception
@@ -565,7 +574,7 @@ class Runner:
raise raw_result.exception
try:
- run_result = self._finalize_run_result(raw_result, cell_id)
+ run_result = self._finalize_run_result(raw_result, cell)
except BaseException as exc:
unexpected_failure = exc
run_result = RunResult(output=None, exception=None)
@@ -600,9 +609,10 @@ class Runner:
return run_result
def _finalize_run_result(
- self, raw_result: RunResult, cell_id: CellId_t
+ self, raw_result: RunResult, cell: CellImpl
) -> RunResult:
"""Classify the Evaluator's RunResult and apply Runner side effects."""
+ cell_id = cell.cell_id
exc = raw_result.exception
if exc is None:
return raw_result
@@ -622,7 +632,7 @@ class Runner:
type(exc), exc, exc.__traceback__, file=tmpio
)
tmpio.seek(0)
- write_traceback(tmpio.read())
+ write_traceback(tmpio.read(), code=cell.code)
return RunResult(output=None, exception=MarimoInterrupt())
# Should cover all cell runtime exceptions.
@@ -677,7 +687,7 @@ class Runner:
file=tmpio,
)
tmpio.seek(0)
- write_traceback(tmpio.read())
+ write_traceback(tmpio.read(), code=cell.code)
return run_result
# Anything else escaping the Evaluator is unexpected.
@@ -688,7 +698,7 @@ class Runner:
type(exc), exc, exc.__traceback__, file=tmpio
)
tmpio.seek(0)
- write_traceback(tmpio.read())
+ write_traceback(tmpio.read(), code=cell.code)
return RunResult(output=None, exception=UnknownError(f"{exc}"))
def _update_debugger_state(
diff --git a/marimo/_runtime/runner/hooks_on_finish.py b/marimo/_runtime/runner/hooks_on_finish.py
index 862dac1493..9229354a71 100644
--- a/marimo/_runtime/runner/hooks_on_finish.py
+++ b/marimo/_runtime/runner/hooks_on_finish.py
@@ -34,6 +34,7 @@ def _send_interrupt_errors(ctx: OnFinishHookContext) -> None:
clear_console=True,
cell_id=cid,
execution_id=ctx.execution_ids.get(cid),
+ code=ctx.graph.cells[cid].code,
)
@@ -85,6 +86,7 @@ def _send_cancellation_errors(ctx: OnFinishHookContext) -> None:
clear_console=True,
cell_id=cid,
execution_id=ctx.execution_ids.get(cid),
+ code=cell.code,
)
diff --git a/marimo/_runtime/runner/hooks_post_execution.py b/marimo/_runtime/runner/hooks_post_execution.py
index f0b71a46fd..43251befa7 100644
--- a/marimo/_runtime/runner/hooks_post_execution.py
+++ b/marimo/_runtime/runner/hooks_post_execution.py
@@ -45,6 +45,7 @@ from marimo._runtime.context.types import (
get_context,
get_global_context,
)
+from marimo._runtime.context.utils import get_mode
from marimo._runtime.control_flow import MarimoInterrupt, MarimoStopError
from marimo._runtime.runner import cell_runner
from marimo._runtime.runner.hook_context import PostExecutionHookContext
@@ -364,7 +365,7 @@ def _broadcast_outputs(
):
ctx.exceptions[cell.cell_id] = formatted_output.exception
if formatted_output.traceback is not None:
- write_traceback(formatted_output.traceback)
+ write_traceback(formatted_output.traceback, code=cell.code)
CellNotificationUtils.broadcast_output(
channel=CellChannel.OUTPUT,
@@ -380,6 +381,7 @@ def _broadcast_outputs(
data=[run_result.output],
clear_console=True,
cell_id=cell.cell_id,
+ code=cell.code,
)
elif isinstance(run_result.exception, MarimoInterrupt):
LOGGER.debug("Cell %s was interrupted", cell.cell_id)
@@ -389,12 +391,14 @@ def _broadcast_outputs(
data=[MarimoInterruptionError()],
clear_console=False,
cell_id=cell.cell_id,
+ code=cell.code,
)
elif isinstance(run_result.exception, MarimoExceptionRaisedError):
CellNotificationUtils.broadcast_error(
data=[run_result.exception],
clear_console=False,
cell_id=cell.cell_id,
+ code=cell.code,
)
elif isinstance(run_result.exception, MarimoSQLError):
LOGGER.debug("Cell %s raised a SQL error", cell.cell_id)
@@ -402,6 +406,7 @@ def _broadcast_outputs(
data=[run_result.exception],
clear_console=True,
cell_id=cell.cell_id,
+ code=cell.code,
)
elif run_result.exception is not None:
LOGGER.debug(
@@ -419,11 +424,10 @@ def _broadcast_outputs(
if not msg:
msg = f"This cell raised an exception: {exception_type}"
- # Include formatted traceback if enabled in config
formatted_traceback = None
- show_tracebacks = False
+ show_tracebacks = get_mode() == "edit"
if ctx.user_config is not None:
- show_tracebacks = bool(
+ show_tracebacks = show_tracebacks or bool(
ctx.user_config["runtime"].get("show_tracebacks", False)
)
@@ -445,6 +449,7 @@ def _broadcast_outputs(
],
clear_console=False,
cell_id=cell.cell_id,
+ code=cell.code,
)
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 86f237b7b9..fc6680b940 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -449,6 +449,8 @@ class CellMetadata:
"""
config: CellConfig = dataclasses.field(default_factory=CellConfig)
+ # Retain validated source even when a syntax error prevents registration.
+ code: str | None = None
def _get_attached_catalogs() -> set[str]:
@@ -874,6 +876,7 @@ class Kernel:
cell.configure(self.cell_metadata[cell_id].config)
elif cell_id not in self.cell_metadata:
self.cell_metadata[cell_id] = CellMetadata()
+ self.cell_metadata[cell_id].code = cell.code
self.graph.register_cell(cell_id, cell)
if stale:
@@ -1255,6 +1258,9 @@ class Kernel:
pending = self._uninstantiated_execution_requests.pop(
er.cell_id, None
)
+ self.cell_metadata.setdefault(
+ er.cell_id, CellMetadata()
+ ).code = er.code
old_children, error = self._maybe_register_cell(
er.cell_id,
er.code,
@@ -1400,7 +1406,10 @@ class Kernel:
)
with execution.activate():
CellNotificationUtils.broadcast_error(
- data=self.errors[cid], clear_console=True, cell_id=cid
+ data=self.errors[cid],
+ clear_console=True,
+ cell_id=cid,
+ code=self.cell_metadata[cid].code,
)
execution.finish()
@@ -1833,6 +1842,7 @@ class Kernel:
data=[MarimoInterruptionError()],
clear_console=False,
cell_id=request.cell_id,
+ code=request.code,
)
# TODO(akshayka): This hack is needed because the FE
@@ -1907,6 +1917,7 @@ class Kernel:
data=[error],
clear_console=False,
cell_id=SCRATCH_CELL_ID,
+ code=code,
)
CellNotificationUtils.broadcast_status(
cell_id=SCRATCH_CELL_ID,
@@ -1991,10 +2002,11 @@ class Kernel:
"""Apply cell configs and return the stale cells they enabled."""
stale_cells: set[CellId_t] = set()
for cell_id, config in configs.items():
- previous = self.cell_metadata.get(cell_id, CellMetadata()).config
+ metadata = self.cell_metadata.setdefault(cell_id, CellMetadata())
+ previous = metadata.config
merged = CellConfig.from_dict(previous.asdict())
merged.configure(config)
- self.cell_metadata[cell_id] = CellMetadata(config=merged)
+ metadata.config = merged
cell = self.graph.cells.get(cell_id)
if cell is None:
continue
diff --git a/marimo/_schemas/generated/notifications.yaml b/marimo/_schemas/generated/notifications.yaml
index b0e4cb6f41..5222a8df16 100644
--- a/marimo/_schemas/generated/notifications.yaml
+++ b/marimo/_schemas/generated/notifications.yaml
@@ -196,6 +196,8 @@ components:
properties:
channel:
$ref: '#/components/schemas/CellChannel'
+ code:
+ type: string
data:
anyOf:
- type: string
@@ -260,6 +262,10 @@ components:
- video/mpeg
timestamp:
type: number
+ traceback_format:
+ enum:
+ - html
+ - text
required:
- channel
- mimetype
diff --git a/marimo/_schemas/generated/session.yaml b/marimo/_schemas/generated/session.yaml
index 82fd56459d..c8c3f59d67 100644
--- a/marimo/_schemas/generated/session.yaml
+++ b/marimo/_schemas/generated/session.yaml
@@ -28,6 +28,8 @@ components:
type: object
DataOutput:
properties:
+ code:
+ type: string
data:
additionalProperties: {}
type: object
@@ -41,6 +43,8 @@ components:
type: object
ErrorOutput:
properties:
+ code:
+ type: string
ename:
type: string
evalue:
@@ -88,6 +92,8 @@ components:
type: object
StreamMediaOutput:
properties:
+ code:
+ type: string
data:
type: string
mimetype:
@@ -121,6 +127,11 @@ components:
enum:
- media
type: string
+ traceback_format:
+ enum:
+ - text
+ - html
+ type: string
type:
enum:
- streamMedia
@@ -133,6 +144,8 @@ components:
type: object
StreamOutput:
properties:
+ code:
+ type: string
mimetype:
enum:
- application/json
@@ -168,6 +181,11 @@ components:
type: string
text:
type: string
+ traceback_format:
+ enum:
+ - text
+ - html
+ type: string
type:
enum:
- stream
diff --git a/marimo/_schemas/session.py b/marimo/_schemas/session.py
index be91d74716..0e02e54488 100644
--- a/marimo/_schemas/session.py
+++ b/marimo/_schemas/session.py
@@ -10,8 +10,14 @@ It may be externally used and must be kept backwards compatible.
from __future__ import annotations
+import sys
from typing import Any, Literal
+if sys.version_info >= (3, 11):
+ from typing import NotRequired
+else:
+ from typing_extensions import NotRequired
+
from marimo._messaging.mimetypes import KnownMimeType
from marimo._schemas.common import BaseDict
@@ -31,6 +37,8 @@ class StreamOutput(BaseDict):
name: Literal["stdout", "stderr"]
text: str
mimetype: KnownMimeType | None
+ code: NotRequired[str]
+ traceback_format: NotRequired[Literal["text", "html"]]
class StreamMediaOutput(BaseDict):
@@ -38,6 +46,8 @@ class StreamMediaOutput(BaseDict):
name: Literal["media"]
data: str
mimetype: KnownMimeType
+ code: NotRequired[str]
+ traceback_format: NotRequired[Literal["text", "html"]]
class ErrorOutput(BaseDict):
@@ -45,11 +55,13 @@ class ErrorOutput(BaseDict):
ename: str
evalue: str
traceback: list[str]
+ code: NotRequired[str]
class DataOutput(BaseDict):
type: Literal["data"]
data: dict[str, Any] # MIME-type bundles
+ code: NotRequired[str]
# Union of all possible output types
@@ -67,8 +79,8 @@ class Cell(BaseDict):
outputs: list[OutputType]
console: list[ConsoleType]
- # We don't need to store code or cell config
- # since that exists in the notebook.py itself
+ # Cell code and configuration live in notebook.py. An output can retain
+ # the source that produced it even after the notebook code changes.
# Notebook session metadata
diff --git a/marimo/_server/api/deps.py b/marimo/_server/api/deps.py
index 3cd6f78669..90d57e1f52 100644
--- a/marimo/_server/api/deps.py
+++ b/marimo/_server/api/deps.py
@@ -11,6 +11,7 @@ from marimo._server.session_manager import SessionManager
from marimo._server.tokens import SkewProtectionToken
from marimo._session.model import SessionMode
from marimo._types.ids import SessionId, StableSessionId
+from marimo._utils.env import pair_preview_enabled
from marimo._utils.http import HTTPException, HTTPStatus
if TYPE_CHECKING:
@@ -20,6 +21,8 @@ if TYPE_CHECKING:
from starlette.websockets import WebSocket
from uvicorn import Server
+ from marimo._core.notebook import Notebook
+ from marimo._server.host.context import HostContext
from marimo._session import Session
LOGGER = loggers.marimo_logger()
@@ -48,6 +51,28 @@ class AppStateBase:
def session_manager(self) -> SessionManager:
return self.state.session_manager
+ @property
+ def host_context(self) -> HostContext | None:
+ return getattr(self.state, "host_context", None)
+
+ def notebook_for_session(self, session: Session) -> Notebook | None:
+ """Return the host notebook for an edit session, if available."""
+ context = self.host_context
+ return (
+ None
+ if context is None
+ else context.bridge.notebook_for_session(session)
+ )
+
+ def session_for_notebook(self, notebook_id: str) -> Session | None:
+ """Return the current session for a host notebook, if available."""
+ context = self.host_context
+ return (
+ None
+ if context is None
+ else context.bridge.session_for_notebook(notebook_id)
+ )
+
@property
def mode(self) -> SessionMode:
return self.session_manager.mode
@@ -187,13 +212,26 @@ class AppState(AppStateBase):
),
)
+ return self.session_by_stable_id(stable_session_id)
+
+ def require_pair_preview(self) -> None:
+ """Reject Pair routes when the preview is disabled."""
+ if not pair_preview_enabled():
+ raise HTTPException(status_code=HTTPStatus.NOT_FOUND)
+
+ def session_by_stable_id(self, stable_id: str) -> Session:
+ """Resolve a notebook's stable session ID.
+
+ Args:
+ stable_id (str): Stable session ID from the route.
+ """
session = self.session_manager.get_session_by_stable_id(
- StableSessionId(stable_session_id)
+ StableSessionId(stable_id)
)
if session is None:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND,
- detail=f"Invalid stable session id: {stable_session_id}",
+ detail=f"Invalid stable session id: {stable_id}",
)
return session
diff --git a/marimo/_server/api/endpoints/execution.py b/marimo/_server/api/endpoints/execution.py
index 2df355d498..85832fd65f 100644
--- a/marimo/_server/api/endpoints/execution.py
+++ b/marimo/_server/api/endpoints/execution.py
@@ -9,11 +9,6 @@ from starlette.authentication import requires
from starlette.responses import JSONResponse, StreamingResponse
from marimo import _loggers
-from marimo._code_mode.screenshot_meta import (
- SCREENSHOT_AUTH_TOKEN_KEY,
- SCREENSHOT_FILE_KEY,
- SCREENSHOT_SERVER_URL_KEY,
-)
from marimo._runtime.commands import HTTPRequest, UpdateUIElementCommand
from marimo._server.api.deps import AppState
from marimo._server.api.endpoints.ws.ws_connection_validator import (
@@ -332,6 +327,7 @@ async def execute_code(
from marimo._server.scratchpad import (
ScratchCellListener,
build_done_event,
+ build_scratchpad_request,
snapshot_for_scratchpad,
)
@@ -378,15 +374,14 @@ async def execute_code(
# listener. See #10035.
async with session.scratchpad_lock:
with session.scoped(listener):
- http_req = HTTPRequest.from_request(request)
server_url, auth_token = get_code_mode_credentials(
app_state, request
)
- http_req.meta[SCREENSHOT_SERVER_URL_KEY] = server_url
- http_req.meta[SCREENSHOT_AUTH_TOKEN_KEY] = auth_token
- http_req.meta[SCREENSHOT_FILE_KEY] = (
- session.app_file_manager.path
- or session.initialization_id
+ http_req = build_scratchpad_request(
+ session,
+ request,
+ server_url=server_url,
+ auth_token=auth_token,
)
notebook_cells, cell_outputs = snapshot_for_scratchpad(
session
diff --git a/marimo/_server/api/endpoints/health.py b/marimo/_server/api/endpoints/health.py
index 67494beab9..fa2b48fa13 100644
--- a/marimo/_server/api/endpoints/health.py
+++ b/marimo/_server/api/endpoints/health.py
@@ -98,6 +98,7 @@ async def status(request: Request) -> JSONResponse:
class SessionInfo(TypedDict):
session_id: StableSessionId
+ notebook_id: str | None
filename: str | None
path: str | None
@@ -112,6 +113,12 @@ async def list_sessions(request: Request) -> JSONResponse:
sessions = {
session_id: SessionInfo(
session_id=session.stable_id,
+ notebook_id=(
+ notebook.id
+ if (notebook := state.notebook_for_session(session))
+ is not None
+ else None
+ ),
filename=session.app_file_manager.filename,
path=session.app_file_manager.path,
)
diff --git a/marimo/_server/api/endpoints/pair.py b/marimo/_server/api/endpoints/pair.py
new file mode 100644
index 0000000000..90563f0cd6
--- /dev/null
+++ b/marimo/_server/api/endpoints/pair.py
@@ -0,0 +1,70 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+import msgspec
+from starlette.authentication import requires
+from starlette.responses import Response
+
+from marimo._messaging.messages import AGENT_MESSAGE_TYPE
+from marimo._server.api.deps import AppState
+from marimo._server.router import APIRouter
+from marimo._utils.http import HTTPException, HTTPStatus
+
+if TYPE_CHECKING:
+ from starlette.requests import Request
+
+pair_router = APIRouter()
+
+
+@pair_router.post("/notebooks/{id}/messages", include_in_schema=False)
+@requires("edit")
+async def messages(request: Request) -> Response:
+ """Send any JSON content to all agents attached to the notebook."""
+ state = AppState(request)
+ state.require_pair_preview()
+ session = state.session_by_stable_id(request.path_params["id"])
+ try:
+ payload = msgspec.json.decode(await request.body())
+ except msgspec.DecodeError as error:
+ raise HTTPException(
+ status_code=HTTPStatus.BAD_REQUEST,
+ detail="Invalid JSON agent message payload.",
+ ) from error
+
+ notebook = state.notebook_for_session(session)
+ if notebook is None or not any(
+ a.kind == "agent" for a in notebook.attachments
+ ):
+ raise HTTPException(status_code=409, detail="No agent attached")
+ notebook.emit(AGENT_MESSAGE_TYPE, payload)
+ return Response(status_code=202)
+
+
+class DetachRequest(msgspec.Struct):
+ attachment_id: str
+
+
+@pair_router.post(
+ "/notebooks/{id}/attachments/detach", include_in_schema=False
+)
+@requires("edit")
+async def detach(request: Request) -> Response:
+ """Disconnect one attachment without stopping its notebook runtime."""
+ state = AppState(request)
+ state.require_pair_preview()
+ session = state.session_by_stable_id(request.path_params["id"])
+ try:
+ body = msgspec.json.decode(await request.body(), type=DetachRequest)
+ if not body.attachment_id:
+ raise ValueError("Empty attachment ID")
+ except (msgspec.DecodeError, ValueError) as error:
+ raise HTTPException(
+ status_code=HTTPStatus.BAD_REQUEST,
+ detail="Invalid attachment ID.",
+ ) from error
+ notebook = state.notebook_for_session(session)
+ if notebook is not None:
+ notebook.detach(body.attachment_id)
+ return Response(status_code=204)
diff --git a/marimo/_server/api/endpoints/ws/session_handler.py b/marimo/_server/api/endpoints/ws/session_handler.py
index 70da09d458..8c393c2d4b 100644
--- a/marimo/_server/api/endpoints/ws/session_handler.py
+++ b/marimo/_server/api/endpoints/ws/session_handler.py
@@ -13,6 +13,7 @@ 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,
@@ -24,6 +25,7 @@ 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,
@@ -91,6 +93,7 @@ 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
@@ -148,6 +151,7 @@ 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,
@@ -366,6 +370,16 @@ class SessionHandler(SessionConsumer, abc.ABC):
) -> 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/api/router.py b/marimo/_server/api/router.py
index 6dd0570bd7..8833d46ad8 100644
--- a/marimo/_server/api/router.py
+++ b/marimo/_server/api/router.py
@@ -26,6 +26,7 @@ from marimo._server.api.endpoints.home import router as home_router
from marimo._server.api.endpoints.login import router as login_router
from marimo._server.api.endpoints.lsp import router as lsp_router
from marimo._server.api.endpoints.packages import router as packages_router
+from marimo._server.api.endpoints.pair import pair_router
from marimo._server.api.endpoints.secrets import router as secrets_router
from marimo._server.api.endpoints.sql import router as sql_router
from marimo._server.api.endpoints.storage import router as storage_router
@@ -72,6 +73,7 @@ def build_routes(base_url: str = "") -> list[BaseRoute]:
storage_router, prefix="/api/storage", name="storage"
)
app_router.include_router(ai_router, prefix="/api/ai", name="ai")
+ app_router.include_router(pair_router, prefix="/api/pair", name="pair")
app_router.include_router(home_router, prefix="/api/home", name="home")
app_router.include_router(login_router, prefix="/auth", name="auth")
app_router.include_router(
diff --git a/marimo/_server/host/backend.py b/marimo/_server/host/backend.py
index 9e125806ba..ce0d3247e0 100644
--- a/marimo/_server/host/backend.py
+++ b/marimo/_server/host/backend.py
@@ -19,7 +19,7 @@ from marimo._messaging.notification import (
StartupProgressNotification,
)
from marimo._messaging.serde import deserialize_kernel_message
-from marimo._runtime.commands import ExecuteScratchpadCommand
+from marimo._runtime.commands import ExecuteScratchpadCommand, HTTPRequest
from marimo._runtime.scratch import SCRATCH_CELL_ID
from marimo._server.host.events import notification_event
from marimo._server.host.translate import RunTranslator
@@ -38,6 +38,7 @@ if TYPE_CHECKING:
from marimo._server.session_manager import SessionManager
from marimo._session.events import SessionEventBus
from marimo._session.session import Session
+ from marimo._types.encodable import Encodable
LOGGER = _loggers.marimo_logger()
@@ -47,6 +48,7 @@ _PHASES = {
}
Observe = Callable[[be.Message], None]
+RequestMetadata = Callable[["Session"], dict[str, "Encodable"]]
@dataclass
@@ -84,6 +86,8 @@ class SessionBackend(SessionConsumer):
document_changed: Callable[[], None] | None = None,
session_attached: Callable[[], None] | None = None,
session_detached: Callable[[Session], None] | None = None,
+ *,
+ request_metadata: RequestMetadata | None = None,
) -> None:
self._notebook_id = notebook_id
self._file = file
@@ -97,6 +101,7 @@ class SessionBackend(SessionConsumer):
"""Called with the session attached, before the runtime is reported."""
self._session_detached = session_detached
"""Called with the session that detached, before its exit is reported."""
+ self._request_metadata = request_metadata
self._kernel: _Kernel | None = None
self._run: _Run | None = None
self._translators: dict[str, RunTranslator] = {}
@@ -182,12 +187,34 @@ class SessionBackend(SessionConsumer):
http_request=None,
)
cells, outputs = snapshot_for_scratchpad(session)
+ request = None
+ if self._request_metadata is not None:
+ # Host runs have no HTTP origin. Give the URL fields the same
+ # keys a real request has so notebook code can read them.
+ empty_url: dict[str, Encodable] = {
+ "path": "",
+ "port": None,
+ "scheme": "",
+ "netloc": "",
+ "query": "",
+ "hostname": None,
+ }
+ request = HTTPRequest(
+ url=dict(empty_url),
+ base_url=dict(empty_url),
+ headers={},
+ query_params={},
+ path_params={},
+ cookies={},
+ user={},
+ meta=self._request_metadata(session),
+ )
run.submitted = True
self._translators[run.translator.run_id] = run.translator
session.put_control_request(
ExecuteScratchpadCommand(
code=code,
- request=None,
+ request=request,
notebook_cells=cells,
cell_outputs=outputs,
run_id=run.translator.run_id,
diff --git a/marimo/_server/host/bridge.py b/marimo/_server/host/bridge.py
index 8a4c5f5c8b..8a0359c1d9 100644
--- a/marimo/_server/host/bridge.py
+++ b/marimo/_server/host/bridge.py
@@ -20,10 +20,11 @@ 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
-from marimo._server.host.backend import SessionBackend
+from marimo._server.host.backend import RequestMetadata, SessionBackend
from marimo._server.host.events import notification_event
from marimo._server.host.index import WorkspaceIndex
from marimo._session.events import SessionEventListener
@@ -93,9 +94,12 @@ class SessionBridge(SessionEventListener):
self,
manager: SessionManager,
config_manager: MarimoConfigManager | None = None,
+ *,
+ request_metadata: RequestMetadata | None = None,
) -> None:
self._manager = manager
self._config_manager = config_manager
+ self._request_metadata = request_metadata
self._files_lock = asyncio.Lock()
self._saving: set[protocol.NotebookId] = set()
# TODO(MO-8005): The writer owns this baseline once there is one
@@ -113,7 +117,7 @@ class SessionBridge(SessionEventListener):
self.host, manager.workspace, self._initialize_notebook
)
self._unsubscribe = self.host.subscribe(
- self._forget_backend, types={"notebook"}
+ self._on_host_event, types={"notebook", "attachment"}
)
async def open(self) -> None:
@@ -127,6 +131,19 @@ 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():
+ if backend.session is session:
+ # Adoption loads the notebook before it attaches a session.
+ return self.host.peek_notebook(notebook_id)
+ return None
+
async def refresh(self) -> None:
"""Refresh the catalog without observing a half-finished file move."""
async with self._files_lock:
@@ -654,19 +671,43 @@ class SessionBridge(SessionEventListener):
session_detached=lambda session: self._detach_document(
notebook_id, session
),
+ request_metadata=self._request_metadata,
)
self._backends[notebook_id] = backend
return backend
- def _forget_backend(self, event: RoutedEvent) -> None:
+ def _on_host_event(self, event: RoutedEvent) -> None:
if (
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/marimo/_server/host/lifespan.py b/marimo/_server/host/lifespan.py
index 8af1b900ef..70b58e27c5 100644
--- a/marimo/_server/host/lifespan.py
+++ b/marimo/_server/host/lifespan.py
@@ -11,9 +11,11 @@ from typing import TYPE_CHECKING
from marimo import _loggers
from marimo._config.settings import GLOBAL_SETTINGS
from marimo._server.api.deps import AppStateBase
+from marimo._server.api.utils import format_url_host
from marimo._server.host.bridge import SessionBridge
from marimo._server.host.context import HostContext
from marimo._server.host.record import HostRecordFile, host_url
+from marimo._server.scratchpad import scratchpad_request_metadata
from marimo._session.model import SessionMode
if TYPE_CHECKING:
@@ -32,10 +34,22 @@ async def host(app: Starlette) -> AsyncIterator[None]:
yield
return
- bridge = SessionBridge(state.session_manager, state.config_manager)
+ server = state.server.config
+ url_host = format_url_host(
+ server.host, server.port, route_bind_all_to_loopback=True
+ )
+ server_url = f"http://{url_host}:{server.port}{state.base_url.rstrip('/')}"
+ bridge = SessionBridge(
+ state.session_manager,
+ state.config_manager,
+ request_metadata=lambda session: scratchpad_request_metadata(
+ session,
+ server_url=server_url,
+ auth_token=str(state.session_manager.auth_token),
+ ),
+ )
await bridge.open()
token = secrets.token_urlsafe(32)
- server = state.server.config
url = host_url(server.host, server.port, state.base_url)
context = HostContext(bridge=bridge, token=token, port=server.port)
app.state.host_context = context
diff --git a/marimo/_server/scratchpad.py b/marimo/_server/scratchpad.py
index a933f843f4..1b7427d99d 100644
--- a/marimo/_server/scratchpad.py
+++ b/marimo/_server/scratchpad.py
@@ -36,11 +36,11 @@ if TYPE_CHECKING:
from marimo._messaging.notebook.document import NotebookCell
from marimo._messaging.types import KernelMessage
from marimo._session.session import Session
+ from marimo._types.encodable import Encodable
EXECUTION_TIMEOUT = (
30.0 # seconds — used only by wait(); stream() has no timeout
)
-
# Channel name constants for SSE events
_CHANNEL_MAP = {
CellChannel.STDOUT: "stdout",
@@ -249,6 +249,48 @@ class ScratchCellListener(EventAwareExtension):
# -- Helpers ------------------------------------------------------------------
+def build_scratchpad_request(
+ session: Session,
+ request: Request,
+ *,
+ server_url: str,
+ auth_token: str,
+) -> HTTPRequest:
+ """Build kernel request metadata for scratchpad execution.
+
+ Args:
+ session (Session): Notebook that owns the scratchpad.
+ request (Request): HTTP request to serialize.
+ server_url (str): Trusted URL for screenshot callbacks.
+ auth_token (str): Token for screenshot callbacks.
+ """
+ http_req = HTTPRequest.from_request(request)
+ http_req.meta.update(
+ scratchpad_request_metadata(
+ session, server_url=server_url, auth_token=auth_token
+ )
+ )
+ return http_req
+
+
+def scratchpad_request_metadata(
+ session: Session, *, server_url: str, auth_token: str
+) -> dict[str, Encodable]:
+ """Return server metadata for scratchpad screenshot callbacks.
+
+ Args:
+ session (Session): Session that owns the scratchpad.
+ server_url (str): Trusted URL for screenshot callbacks.
+ auth_token (str): Token for screenshot callbacks.
+ """
+ return {
+ SCREENSHOT_SERVER_URL_KEY: server_url,
+ SCREENSHOT_AUTH_TOKEN_KEY: auth_token,
+ SCREENSHOT_FILE_KEY: session.app_file_manager.path
+ or session.initialization_id,
+ }
+
+
def snapshot_for_scratchpad(
session: Session,
) -> tuple[tuple[NotebookCell, ...], CellOutputs]:
@@ -387,11 +429,8 @@ async def run_scratchpad_code(
timeout: float = EXECUTION_TIMEOUT,
) -> CodeExecutionResult:
"""Drive the kernel scratchpad on behalf of code-mode"""
- http_req = HTTPRequest.from_request(request)
- http_req.meta[SCREENSHOT_SERVER_URL_KEY] = server_url
- http_req.meta[SCREENSHOT_AUTH_TOKEN_KEY] = auth_token
- http_req.meta[SCREENSHOT_FILE_KEY] = (
- session.app_file_manager.path or session.initialization_id
+ http_req = build_scratchpad_request(
+ session, request, server_url=server_url, auth_token=auth_token
)
session.instantiate(
diff --git a/marimo/_session/session.py b/marimo/_session/session.py
index 913c1a75d3..7c1496802b 100644
--- a/marimo/_session/session.py
+++ b/marimo/_session/session.py
@@ -247,6 +247,7 @@ class SessionImpl(Session):
self._stable_id = mint(StableSessionId, "sess")
self.app_file_manager = app_file_manager
self.room = Room()
+
self._kernel_manager = kernel_manager
self.ttl_seconds = (
ttl_seconds if ttl_seconds is not None else _DEFAULT_TTL_SECONDS
diff --git a/marimo/_session/state/serialize.py b/marimo/_session/state/serialize.py
index bd62214843..6414d772a6 100644
--- a/marimo/_session/state/serialize.py
+++ b/marimo/_session/state/serialize.py
@@ -9,6 +9,8 @@ from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Any, cast
+import msgspec
+
from marimo import _loggers
from marimo._ast.cell_manager import CellManager
from marimo._messaging.cell_output import CellChannel, CellOutput
@@ -95,12 +97,15 @@ def _normalize_error(error: MarimoError | dict[str, Any]) -> ErrorOutput:
if isinstance(error, dict):
return ErrorOutput(
type="error",
- ename=error.get("type", "UnknownError"),
+ ename=error.get("exception_type")
+ or error.get("type", "UnknownError"),
evalue=error.get("msg", ""),
- traceback=error.get("traceback", []),
+ traceback=as_list(error.get("traceback")),
)
else:
- if isinstance(error, UnknownError) and error.error_type:
+ if isinstance(error, MarimoExceptionRaisedError):
+ ename = error.exception_type
+ elif isinstance(error, UnknownError) and error.error_type:
# UnknownError with custom error_type field
ename = error.error_type
else:
@@ -111,8 +116,21 @@ def _normalize_error(error: MarimoError | dict[str, Any]) -> ErrorOutput:
type="error",
ename=ename,
evalue=error.describe(),
- traceback=getattr(error, "traceback", []),
+ traceback=as_list(getattr(error, "traceback", None)),
+ )
+
+
+def _restore_traceback(traceback: str | list[str] | None) -> str | None:
+ entries = as_list(traceback)
+ if not entries:
+ return None
+ return (
+ "".join(
+ entry if entry.endswith("\n") else entry + "\n"
+ for entry in entries[:-1]
)
+ + entries[-1]
+ )
def serialize_session_view(
@@ -177,6 +195,10 @@ def serialize_session_view(
)
)
+ if cell_notif.output and isinstance(cell_notif.output.code, str):
+ for output in outputs:
+ output["code"] = cell_notif.output.code
+
# Convert console outputs
for console_out in as_list(cell_notif.console):
assert isinstance(console_out, CellOutput)
@@ -202,6 +224,11 @@ def serialize_session_view(
)
)
+ if isinstance(console_out.code, str):
+ console[-1]["code"] = console_out.code
+ if console_out.traceback_format is not msgspec.UNSET:
+ console[-1]["traceback_format"] = console_out.traceback_format
+
code_hash = _hash_code(view.last_executed_code.get(cell_id))
cells.append(
@@ -250,8 +277,12 @@ def deserialize_session(
exception_type=output["ename"],
msg=output["evalue"],
raising_cell=None,
+ traceback=_restore_traceback(
+ output.get("traceback")
+ ),
)
],
+ code=output.get("code", msgspec.UNSET),
)
)
elif output["type"] == "data":
@@ -267,6 +298,7 @@ def deserialize_session(
next(iter(output["data"].keys())),
),
data=next(iter(output["data"].values())),
+ code=output.get("code", msgspec.UNSET),
)
)
else:
@@ -276,6 +308,7 @@ def deserialize_session(
channel=CellChannel.OUTPUT,
mimetype="application/vnd.marimo+mimebundle",
data=output["data"],
+ code=output.get("code", msgspec.UNSET),
)
)
else:
@@ -294,6 +327,10 @@ def deserialize_session(
channel=CellChannel.MEDIA,
data=console["data"],
mimetype=console["mimetype"],
+ code=console.get("code", msgspec.UNSET),
+ traceback_format=console.get(
+ "traceback_format", msgspec.UNSET
+ ),
)
)
else:
@@ -326,6 +363,10 @@ def deserialize_session(
else CellChannel.STDOUT,
data=data,
mimetype=mimetype,
+ code=console.get("code", msgspec.UNSET),
+ traceback_format=console.get(
+ "traceback_format", msgspec.UNSET
+ ),
)
)
diff --git a/marimo/_templates.py b/marimo/_templates.py
index e9a7cf4763..f4c7dc41bd 100644
--- a/marimo/_templates.py
+++ b/marimo/_templates.py
@@ -23,7 +23,7 @@ from marimo._schemas.session import NotebookSessionV1
from marimo._server.tokens import SkewProtectionToken
from marimo._session.model import SessionMode
from marimo._session.notebook import read_css_file, read_html_head_file
-from marimo._utils.env import is_env_true
+from marimo._utils.env import pair_preview_enabled
from marimo._utils.versions import is_editable
from marimo._version import __version__
@@ -140,7 +140,7 @@ def _get_mount_config(
}
pair_preview = ""
- if is_env_true("MARIMO_PAIR_NEXT"):
+ if pair_preview_enabled():
pair_preview = ',\n "pairPreview": ' + json_script(
{
"command": get_pair_command(),
diff --git a/marimo/_utils/env.py b/marimo/_utils/env.py
index 8ba8316c7a..29d6571ebc 100644
--- a/marimo/_utils/env.py
+++ b/marimo/_utils/env.py
@@ -3,6 +3,13 @@ from __future__ import annotations
import os
+PAIR_PREVIEW_ENV = "MARIMO_PAIR_NEXT"
+
+
+def pair_preview_enabled() -> bool:
+ """Return whether the Pair preview is enabled."""
+ return is_env_true(PAIR_PREVIEW_ENV)
+
def is_env_true(key: str, default: bool = False) -> bool:
"""Return True if the env var `key` is set to a truthy value ("true"/"1").
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index a5cdd83eb1..1c5725810d 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -264,6 +264,72 @@ 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:
@@ -522,6 +588,8 @@ components:
properties:
channel:
$ref: '#/components/schemas/CellChannel'
+ code:
+ type: string
data:
anyOf:
- type: string
@@ -586,6 +654,10 @@ components:
- video/mpeg
timestamp:
type: number
+ traceback_format:
+ enum:
+ - html
+ - text
required:
- channel
- mimetype
@@ -4211,10 +4283,12 @@ 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 a0afbed67d..97897c363e 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -3984,6 +3984,36 @@ 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;
@@ -4166,6 +4196,7 @@ export interface components {
/** CellOutput */
CellOutput: {
channel: components["schemas"]["CellChannel"];
+ code?: string;
data:
| string
| (
@@ -4211,6 +4242,8 @@ export interface components {
| "video/mp4"
| "video/mpeg";
timestamp?: number;
+ /** @enum {unknown} */
+ traceback_format?: "html" | "text";
};
/**
* CellOutputs
@@ -6331,7 +6364,8 @@ export interface components {
| components["schemas"]["FocusCellNotification"]
| components["schemas"]["ActiveLineNotification"]
| components["schemas"]["NotebookDocumentTransactionNotification"]
- | components["schemas"]["ConsumerCapabilitiesNotification"];
+ | components["schemas"]["ConsumerCapabilitiesNotification"]
+ | components["schemas"]["AttachmentsNotification"];
/**
* OpenAiConfig
* @description Configuration options for OpenAI or OpenAI-compatible services.
diff --git a/packages/openapi/src/session.ts b/packages/openapi/src/session.ts
index d08655759d..5ca580ec0a 100644
--- a/packages/openapi/src/session.ts
+++ b/packages/openapi/src/session.ts
@@ -20,6 +20,7 @@ export interface components {
)[];
};
DataOutput: {
+ code?: string;
data: {
[key: string]: unknown;
};
@@ -27,6 +28,7 @@ export interface components {
type: "data";
};
ErrorOutput: {
+ code?: string;
ename: string;
evalue: string;
traceback: string[];
@@ -43,6 +45,7 @@ export interface components {
version: string;
};
StreamMediaOutput: {
+ code?: string;
data: string;
/** @enum {string} */
mimetype:
@@ -73,9 +76,12 @@ export interface components {
/** @enum {string} */
name: "media";
/** @enum {string} */
+ traceback_format?: "text" | "html";
+ /** @enum {string} */
type: "streamMedia";
};
StreamOutput: {
+ code?: string;
/** @enum {string|null} */
mimetype:
| "application/json"
@@ -107,6 +113,8 @@ export interface components {
name: "stdout" | "stderr";
text: string;
/** @enum {string} */
+ traceback_format?: "text" | "html";
+ /** @enum {string} */
type: "stream";
};
TimeMetadata: {
diff --git a/tests/_code_mode/test_code_mode_context.py b/tests/_code_mode/test_code_mode_context.py
index 311cc99f7d..284507af57 100644
--- a/tests/_code_mode/test_code_mode_context.py
+++ b/tests/_code_mode/test_code_mode_context.py
@@ -1730,3 +1730,41 @@ class TestErrorReporting:
captured = capsys.readouterr()
assert "created and ran" in captured.out
assert "error in cell" not in captured.err
+
+
+async def test_config_edit_retains_unregistered_error_source(
+ k: Kernel,
+) -> None:
+ source = "x = ("
+ cid = CellId_t("broken")
+ await k.run([ExecuteCellCommand(cell_id=cid, code=source)])
+ assert cid not in k.graph.cells
+ assert k.cell_metadata[cid].code == source
+ cell = NotebookCell(id=cid, code=source, name="", config=CellConfig())
+ with _ctx(k, extra_doc_cells=[cell]) as ctx:
+ async with ctx as nb:
+ nb.edit_cell(str(cid), hide_code=True)
+ assert k.cell_metadata[cid].code == source
+ assert k.cell_metadata[cid].config.hide_code is True
+
+
+async def test_config_edit_retains_semantic_error_source(k: Kernel) -> None:
+ source = "duplicate = 1"
+ cid = CellId_t("first")
+ await k.run(
+ [
+ ExecuteCellCommand(cell_id=cid, code=source),
+ ExecuteCellCommand(
+ cell_id=CellId_t("second"), code="duplicate = 2"
+ ),
+ ]
+ )
+ assert cid in k.errors
+ with _ctx(k) as ctx:
+ async with ctx as nb:
+ nb.edit_cell(str(cid), hide_code=True)
+ await k.run(
+ [ExecuteCellCommand(cell_id=CellId_t("third"), code="unrelated = 3")]
+ )
+ assert cid in k.errors
+ assert k.cell_metadata[cid].code == source
diff --git a/tests/_export/test_exporter.py b/tests/_export/test_exporter.py
index 731f967a4b..640e7f2412 100644
--- a/tests/_export/test_exporter.py
+++ b/tests/_export/test_exporter.py
@@ -1107,7 +1107,20 @@ def test_export_as_html_code_hash_consistency(
session_view.cell_notifications[cell_ids[0]] = CellNotification(
cell_id=cell_ids[0],
status="idle",
- output=None,
+ output=CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="application/vnd.marimo+error",
+ data=[
+ {
+ "type": "exception",
+ "msg": "bad",
+ "exception_type": "ValueError",
+ "raising_cell": None,
+ "traceback": None,
+ }
+ ],
+ code="private_source_sentinel = 42",
+ ),
console=[],
timestamp=0,
)
@@ -1139,6 +1152,8 @@ def test_export_as_html_code_hash_consistency(
html_with_code, _ = exporter.export_as_html(export_request)
assert export_request.snapshot == snapshot_before
+ assert "private_source_sentinel" not in html_without_code
+ assert "private_source_sentinel" in html_with_code
# Extract code hash from both HTML outputs
hash_pattern = r"<marimo-code-hash[^>]*>([a-f0-9]+)</marimo-code-hash>"
diff --git a/tests/_messaging/mocks.py b/tests/_messaging/mocks.py
index 52e96b9c7e..3d8e95ec67 100644
--- a/tests/_messaging/mocks.py
+++ b/tests/_messaging/mocks.py
@@ -52,8 +52,12 @@ class MockStderr(Stderr):
self.messages = stream.messages
def _write_with_mimetype(
- self, data: str, mimetype: ConsoleMimeType
+ self,
+ data: str,
+ mimetype: ConsoleMimeType,
+ *,
+ code: str | None = None,
) -> int:
- del mimetype
+ del mimetype, code
self.messages.append(data)
return len(data)
diff --git a/tests/_messaging/test_cell_output.py b/tests/_messaging/test_cell_output.py
index 6372623635..a5f50b7733 100644
--- a/tests/_messaging/test_cell_output.py
+++ b/tests/_messaging/test_cell_output.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import msgspec
import pytest
from marimo._messaging.cell_output import CellChannel, CellOutput
@@ -92,6 +93,14 @@ def test_identity(subject: CellOutput):
assert subject == parse_raw(serialized, CellOutput)
[email protected]("code", ["raise ValueError('failed code')", ""])
+def test_source_code_round_trip(code: str) -> None:
+ output = CellOutput.errors([MarimoSyntaxError(msg="bad code")], code=code)
+ encoded = msgspec.json.encode(output)
+ restored = msgspec.json.decode(encoded, type=CellOutput)
+ assert restored.code == code
+
+
def test_cell_output_static_methods():
# Test empty output
empty = CellOutput.empty()
diff --git a/tests/_messaging/test_console_output_worker.py b/tests/_messaging/test_console_output_worker.py
index d4b49db55e..c69fb90ea2 100644
--- a/tests/_messaging/test_console_output_worker.py
+++ b/tests/_messaging/test_console_output_worker.py
@@ -44,6 +44,37 @@ class TestConsoleOutputWorker:
("second", "second"),
]
+ def test_flush_keeps_source_code_and_separates_outputs_by_code(
+ self,
+ ) -> None:
+ buffered = {}
+ for code in ("x = 1", "x = 2"):
+ _add_output_to_buffer(
+ ConsoleMsg(
+ CellChannel.STDERR,
+ "cell1",
+ "Traceback",
+ "application/vnd.marimo+traceback",
+ run_id="same-run",
+ execution_id="same-execution",
+ code=code,
+ ),
+ buffered,
+ )
+ stream = MockStream()
+ _flush_outputs(buffered, stream)
+ assert [n.console.code for n in stream.cell_notifications] == [
+ "x = 1",
+ "x = 2",
+ ]
+
+ def test_write_console_output_omits_code_when_absent(self) -> None:
+ stream = MockStream()
+ _write_console_output(
+ stream, CellChannel.STDERR, "cell1", "Hello", "text/plain"
+ )
+ assert "code" not in stream.operations[0]["console"]
+
def test_buffer_preserves_run_ids_across_execution_boundaries(
self,
) -> None:
diff --git a/tests/_messaging/test_tracebacks.py b/tests/_messaging/test_tracebacks.py
index f5c5de5d4c..924c25b272 100644
--- a/tests/_messaging/test_tracebacks.py
+++ b/tests/_messaging/test_tracebacks.py
@@ -53,6 +53,16 @@ class TestTracebacks:
# Second argument should be the mimetype
_, kwargs = mock_stderr._write_with_mimetype.call_args
assert kwargs["mimetype"] == "application/vnd.marimo+traceback"
+ assert kwargs["code"] is None
+
+ def test_write_traceback_to_stderr_keeps_code(self) -> None:
+ mock_stderr = MagicMock(spec=Stderr)
+
+ with patch("sys.stderr", mock_stderr):
+ write_traceback("ValueError: invalid value", code="raise x")
+
+ _, kwargs = mock_stderr._write_with_mimetype.call_args
+ assert kwargs["code"] == "raise x"
def test_write_traceback_to_regular_stderr(self) -> None:
# Test writing traceback to regular stderr (not Stderr)
@@ -258,3 +268,35 @@ class TestIsCodeModeRequest:
assert is_code_mode_request() is False
finally:
HTTP_REQUEST_CTX.reset(token)
+
+
[email protected]("redirected", [True, False])
+def test_run_mode_tracebacks_omit_full_source(redirected: bool) -> None:
+ import msgspec
+
+ stderr = MagicMock(spec=Stderr) if redirected else MagicMock()
+ context = MagicMock(cell_id="cell")
+ with (
+ patch("sys.stderr", stderr),
+ patch("marimo._messaging.tracebacks.get_mode", return_value="run"),
+ patch(
+ "marimo._messaging.tracebacks._show_tracebacks_enabled",
+ return_value=True,
+ ),
+ patch(
+ "marimo._messaging.tracebacks.safe_get_context",
+ return_value=context,
+ ),
+ patch(
+ "marimo._messaging.tracebacks.is_code_mode_request",
+ return_value=False,
+ ),
+ patch(
+ "marimo._messaging.tracebacks.broadcast_notification"
+ ) as broadcast,
+ ):
+ write_traceback("ValueError: bad", code="private_source_sentinel = 42")
+ if redirected:
+ assert stderr._write_with_mimetype.call_args.kwargs["code"] is None
+ else:
+ assert broadcast.call_args.args[0].console.code is msgspec.UNSET
diff --git a/tests/_messaging/test_types.py b/tests/_messaging/test_types.py
index 4ac0e09501..53c98c6c74 100644
--- a/tests/_messaging/test_types.py
+++ b/tests/_messaging/test_types.py
@@ -50,8 +50,13 @@ class TestStdoutStderr:
self.written_data: list[tuple[str, KnownMimeType]] = []
def _write_with_mimetype(
- self, data: str, mimetype: KnownMimeType
+ self,
+ data: str,
+ mimetype: KnownMimeType,
+ *,
+ code: str | None = None,
) -> int:
+ del code
self.written_data.append((data, mimetype))
return len(data)
diff --git a/tests/_pyodide/test_pyodide_streams.py b/tests/_pyodide/test_pyodide_streams.py
index c9062bac47..703da7cc60 100644
--- a/tests/_pyodide/test_pyodide_streams.py
+++ b/tests/_pyodide/test_pyodide_streams.py
@@ -103,6 +103,27 @@ class TestPyodideStdout:
class TestPyodideStderr:
+ @pytest.mark.parametrize("code", [None, "raise ValueError('failed')"])
+ def test_traceback_source_forwarding(
+ self,
+ pyodide_stderr: PyodideStderr,
+ pyodide_pipe: Mock,
+ code: str | None,
+ ) -> None:
+ pyodide_stderr._write_with_mimetype(
+ "ValueError: failed",
+ mimetype="application/vnd.marimo+traceback",
+ code=code,
+ )
+ pyodide_pipe.assert_called_once()
+ console = json.loads(pyodide_pipe.call_args.args[0])["console"]
+ assert console["data"] == "ValueError: failed"
+ assert console["mimetype"] == "application/vnd.marimo+traceback"
+ if code is None:
+ assert "code" not in console
+ else:
+ assert console["code"] == code
+
def test_writable(self, pyodide_stderr: PyodideStderr) -> None:
assert pyodide_stderr.writable() is True
diff --git a/tests/_runtime/_helpers/streams.py b/tests/_runtime/_helpers/streams.py
index 6c0d62a76a..99e0fa12c3 100644
--- a/tests/_runtime/_helpers/streams.py
+++ b/tests/_runtime/_helpers/streams.py
@@ -99,9 +99,13 @@ class MockStderr(ThreadSafeStderr):
self.messages: list[str] = []
def _write_with_mimetype(
- self, data: str, mimetype: ConsoleMimeType
+ self,
+ data: str,
+ mimetype: ConsoleMimeType,
+ *,
+ code: str | None = None,
) -> int:
- del mimetype
+ del mimetype, code
self.messages.append(data)
return len(data)
diff --git a/tests/_runtime/runner/test_cell_runner.py b/tests/_runtime/runner/test_cell_runner.py
index 634abfc88c..40e2573016 100644
--- a/tests/_runtime/runner/test_cell_runner.py
+++ b/tests/_runtime/runner/test_cell_runner.py
@@ -757,3 +757,41 @@ async def test_run_all_swallows_sigint_raise_and_fires_on_finish(
"on_finish_hooks must see the cells that were still queued "
"when SIGINT fired"
)
+
+
+async def test_traceback_keeps_source_captured_before_await(
+ execution_kernel: Kernel,
+ exec_req: ExecReqProvider,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from unittest.mock import Mock
+
+ from marimo._ast.compiler import compile_cell
+ from marimo._runtime.exceptions import MarimoRuntimeException
+
+ k = execution_kernel
+ request = exec_req.get("original_source = 1")
+ await k.run([request])
+ runner = Runner(
+ roots={request.cell_id},
+ graph=k.graph,
+ glbls=k.globals,
+ debugger=k.debugger,
+ hooks=NotebookCellHooks(),
+ )
+
+ async def replace_cell(_cell: CellImpl) -> RunResult:
+ k.graph.cells[request.cell_id] = compile_cell(
+ "replacement_source = 2", cell_id=request.cell_id
+ )
+ exception = MarimoRuntimeException()
+ exception.__cause__ = ValueError("bad")
+ return RunResult(output=None, exception=exception)
+
+ writer = Mock()
+ monkeypatch.setattr(runner, "evaluate_interruptible", replace_cell)
+ monkeypatch.setattr(
+ "marimo._runtime.runner.cell_runner.write_traceback", writer
+ )
+ await runner.run(request.cell_id)
+ assert writer.call_args.kwargs["code"] == "original_source = 1"
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index 57b6fe16d4..b0a9afc380 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -10,6 +10,7 @@ from contextlib import ExitStack
from typing import TYPE_CHECKING, Any, cast
from unittest.mock import MagicMock, Mock, patch
+import msgspec
import pytest
from marimo._ast.variables import is_mangled_local
@@ -4221,6 +4222,70 @@ class TestStateTransitions:
class TestErrorHandling:
+ @pytest.mark.parametrize(
+ "code",
+ [
+ "raise ValueError('failed snapshot')",
+ "x =",
+ "from marimo._runtime.control_flow import MarimoInterrupt; raise MarimoInterrupt()",
+ ],
+ )
+ async def test_error_captures_source_code(
+ self,
+ mocked_kernel: MockedKernel,
+ exec_req: ExecReqProvider,
+ code: str,
+ ) -> None:
+ request = exec_req.get(code)
+ await mocked_kernel.k.run([request])
+ error_op = _filter_to_error_ops(
+ mocked_kernel.stream.cell_notifications
+ )[0]
+ assert error_op.output is not None
+ assert error_op.output.code == code
+ if code.startswith("raise ValueError"):
+ error = _parse_error_output(error_op)[0]
+ assert isinstance(error, MarimoExceptionRaisedError)
+ assert error.traceback is not None
+ assert "failed snapshot" in error.traceback
+
+ await mocked_kernel.k.run(
+ [ExecuteCellCommand(cell_id=request.cell_id, code="42")]
+ )
+ assert error_op.output.code == code
+
+ newer_code = "raise ValueError('newer failure')"
+ await mocked_kernel.k.run(
+ [ExecuteCellCommand(cell_id=request.cell_id, code=newer_code)]
+ )
+ latest_error = _filter_to_error_ops(
+ mocked_kernel.stream.cell_notifications
+ )[-1]
+ assert latest_error.output is not None
+ assert latest_error.output.code == newer_code
+ assert error_op.output.code == code
+
+ async def test_cancelled_descendant_captures_own_code(
+ self, mocked_kernel: MockedKernel, exec_req: ExecReqProvider
+ ) -> None:
+ await mocked_kernel.k.run(
+ [
+ exec_req.get("x = 0; raise ValueError('ancestor failure')"),
+ child := exec_req.get("x + 1"),
+ ]
+ )
+ error_ops = _filter_to_error_ops(
+ mocked_kernel.stream.cell_notifications
+ )
+ child_op = next(op for op in error_ops if op.cell_id == child.cell_id)
+ assert child_op.output is not None
+ assert child_op.output.code == child.code
+ assert child_op.console == []
+ error = _parse_error_output(child_op)[0]
+ assert isinstance(error, MarimoExceptionRaisedError)
+ assert error.traceback is None
+ assert error.raising_cell is not None
+
async def test_error_handling(
self, mocked_kernel: MockedKernel, exec_req: ExecReqProvider
) -> None:
@@ -4249,6 +4314,8 @@ class TestErrorHandling:
assert len(errors) == 1
assert isinstance(errors[0], MarimoInternalError)
assert errors[0].msg.startswith("An internal error occurred: ")
+ assert error_cell_notification[0].output is not None
+ assert error_cell_notification[0].output.code is msgspec.UNSET
# Verify no traceback leaks via console output
for op in cell_notifications:
diff --git a/tests/_server/api/endpoints/test_execution.py b/tests/_server/api/endpoints/test_execution.py
index faa1fe34a8..7839662f02 100644
--- a/tests/_server/api/endpoints/test_execution.py
+++ b/tests/_server/api/endpoints/test_execution.py
@@ -6,7 +6,7 @@ import json
import sys
import time
from typing import TYPE_CHECKING
-from unittest.mock import MagicMock
+from unittest.mock import MagicMock, patch
import pytest
@@ -16,7 +16,11 @@ from marimo._code_mode.screenshot_meta import (
SCREENSHOT_SERVER_URL_KEY,
)
from marimo._messaging.notification import ConsumerCapabilities
-from marimo._runtime.commands import ExecuteCellsCommand
+from marimo._runtime.commands import (
+ ExecuteCellsCommand,
+ ExecuteScratchpadCommand,
+)
+from marimo._server import scratchpad as scratchpad_mod
from marimo._server.api.utils import enforce_consumer_capability
from marimo._types.ids import CellId_t, SessionId
from marimo._utils.http import HTTPException
@@ -58,9 +62,6 @@ def _count_execute_interrupts(
watcher_fires (bool): The disconnect watcher sees the disconnect.
stream_cancelled (bool): The response stream is cancelled.
"""
- from unittest.mock import patch
-
- from marimo._server import scratchpad as scratchpad_mod
session = get_session_manager(client).get_session(SESSION_ID)
assert session is not None
@@ -266,9 +267,7 @@ class TestExecutionRoutes_EditMode:
@staticmethod
@with_session(SESSION_ID)
def test_execute_with_stable_session_id(client: TestClient) -> None:
- from unittest.mock import patch
- from marimo._runtime.commands import ExecuteScratchpadCommand
from marimo._server import scratchpad as scratchpad_mod
session = get_session_manager(client).get_session(SESSION_ID)
@@ -361,9 +360,8 @@ class TestExecutionRoutes_EditMode:
"""Inject the trusted server URL, auth token, and notebook key
so screenshots authenticate and attach to the active notebook.
"""
- from unittest.mock import PropertyMock, patch
+ from unittest.mock import PropertyMock
- from marimo._runtime.commands import ExecuteScratchpadCommand
from marimo._server import scratchpad as scratchpad_mod
session = get_session_manager(client).get_session(SESSION_ID)
@@ -431,11 +429,9 @@ class TestExecutionRoutes_EditMode:
`cell.console_outputs`. Regression guard: removing the
construction line in the endpoint should fail this test.
"""
- from unittest.mock import patch
from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._messaging.notification import CellNotification
- from marimo._runtime.commands import ExecuteScratchpadCommand
from marimo._server import scratchpad as scratchpad_mod
session = get_session_manager(client).get_session(SESSION_ID)
diff --git a/tests/_server/api/endpoints/test_health.py b/tests/_server/api/endpoints/test_health.py
index b92be7f9a6..0a97a3f130 100644
--- a/tests/_server/api/endpoints/test_health.py
+++ b/tests/_server/api/endpoints/test_health.py
@@ -85,6 +85,7 @@ def test_sessions_stable_id_survives_reconnect(
assert session is not None
expected = {
"session_id": session.stable_id,
+ "notebook_id": None,
"filename": session.app_file_manager.filename,
"path": session.app_file_manager.path,
}
diff --git a/tests/_server/api/endpoints/test_kiosk.py b/tests/_server/api/endpoints/test_kiosk.py
index 650216c8bd..2f41490a81 100644
--- a/tests/_server/api/endpoints/test_kiosk.py
+++ b/tests/_server/api/endpoints/test_kiosk.py
@@ -47,6 +47,10 @@ 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_pair_endpoints.py b/tests/_server/api/endpoints/test_pair_endpoints.py
new file mode 100644
index 0000000000..2281cceec8
--- /dev/null
+++ b/tests/_server/api/endpoints/test_pair_endpoints.py
@@ -0,0 +1,285 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+from unittest.mock import Mock
+
+import msgspec
+import pytest
+
+from marimo._ast.app import App, InternalApp
+from marimo._config.manager import get_default_config_manager
+from marimo._core import protocol
+from marimo._messaging.messages import AGENT_MESSAGE_TYPE
+from marimo._server.host.bridge import SessionBridge
+from marimo._server.host.context import HostContext
+from marimo._server.workspace import SingleFileWorkspace
+from marimo._session.consumer import SessionConsumer
+from marimo._session.extensions.extensions import SessionViewExtension
+from marimo._session.managers import KernelManagerImpl
+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 ConsumerId, SessionId
+from marimo._utils.env import PAIR_PREVIEW_ENV
+from marimo._utils.marimo_path import MarimoPath
+from tests._server.mocks import get_session_manager, token_header
+
+if TYPE_CHECKING:
+ from collections.abc import AsyncIterator
+ from pathlib import Path
+
+ from starlette.testclient import TestClient
+
+ from marimo._core.notebook import Notebook
+
+
[email protected](autouse=True)
+def preview(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv(PAIR_PREVIEW_ENV, "1")
+
+
+async def target(
+ client: TestClient, tmp_path: Path
+) -> AsyncIterator[tuple[SessionImpl, Notebook]]:
+ consumer = Mock(spec=SessionConsumer)
+ consumer.consumer_id = ConsumerId("browser")
+ consumer.connection_state.return_value = ConnectionState.OPEN
+ kernel = Mock(spec=KernelManagerImpl)
+ kernel.kernel_task = None
+ session = SessionImpl(
+ session_view=SessionView(),
+ initialization_id="notebook.py",
+ session_consumer=consumer,
+ kernel_manager=kernel,
+ app_file_manager=AppFileManager.from_app(InternalApp(App())),
+ config_manager=get_default_config_manager(current_path=None),
+ ttl_seconds=None,
+ extensions=[SessionViewExtension()],
+ )
+ manager = get_session_manager(client)
+ file = tmp_path / "notebook.py"
+ file.write_text("import marimo\napp = marimo.App()\n")
+ session.app_file_manager.filename = str(file)
+ manager.workspace = SingleFileWorkspace.from_path(MarimoPath(file))
+ manager._repository.add_sync(SessionId("browser"), session)
+ bridge = SessionBridge(manager)
+ await bridge.open()
+ notebook = bridge.notebook_for_session(session)
+ assert notebook is not None
+ client.app.state.host_context = HostContext(bridge, "host-token", 2718)
+ try:
+ yield session, notebook
+ finally:
+ client.app.state.host_context = None
+ bridge.close()
+ session.close()
+
+
+def path(session: SessionImpl, operation: str) -> str:
+ return f"/api/pair/notebooks/{session.stable_id}/{operation}"
+
+
+ "payload", [{"cell": "x", "text": "λ"}, [1, "a"], "hello", 42, True, None]
+)
+def test_message_is_an_opaque_custom_event(
+ client: TestClient, target: tuple[SessionImpl, Notebook], payload: object
+) -> None:
+ session, notebook = target
+ notebook.attach(kind="agent", identity="codex", name="Codex")
+ notebook.attach(kind="agent", identity="claude", name="Claude")
+ events = []
+ client.app.state.host_context.bridge.host.subscribe(
+ events.append, notebook_id=notebook.id, types={"custom"}
+ )
+ response = client.post(
+ path(session, "messages"),
+ content=msgspec.json.encode(payload),
+ headers=token_header("fake-token"),
+ )
+ assert (response.status_code, response.content) == (202, b"")
+ assert len(events) == 1
+ event = events[0].event
+ assert isinstance(event, protocol.CustomEvent)
+ assert event.data.custom == protocol.Custom(
+ type=AGENT_MESSAGE_TYPE, data=payload
+ )
+
+
[email protected]("client_attached", [False, True])
+def test_message_requires_an_agent(
+ client: TestClient,
+ target: tuple[SessionImpl, Notebook],
+ client_attached: bool,
+) -> None:
+ session, notebook = target
+ if client_attached:
+ notebook.attach(kind="client")
+ response = client.post(
+ path(session, "messages"), json={}, headers=token_header("fake-token")
+ )
+ assert (response.status_code, response.json()) == (
+ 409,
+ {"detail": "No agent attached"},
+ )
+
+
+def test_no_host_notebook(
+ client: TestClient, target: tuple[SessionImpl, Notebook]
+) -> None:
+ session, _ = target
+ client.app.state.host_context = None
+ response = client.post(
+ path(session, "messages"), json={}, headers=token_header("fake-token")
+ )
+ assert response.status_code == 409
+ response = client.post(
+ path(session, "attachments/detach"),
+ json={"attachment_id": "missing"},
+ headers=token_header("fake-token"),
+ )
+ assert response.status_code == 204
+
+
+def test_detach_removes_only_the_selected_attachment(
+ client: TestClient, target: tuple[SessionImpl, Notebook]
+) -> None:
+ session, notebook = target
+ first = notebook.attach(kind="agent", identity="same")
+ second = notebook.attach(kind="agent", identity="same")
+ response = client.post(
+ path(session, "attachments/detach"),
+ json={"attachment_id": first.id},
+ headers=token_header("fake-token"),
+ )
+ assert (response.status_code, notebook.attachments, session._closed) == (
+ 204,
+ [second],
+ False,
+ )
+ response = client.post(
+ path(session, "attachments/detach"),
+ json={"attachment_id": first.id},
+ headers=token_header("fake-token"),
+ )
+ assert response.status_code == 204
+
+
+ "body",
+ [b"{", b"null", b"{}", b'{"attachment_id": 1}', b'{"attachment_id": ""}'],
+)
+def test_invalid_detach_body(
+ client: TestClient, target: tuple[SessionImpl, Notebook], body: bytes
+) -> None:
+ session, _ = target
+ assert (
+ client.post(
+ path(session, "attachments/detach"),
+ content=body,
+ headers=token_header("fake-token"),
+ ).status_code
+ == 400
+ )
+
+
+def test_invalid_message_json(
+ client: TestClient, target: tuple[SessionImpl, Notebook]
+) -> None:
+ session, _ = target
+ response = client.post(
+ path(session, "messages"),
+ content=b"{",
+ headers=token_header("fake-token"),
+ )
+ assert (response.status_code, response.json()) == (
+ 400,
+ {"detail": "Invalid JSON agent message payload."},
+ )
+
+
[email protected]("operation", ["messages", "attachments/detach"])
+def test_preview_gate(
+ client: TestClient,
+ target: tuple[SessionImpl, Notebook],
+ monkeypatch: pytest.MonkeyPatch,
+ operation: str,
+) -> None:
+ session, _ = target
+ monkeypatch.delenv(PAIR_PREVIEW_ENV)
+ assert (
+ client.post(
+ path(session, operation),
+ json={},
+ headers=token_header("fake-token"),
+ ).status_code
+ == 404
+ )
+
+
[email protected]("operation", ["messages", "attachments/detach"])
+def test_missing_session(client: TestClient, operation: str) -> None:
+ assert (
+ client.post(
+ f"/api/pair/notebooks/missing/{operation}",
+ json={},
+ headers=token_header("fake-token"),
+ ).status_code
+ == 404
+ )
+
+
+def test_pair_events_route_is_removed(
+ client: TestClient, target: tuple[SessionImpl, Notebook]
+) -> None:
+ session, _ = target
+ assert (
+ client.get(
+ path(session, "events"), headers=token_header("fake-token")
+ ).status_code
+ == 404
+ )
+
+
[email protected]("operation", ["messages", "attachments/detach"])
+def test_routes_require_authentication(
+ client: TestClient, target: tuple[SessionImpl, Notebook], operation: str
+) -> None:
+ session, notebook = target
+ response = client.post(path(session, operation), json={})
+ assert (response.status_code, notebook.attachments) == (401, [])
+
+
[email protected]("operation", ["messages", "attachments/detach"])
+def test_routes_require_edit_mode(
+ client: TestClient, target: tuple[SessionImpl, Notebook], operation: str
+) -> None:
+ session, _ = target
+ manager = get_session_manager(client)
+ manager.mode = SessionMode.RUN
+ headers = token_header(str(manager.auth_token))
+ assert client.get("/api/version", headers=headers).status_code == 200
+ assert (
+ client.post(
+ path(session, operation), json={}, headers=headers
+ ).status_code
+ == 401
+ )
+
+
+def test_sessions_include_host_notebook_id(
+ client: TestClient, target: tuple[SessionImpl, Notebook]
+) -> None:
+ session, notebook = target
+ response = client.get("/api/sessions", headers=token_header("fake-token"))
+ assert response.json() == {
+ "browser": {
+ "session_id": session.stable_id,
+ "notebook_id": notebook.id,
+ "filename": session.app_file_manager.filename,
+ "path": session.app_file_manager.path,
+ }
+ }
diff --git a/tests/_server/api/endpoints/test_resume_session.py b/tests/_server/api/endpoints/test_resume_session.py
index 354c9aa812..3f7b03fd80 100644
--- a/tests/_server/api/endpoints/test_resume_session.py
+++ b/tests/_server/api/endpoints/test_resume_session.py
@@ -316,8 +316,8 @@ 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 _ in range(2):
- assert websocket.receive_json()["op"] == "environment-state"
+ for op in ("attachments", "environment-state", "environment-state"):
+ assert websocket.receive_json()["op"] == op
session = get_session(client, SessionId("123"))
assert session
@@ -395,6 +395,10 @@ 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",
@@ -467,6 +471,10 @@ 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 c508d56c96..eb08c09491 100644
--- a/tests/_server/api/endpoints/test_ws.py
+++ b/tests/_server/api/endpoints/test_ws.py
@@ -5,14 +5,17 @@ import asyncio
from contextlib import contextmanager
from pathlib import Path
from typing import TYPE_CHECKING, Any
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import AsyncMock, MagicMock, Mock, 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,
@@ -25,10 +28,17 @@ 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 SessionId
+from marimo._types.ids import CellId_t, 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,
@@ -194,6 +204,58 @@ 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"
+ 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": (
+ [msgspec.json.decode(msgspec.json.encode(attachment))]
+ if attachment_state == "attached"
+ else []
+ ),
+ },
+ }
+ ]
+
+
def test_completed_startup_is_restored_on_reconnect_and_refresh(
client: TestClient,
) -> None:
@@ -450,8 +512,12 @@ async def test_connects_to_existing_session_with_same_file(
with client.websocket_connect(ws_1) as websocket1:
data = websocket1.receive_json()
assert_parse_ready_response(data)
- for _ in range(2):
- assert websocket1.receive_json()["op"] == "environment-state"
+ for op in (
+ "attachments",
+ "environment-state",
+ "environment-state",
+ ):
+ assert websocket1.receive_json()["op"] == op
# Instantiate the session
client.post(
@@ -475,10 +541,12 @@ async def test_connects_to_existing_session_with_same_file(
# which the room membership is observable.
data2 = websocket2.receive_json()
assert_parse_ready_response(data2)
- for _ in range(2):
- assert (
- websocket2.receive_json()["op"] == "environment-state"
- )
+ for op in (
+ "attachments",
+ "environment-state",
+ "environment-state",
+ ):
+ assert websocket2.receive_json()["op"] == op
assert data2["data"]["resumed"] is True
diff --git a/tests/_server/host/test_host_backend.py b/tests/_server/host/test_host_backend.py
index 7df12cc98f..7ffc7d8925 100644
--- a/tests/_server/host/test_host_backend.py
+++ b/tests/_server/host/test_host_backend.py
@@ -7,6 +7,11 @@ import asyncio
import pytest
+from marimo._code_mode.screenshot_meta import (
+ SCREENSHOT_AUTH_TOKEN_KEY,
+ SCREENSHOT_FILE_KEY,
+ SCREENSHOT_SERVER_URL_KEY,
+)
from marimo._core import backend as be, protocol
from marimo._core.stream import Stream
from marimo._messaging.notification import (
@@ -18,6 +23,7 @@ from marimo._messaging.notification import (
from marimo._messaging.serde import serialize_kernel_message
from marimo._runtime.scratch import SCRATCH_CELL_ID
from marimo._server.host.backend import SessionBackend
+from marimo._server.scratchpad import scratchpad_request_metadata
from marimo._session.types import KernelExitInfo, KernelState
from marimo._version import __version__
from tests._server.host.conftest import (
@@ -363,3 +369,42 @@ async def test_submission_failure_is_an_error(
related=(),
)
)
+
+
+async def test_host_run_carries_screenshot_metadata(
+ manager: FakeManager, observed: Observed
+) -> None:
+ b = SessionBackend(
+ protocol.NotebookId("n1"),
+ lambda: "/ws/forecasts.py",
+ manager, # type: ignore[arg-type]
+ observed,
+ Stream(),
+ request_metadata=lambda session: {
+ **scratchpad_request_metadata(
+ session,
+ server_url="http://127.0.0.1:2718/base",
+ auth_token="editor-token",
+ ),
+ "extra": {"enabled": True},
+ },
+ )
+ b.adopt(RT1, manager.next_session)
+ run_id = protocol.RunId("run-screenshot")
+ b.run(run_id, "ctx.screenshot()")
+ await asyncio.wait_for(manager.next_session.submitted.wait(), 5)
+ command = manager.next_session.commands[-1]
+ assert command.request.meta == {
+ SCREENSHOT_SERVER_URL_KEY: "http://127.0.0.1:2718/base",
+ SCREENSHOT_AUTH_TOKEN_KEY: "editor-token",
+ SCREENSHOT_FILE_KEY: "/ws/forecasts.py",
+ "extra": {"enabled": True},
+ }
+ assert command.request.headers == {}
+ assert command.request.url["path"] == ""
+ assert command.request.base_url["path"] == ""
+ assert "HTTPRequest(path=''" in repr(command.request)
+ manager.next_session.broadcast(CompletedRunNotification(run_id=run_id))
+ assert b._run is not None
+ assert b._run.task is not None
+ await b._run.task
diff --git a/tests/_server/host/test_host_bridge.py b/tests/_server/host/test_host_bridge.py
index 68ad0e303d..aa2ec62691 100644
--- a/tests/_server/host/test_host_bridge.py
+++ b/tests/_server/host/test_host_bridge.py
@@ -5,24 +5,30 @@ from __future__ import annotations
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
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,
VariablesNotification,
)
from marimo._runtime.scratch import SCRATCH_CELL_ID
+from marimo._server.api.deps import AppStateBase
from marimo._server.host.bridge import SessionBridge
from marimo._server.host.events import MarimoEvent, MarimoMessage
from marimo._server.models.home import MarimoFile
from marimo._server.workspace import FixedFilesWorkspace
+from marimo._session.model import SessionMode
from tests._core.conftest import names
from tests._server.host.conftest import FakeManager, FakeSession
@@ -1037,3 +1043,129 @@ async def test_session_notifications_join_the_notebook_stream_once(
(protocol.RunId("run-1"), MarimoMessage(planned)),
]
bridge.close()
+
+
+async def test_session_notebook_lookup_boundaries(
+ manager: FakeManager, tmp_path: Path
+) -> None:
+ prepare(manager, tmp_path, "a.py", "unopened.py")
+ saved = FakeSession(str(tmp_path / "a.py"))
+ unsaved = FakeSession(None)
+ outside = FakeSession(str(tmp_path.parent / "outside.py"))
+ manager.sessions.update(saved=saved, unsaved=unsaved, outside=outside)
+ bridge = SessionBridge(manager) # type: ignore[arg-type]
+ 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]
+
+
[email protected]("mode", ["edit", "run"])
+def test_app_state_without_host_has_no_notebook(mode: str) -> None:
+ state = AppStateBase(
+ State({"session_manager": SimpleNamespace(mode=SessionMode(mode))})
+ )
+ assert state.notebook_for_session(FakeSession(None)) is None # type: ignore[arg-type]
+
+
+async def test_bridge_supplies_metadata_for_the_current_session(
+ manager: FakeManager, tmp_path: Path
+) -> None:
+ prepare(manager, tmp_path, "a.py")
+ session = FakeSession(str(tmp_path / "a.py"))
+ manager.sessions["browser"] = session
+ bridge = SessionBridge(
+ manager, # type: ignore[arg-type]
+ request_metadata=lambda current: {
+ "file": current.app_file_manager.path,
+ "extra": 7,
+ },
+ )
+ await bridge.open()
+ notebook = bridge.notebook_for_session(session) # type: ignore[arg-type]
+ assert notebook is not None
+ run = notebook.run("print(1)", request_id="metadata-test")
+ await session.submitted.wait()
+ assert session.commands[-1].request.meta == {
+ "file": str(tmp_path / "a.py"),
+ "extra": 7,
+ }
+ assert session.commands[-1].request.user == {}
+ session.broadcast(CompletedRunNotification(run_id=run.id))
+ backend = bridge._backends[notebook.id]
+ assert backend._run is not None
+ 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 1d04e2fd57..094530f957 100644
--- a/tests/_server/host/test_host_websocket.py
+++ b/tests/_server/host/test_host_websocket.py
@@ -149,6 +149,15 @@ 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"],
@@ -276,7 +285,12 @@ 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[:-1] == [missed]
+ 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
client.portal.call(
session.notify, CompletedRunNotification(run_id="live")
)
diff --git a/tests/_session/state/snapshots/mixed_error_session.json b/tests/_session/state/snapshots/mixed_error_session.json
index 3b26415f39..2547458447 100644
--- a/tests/_session/state/snapshots/mixed_error_session.json
+++ b/tests/_session/state/snapshots/mixed_error_session.json
@@ -11,9 +11,9 @@
"outputs": [
{
"type": "error",
- "ename": "exception",
+ "ename": "ValueError",
"evalue": "Invalid value",
- "traceback": null
+ "traceback": []
},
{
"type": "error",
@@ -25,4 +25,4 @@
"console": []
}
]
-}
\ No newline at end of file
+}
diff --git a/tests/_session/state/test_serialize_session.py b/tests/_session/state/test_serialize_session.py
index 9bbcdd500a..677e4db536 100644
--- a/tests/_session/state/test_serialize_session.py
+++ b/tests/_session/state/test_serialize_session.py
@@ -6,6 +6,7 @@ import sys
import tempfile
from pathlib import Path
+import msgspec
import pytest
from marimo import __version__
@@ -13,6 +14,7 @@ from marimo._ast.cell import CellConfig, RuntimeStateType
from marimo._ast.cell_manager import CellManager
from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._messaging.errors import MarimoExceptionRaisedError, UnknownError
+from marimo._messaging.msgspec_encoder import asdict
from marimo._messaging.notebook.document import NotebookCell, NotebookDocument
from marimo._messaging.notification import (
CellNotification,
@@ -119,6 +121,137 @@ def test_serialize_session_with_error(session_view: SessionView):
snapshot("error_session.json", json.dumps(result, indent=2))
[email protected]("dictionary", [False, True])
+def test_exception_type_survives_cache_round_trip(
+ session_view: SessionView, *, dictionary: bool
+) -> None:
+ error = MarimoExceptionRaisedError(
+ msg="bad value",
+ exception_type="ValueError",
+ raising_cell=None,
+ )
+ session_view.cell_notifications[CELL1] = _make_cell_notification(
+ CELL1,
+ output=CellOutput.errors(
+ [asdict(error) if dictionary else error], # type: ignore[list-item]
+ ),
+ )
+ session_view.last_executed_code[CELL1] = "raise ValueError('bad value')"
+ saved = serialize_session_view(
+ session_view, [CELL1], drop_virtual_file_outputs=False
+ )
+ assert saved["cells"][0]["outputs"] == [
+ {
+ "type": "error",
+ "ename": "ValueError",
+ "evalue": "bad value",
+ "traceback": [],
+ }
+ ]
+ restored = deserialize_session(
+ saved, _build_code_hash_to_cell_id_mapping(saved)
+ )
+ output = restored.cell_notifications[CELL1].output
+ assert output is not None
+ assert output.data == [error]
+
+
[email protected]("dictionary", [False, True])
[email protected]("traceback_format", ["text", "html"])
+def test_error_evidence_survives_cache_round_trip(
+ session_view: SessionView, *, dictionary: bool, traceback_format: str
+) -> None:
+ code = "raise ValueError('failed code')"
+ traceback = (
+ '<span class="codehilite"><pre>ValueError: failed code\n</pre></span>'
+ )
+ error = MarimoExceptionRaisedError(
+ msg="failed code",
+ exception_type="ValueError",
+ raising_cell=None,
+ traceback=traceback,
+ )
+ output = CellOutput.errors(
+ [asdict(error) if dictionary else error], # type: ignore[list-item]
+ code=code,
+ )
+ session_view.add_notification(
+ _make_cell_notification(
+ CELL1,
+ output=output,
+ console=[
+ CellOutput(
+ channel=CellChannel.STDERR,
+ mimetype="application/vnd.marimo+traceback",
+ data=traceback,
+ code=code,
+ traceback_format=traceback_format, # type: ignore[arg-type]
+ )
+ ],
+ )
+ )
+ session_view.add_notification(
+ CellNotification(cell_id=CELL1, status="queued")
+ )
+ session_view.last_executed_code[CELL1] = "newer code"
+ saved = serialize_session_view(
+ session_view, [CELL1], drop_virtual_file_outputs=False
+ )
+ saved_error = saved["cells"][0]["outputs"][0]
+ assert saved_error["type"] == "error"
+ assert saved_error["code"] == code
+ assert saved_error["traceback"] == [traceback]
+ restored = deserialize_session(
+ saved, _build_code_hash_to_cell_id_mapping(saved)
+ )
+ notification = restored.cell_notifications[CELL1]
+ assert notification.output is not None
+ assert notification.output.code == code
+ assert notification.output.data == [error]
+ assert isinstance(notification.console, list)
+ assert notification.console[0].code == code
+ assert notification.console[0].data == traceback
+ assert notification.console[0].traceback_format == traceback_format
+
+
+ ("entries", "expected"),
+ [
+ ([], None),
+ (["Traceback", "ValueError: bad"], "Traceback\nValueError: bad"),
+ (["Traceback\n", "ValueError: bad"], "Traceback\nValueError: bad"),
+ (["<pre>ValueError: bad\n</pre>"], "<pre>ValueError: bad\n</pre>"),
+ ("<pre>ValueError: bad\n</pre>", "<pre>ValueError: bad\n</pre>"),
+ ],
+)
+def test_restored_legacy_traceback_preserves_boundaries(
+ session_view: SessionView,
+ entries: list[str] | str,
+ expected: str | None,
+) -> None:
+ session_view.cell_notifications[CELL1] = _make_cell_notification(
+ CELL1, output=CellOutput.errors([UnknownError(msg="bad")])
+ )
+ session_view.last_executed_code[CELL1] = "legacy code"
+ saved = serialize_session_view(
+ session_view, [CELL1], drop_virtual_file_outputs=False
+ )
+ error = saved["cells"][0]["outputs"][0]
+ assert error["type"] == "error"
+ error["ename"] = "exception"
+ error["traceback"] = entries # type: ignore[typeddict-item]
+ restored = deserialize_session(
+ saved, _build_code_hash_to_cell_id_mapping(saved)
+ )
+ output = restored.cell_notifications[CELL1].output
+ assert output is not None
+ assert output.code is msgspec.UNSET
+ assert isinstance(output.data, list)
+ assert isinstance(output.data[0], MarimoExceptionRaisedError)
+ assert output.data[0].exception_type == "exception"
+ assert output.data[0].traceback == expected
+
+
def test_serialize_session_with_console(session_view: SessionView):
"""Test serialization of a session with console output"""
view = session_view
@@ -1002,9 +1135,9 @@ def test_serialize_session_with_mixed_error_formats(session_view: SessionView):
# Check first error (dictionary with explicit no traceback)
error1 = cell["outputs"][0]
assert error1["type"] == "error"
- assert error1["ename"] == "exception"
+ assert error1["ename"] == "ValueError"
assert error1["evalue"] == "Invalid value"
- assert error1["traceback"] is None
+ assert error1["traceback"] == []
# Check second error (object format)
error2 = cell["outputs"][1]
diff --git a/tests/_session/state/test_session_view.py b/tests/_session/state/test_session_view.py
index 33927364b8..e408edad7a 100644
--- a/tests/_session/state/test_session_view.py
+++ b/tests/_session/state/test_session_view.py
@@ -1,6 +1,7 @@
# 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
@@ -8,6 +9,7 @@ import msgspec
import pytest
from marimo._ast.cell import RuntimeStateType
+from marimo._core.protocol import Attachment, NotebookId
from marimo._data.models import (
Database,
DataSourceConnection,
@@ -19,6 +21,7 @@ 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,
@@ -85,6 +88,54 @@ 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 40e6980ceb..d13f040f78 100644
--- a/tests/_session/test_notification_ordering.py
+++ b/tests/_session/test_notification_ordering.py
@@ -11,7 +11,10 @@ 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,
@@ -37,8 +40,9 @@ 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 ConsumerId, SessionId
+from marimo._types.ids import CellId_t, 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
@@ -114,6 +118,49 @@ 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: