A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat(pair): deliver notebook messages to native agent inboxes (#11330)
Kiran Gadhavea27e12b4a402
diff --git a/docs/guides/generate_with_ai/marimo_pair.md b/docs/guides/generate_with_ai/marimo_pair.mdindex 223cb1a30f..8932439018 100644--- a/docs/guides/generate_with_ai/marimo_pair.md+++ b/docs/guides/generate_with_ai/marimo_pair.md@@ -1,7 +1,7 @@# Collaborate with agents using marimo pair-Give your agent CLIs (such as Claude Code, Codex, and OpenCode) full access to running marimo notebooks with the **[marimo-pair](https://marimo.io/pair)** agent skill.+Use the **[marimo pair](https://marimo.io/pair)** CLI to connect coding agents+to running marimo notebooks.marimo pair is the recommended way to collaborate on marimo notebooks withagents. It lets your agent read variables, test logic in a scratchpad, run@@ -17,38 +17,75 @@ cells, add and remove cells, and even manipulate UI elements.## Quickstart-Install the skill with:+1. Start a notebook:-/// tab | install with npm+ ```bash+ uvx marimo@latest edit my_notebook.py+ ```-```bash-npx skills add marimo-team/marimo-pair-```+2. Open the notebook actions menu and select **Connect your agent**.+3. Select **Claude**, **Codex**, or **OpenCode** and run the copied command in your terminal.++To use an existing agent conversation, select **Prompt** and paste the copied text into that conversation.+The dialog includes the notebook target and authentication instructions.++Your agent can execute code without enabling agent messages.+Run `uvx marimo@latest pair --help` for the available commands.-///+## Receive notebook messages in your agent-/// tab | install with uv+Agent messages let you send notebook errors to a connected conversation.+This preview requires host support on the marimo server.+Agent connections require a saved notebook inside the server project.++Start the server with:```bash-uvx deno -A npm:skills add marimo-team/marimo-pair+MARIMO_ENABLE_HOST=1 uvx marimo@latest edit my_notebook.py```-///+If the server is already running, restart it with this setting.+Then open **Connect your agent** and follow the dialog instructions.++Supported agents have these requirements:++| Agent | Requirement |+| --- | --- |+| Codex | A native session with the shared daemon and `codex queue` support. |+| Claude Code | A native inbox session on macOS or Linux. |+| OpenCode | Version 2.x on macOS or Linux, with its native local service running. |-Then pair on your first notebook by pasting the following in your agent CLI:+To connect an existing conversation manually, find the saved notebook ID:+```bash+uvx marimo@latest pair notebook list --url http://localhost:2718```-/marimo-pair pair with me on my_notebook.py++Ask the agent to run this command through its own shell tool:++```bash+uvx marimo@latest pair connect --url http://localhost:2718 --notebook <notebook-id>```+Use the server URL printed by marimo.+In a development checkout, use the backend URL rather than the Vite frontend URL.+For authenticated notebook discovery, pass `--token-file` with the path to a file containing the editor token.++The notebook footer shows connected agents.+Use the send action on an error to share its captured source and traceback.+To end delivery, select the disconnect icon in the footer and confirm **Disconnect?**.+The agent conversation and notebook kernel keep running.+## Cloud sandbox with molabYou can also connect to marimo notebooks running on [molab](https://molab.marimo.io/notebooks). This gives you a free sandbox for your agent and also makes it easy to share your work afterwards.-To connect an agent, start a notebook on molab and open the actions panel in the upper right corner. From this menu you need to click "Pair with an agent".+To connect an agent, start a notebook on molab and open the actions panel in the upper right corner.+Select the option to pair with an agent.<div align="center"><img src="/_static/marimo-pair-molab.png" alt="Screenshot of a molab notebook showing the option to pair with an agent from the actions panel"/></div>-This will open up a menu with all the instructions to connect your local agent. You can then use your agent from the terminal as normal, but all the Python code would be written into the notebook in the molab sandbox.+Follow the dialog instructions to connect your local agent.+Use your agent from the terminal to edit and run cells in the molab notebook.diff --git a/frontend/src/__tests__/fixtures/pair-preview.ts b/frontend/src/__tests__/fixtures/pair-config.tssimilarity index 76%rename from frontend/src/__tests__/fixtures/pair-preview.tsrename to frontend/src/__tests__/fixtures/pair-config.tsindex 6c53e89ab0..c0ed8e29b6 100644--- a/frontend/src/__tests__/fixtures/pair-preview.ts+++ b/frontend/src/__tests__/fixtures/pair-config.ts@@ -2,11 +2,12 @@import { readFileSync } from "node:fs";import path from "node:path";-import { pairPreviewSchema } from "@/core/config/pair";+import { pairConfigSchema } from "@/core/config/pair";// Read the Python-owned resource only in tests to check the shared contract.-export const PAIR_PREVIEW = pairPreviewSchema.parse({+export const PAIR_CONFIG = pairConfigSchema.parse({command: "uvx marimo@latest",+ hostEnabled: true,templates: JSON.parse(readFileSync(path.resolve(diff --git a/frontend/src/__tests__/mount.test.ts b/frontend/src/__tests__/mount.test.tsindex ca96b30b47..72140c4b80 100644--- a/frontend/src/__tests__/mount.test.ts+++ b/frontend/src/__tests__/mount.test.ts@@ -8,8 +8,8 @@ import { connectionAtom } from "@/core/network/connection";import { store } from "@/core/state/jotai";import { isStaticNotebook } from "@/core/static/static-state";import { ConnectionState } from "@/core/websocket/types";-import { pairPreviewAtom } from "@/core/config/pair";-import { PAIR_PREVIEW } from "./fixtures/pair-preview";+import { pairConfigAtom } from "@/core/config/pair";+import { PAIR_CONFIG } from "./fixtures/pair-config";import { mount, visibleForTesting } from "../mount";// Mock React DOM@@ -84,20 +84,20 @@ describe("mount", () => {mockElement,);- it("hydrates the server's Pair preview configuration", () => {- const error = mountRead({ pairPreview: PAIR_PREVIEW });+ it("hydrates the server's Pair configuration", () => {+ const error = mountRead({ pairConfig: PAIR_CONFIG });expect(error).toBeUndefined();- expect(store.get(pairPreviewAtom)).toEqual(PAIR_PREVIEW);+ expect(store.get(pairConfigAtom)).toEqual(PAIR_CONFIG);});- it("uses legacy Pair behavior when the host omits preview configuration", () => {- store.set(pairPreviewAtom, PAIR_PREVIEW);+ it("clears Pair configuration when the server omits it", () => {+ store.set(pairConfigAtom, PAIR_CONFIG);const error = mountRead();expect(error).toBeUndefined();- expect(store.get(pairPreviewAtom)).toBeUndefined();+ expect(store.get(pairConfigAtom)).toBeUndefined();});describe("connection state initialization", () => {diff --git a/frontend/src/components/editor/Output.tsx b/frontend/src/components/editor/Output.tsxindex aedad0744b..4d0efb27a9 100644--- a/frontend/src/components/editor/Output.tsx+++ b/frontend/src/components/editor/Output.tsx@@ -66,7 +66,10 @@ export type OnRefactorWithAI = (opts: {* Renders an output based on an OutputMessage.*/export const OutputRenderer: React.FC<{- message: Pick<OutputMessage, "channel" | "data" | "mimetype" | "code">;+ message: Pick<+ OutputMessage,+ "channel" | "data" | "mimetype" | "code" | "traceback_format"+ >;cellId?: CellId;onRefactorWithAI?: OnRefactorWithAI;wrapText?: boolean;@@ -185,6 +188,7 @@ export const OutputRenderer: React.FC<{<MarimoTracebackOutputonRefactorWithAI={onRefactorWithAI}traceback={data}+ tracebackFormat={message.traceback_format}code={message.code}cellId={cellId}/>diff --git a/frontend/src/components/editor/actions/__tests__/pair-with-agent-commands.test.ts b/frontend/src/components/editor/actions/__tests__/pair-with-agent-commands.test.tsindex cd59d075bf..ce556bdd00 100644--- a/frontend/src/components/editor/actions/__tests__/pair-with-agent-commands.test.ts+++ b/frontend/src/components/editor/actions/__tests__/pair-with-agent-commands.test.ts@@ -1,50 +1,34 @@/* Copyright 2026 Marimo. All rights reserved. */import { afterEach, describe, expect, it, vi } from "vitest";+import { PAIR_CONFIG } from "@/__tests__/fixtures/pair-config";+import { shellQuote } from "@/utils/shell";import {type ConnectionInfo,- getFileFromURL,getMarimoCommand,getRawPrompt,getTerminalCommand,maskToken,} from "../pair-with-agent-commands";-import { shellQuote } from "@/utils/shell";-import { PAIR_PREVIEW } from "@/__tests__/fixtures/pair-preview";const CONNECTION: ConnectionInfo = {url: "http://localhost:8000",- file: "notebooks/example.py",- session: "s_ab12cd",+ notebook: "nb-one",};--const CONNECTION_WITHOUT_FILE: ConnectionInfo = {+const CONNECTION_WITHOUT_TARGET: ConnectionInfo = {url: "http://localhost:8000",};describe("shellQuote", () => {- it("quotes an empty string", () => {+ it("quotes empty and unsafe arguments", () => {expect(shellQuote("")).toBe("''");- });-- it("leaves shell-safe values untouched", () => {expect(shellQuote("http://localhost:8000")).toBe("http://localhost:8000");- expect(shellQuote("notebooks/example.py")).toBe("notebooks/example.py");- });-- it("quotes values with shell metacharacters", () => {expect(shellQuote("http://host:8000?a=1&b=2")).toBe("'http://host:8000?a=1&b=2'",);- expect(shellQuote("has space")).toBe("'has space'");expect(shellQuote("$(rm -rf /)")).toBe("'$(rm -rf /)'");- });-- it("escapes embedded single quotes without breaking out", () => {- // Closes the quote, emits a literal ' via "'", then reopens: '"'"'expect(shellQuote("a'b")).toBe(`'a'"'"'b'`);});-it.each([["/tmp/my notebook.py", "'/tmp/my notebook.py'"],[@@ -55,267 +39,115 @@ describe("shellQuote", () => {String.raw`\\server\share\my notebook.py`,String.raw`'\\server\share\my notebook.py'`,],- ])("quotes non-portable path %s as one argument", (path, expected) => {+ ])("quotes path %s as one argument", (path, expected) => {expect(shellQuote(path)).toBe(expected);});});-describe("getFileFromURL", () => {- it("returns undefined when the file query parameter is absent or empty", () => {- expect(getFileFromURL("http://localhost:8000")).toBeUndefined();- expect(getFileFromURL("http://localhost:8000?file=")).toBeUndefined();- });-- it("decodes spaces and literal plus signs", () => {- expect(- getFileFromURL(- "http://localhost:8000?file=relative%2Fmy%20notebook%2Bdata.py",- ),- ).toBe("relative/my notebook+data.py");- expect(getFileFromURL("http://localhost:8000?file=my+notebook.py")).toBe(- "my notebook.py",- );- });-- it("preserves decoded Windows paths and uses the first duplicate value", () => {- expect(- getFileFromURL(- "http://localhost:8000?file=C%3A%5CUsers%5CJane%20Doe%5Cnotebook.py",- ),- ).toBe(String.raw`C:\Users\Jane Doe\notebook.py`);- expect(- getFileFromURL("http://localhost:8000?file=first.py&file=second.py"),- ).toBe("first.py");- });-});-describe("getMarimoCommand", () => {- afterEach(() => {- vi.unstubAllEnvs();- });-- it("uses the local checkout in dev", () => {+ afterEach(() => vi.unstubAllEnvs());+ it("uses the checkout command in development", () => {vi.stubEnv("DEV", true);expect(getMarimoCommand()).toBe("uv run marimo");});-- it("uses uvx outside of dev", () => {+ it("uses uvx outside development", () => {vi.stubEnv("DEV", false);expect(getMarimoCommand()).toBe("uvx marimo@latest");});});describe("getTerminalCommand", () => {- it("uses the preview launcher in production and quotes session-only targets", () => {- vi.stubEnv("DEV", false);- try {- expect(- getTerminalCommand(- "claude",- { url: "http://host:8000?a=1&b=2", session: "s_' {file}" },- false,- { ...PAIR_PREVIEW, command: "uvx marimo@latest" },- ),- ).toBe(- String.raw`claude "$(MARIMO_PAIR_NEXT=1 uvx marimo@latest pair prompt \- --url 'http://host:8000?a=1&b=2' \- --session 's_'"'"' {file}')"`,- );- expect(- getTerminalCommand(- "codex",- CONNECTION_WITHOUT_FILE,- false,- PAIR_PREVIEW,- ),- ).toBe(- String.raw`codex "$(MARIMO_PAIR_NEXT=1 uvx marimo@latest pair prompt \- --url http://localhost:8000)"`,- );- } finally {- vi.unstubAllEnvs();- }- });-it.each([["claude", "claude"],["codex", "codex"],["opencode", "opencode --prompt"],- ] as const)(- "enables the preview inside the %s prompt command",- (agent, cli) => {- expect(- getTerminalCommand(- agent,- { ...CONNECTION, session: "s_ab12cd" },- true,- PAIR_PREVIEW,- ),- ).toBe(- String.raw`${cli} "$(MARIMO_PAIR_NEXT=1 uvx marimo@latest pair prompt \- --url http://localhost:8000 \- --session s_ab12cd \- --with-token)"`,- );- },- );-- it("includes the url and agent flag for each agent", () => {- expect(getTerminalCommand("claude", CONNECTION, false)).toBe(- `claude "$(uv run marimo pair prompt --url http://localhost:8000 --claude)"`,- );- expect(getTerminalCommand("codex", CONNECTION, false)).toBe(- `codex "$(uv run marimo pair prompt --url http://localhost:8000 --codex)"`,- );- expect(getTerminalCommand("opencode", CONNECTION, false)).toBe(- `opencode --prompt "$(uv run marimo pair prompt --url http://localhost:8000 --opencode)"`,+ ] as const)("launches %s through the public CLI", (agent, cli) => {+ expect(getTerminalCommand(agent, CONNECTION, true, PAIR_CONFIG)).toBe(+ `${cli} "$(uvx marimo@latest pair prompt \\\n --url http://localhost:8000 \\\n --notebook nb-one \\\n --with-token)"`,);});-- it("never passes a file to marimo pair prompt", () => {- const command = getTerminalCommand("claude", CONNECTION, false);- expect(command).not.toContain("--file");- expect(command).not.toContain("notebooks/example.py");- });-- it("omits the session outside the preview", () => {- expect(getTerminalCommand("claude", CONNECTION, false)).not.toContain(- "--session",- );- });-- it("omits the session when it is unknown", () => {- expect(- getTerminalCommand(- "claude",- CONNECTION_WITHOUT_FILE,- false,- PAIR_PREVIEW,- ),- ).not.toContain("--session");- });-- it("shell-escapes a url containing metacharacters", () => {+ it("uses a stable Session ID for editor execution", () => {const command = getTerminalCommand("claude",- { url: "http://host:8000?auth=a&b" },+ { url: "http://host:8000?a=1&b=2", session: "stable_' {file}" },false,+ PAIR_CONFIG,);- expect(command).toContain("--url 'http://host:8000?auth=a&b'");- });-- it("adds --with-token before the agent flag when requested", () => {- const command = getTerminalCommand("claude", CONNECTION, true);- expect(command).toContain("--with-token --claude");+ expect(command).toContain("--url 'http://host:8000?a=1&b=2'");+ expect(command).toContain(`--session 'stable_'"'"' {file}'`);+ expect(command).not.toContain("--notebook");});-- it("omits --with-token when not requested", () => {- expect(getTerminalCommand("claude", CONNECTION, false)).not.toContain(- "--with-token",+ it("prefers the verified Notebook ID to a Session ID", () => {+ const command = getTerminalCommand(+ "codex",+ { ...CONNECTION, session: "stable-one" },+ false,+ PAIR_CONFIG,);+ expect(command).toContain("--notebook nb-one");+ expect(command).not.toContain("stable-one");+ expect(command).not.toContain("--with-token");+ });+ it("uses the CLI without injected configuration", () => {+ vi.stubEnv("DEV", true);+ try {+ const command = getTerminalCommand(+ "claude",+ CONNECTION_WITHOUT_TARGET,+ false,+ );+ expect(command).toContain("uv run marimo pair prompt");+ expect(command).not.toMatch(+ /--claude|MARIMO_PAIR_NEXT|--file|--session|--notebook/,+ );+ } finally {+ vi.unstubAllEnvs();+ }});});describe("getRawPrompt", () => {- it("uses supplied templates without reinterpreting inserted values", () => {- expect(- getRawPrompt(- {- url: "http://host/{session}",- session: "{command}/it's",- },- "tok'en {session} $&",- {- ...PAIR_PREVIEW,- command: "custom marimo",- templates: {- ...PAIR_PREVIEW.templates,- prompt: "{command}\n{url}\n{session}{authentication}",- },+ it("does not interpret placeholders in inserted values", () => {+ const prompt = getRawPrompt(+ { url: "http://host/{session}", notebook: "{command}/it's" },+ "tok'en {session} $&",+ {+ ...PAIR_CONFIG,+ command: "custom marimo",+ templates: {+ ...PAIR_CONFIG.templates,+ prompt: "{command}\n{url}\n{notebook}{authentication}",},- ),- ).toBe(- "custom marimo\nhttp://host/{session}\nSession: {command}/it's\n" +- `\n\nFor authenticated Pair commands, set \`export MARIMO_TOKEN='tok'"'"'en {session} $&'\` in the shell that runs marimo.`,+ },+ );+ expect(prompt).toBe(+ "custom marimo\nhttp://host/{session}\nNotebook: {command}/it's\n" ++ `\n\nFor authenticated notebook discovery, set \`export MARIMO_TOKEN='tok'"'"'en {session} $&'\` in the shell that runs marimo.`,);});-it.each([- [CONNECTION_WITHOUT_FILE, ""],+ [CONNECTION_WITHOUT_TARGET, ""],+ [CONNECTION, "Notebook: nb-one\n"],[- { ...CONNECTION_WITHOUT_FILE, session: "s_ab12cd" },- "Session: s_ab12cd\n",+ { ...CONNECTION_WITHOUT_TARGET, session: "stable-one" },+ "Session: stable-one\n",],- [{ ...CONNECTION_WITHOUT_FILE, file: "notebook.py" }, ""],- ])("omits absent preview fields for %j", (connection, fields) => {- expect(getRawPrompt(connection, null, PAIR_PREVIEW)).toBe(- "Pair with me on this running marimo notebook.\n\n" +- `URL: http://localhost:8000\n${fields}\n` +- "Run `uvx marimo@latest pair --help` first.\n" +- "Use `uvx marimo@latest` for all marimo commands.\n\n" +- "Once connected, send a fun toast using `mo.status.toast(...)` (`import marimo as mo`).",- );- });-- it("renders the shared preview template with the session and no file", () => {+ ])("renders the shared CLI prompt for %j", (connection, target) => {+ const expected = `Pair with me on this running marimo notebook.\n\nURL: http://localhost:8000\n${target}\nRun \`uvx marimo@latest pair --help\` first.\nUse \`uvx marimo@latest\` for all marimo commands.`;+ expect(getRawPrompt(connection, null, PAIR_CONFIG)).toBe(expected);expect(- getRawPrompt({ ...CONNECTION, session: "s_ab12cd" }, null, PAIR_PREVIEW),- ).toBe(- "Pair with me on this running marimo notebook.\n\n" +- "URL: http://localhost:8000\n" +- "Session: s_ab12cd\n\n" +- "Run `uvx marimo@latest pair --help` first.\n" +- "Use `uvx marimo@latest` for all marimo commands.\n\n" +- "Once connected, send a fun toast using `mo.status.toast(...)` (`import marimo as mo`).",- );+ getRawPrompt(connection, null, { ...PAIR_CONFIG, hostEnabled: false }),+ ).toBe(expected);});-- it("references the file-scoped execute-code command", () => {- const prompt = getRawPrompt(CONNECTION, null);- expect(prompt).toContain(- "execute-code.sh --url http://localhost:8000 --file notebooks/example.py",- );- expect(prompt).toContain(- "Connect to the notebook at: http://localhost:8000 (file notebooks/example.py)",- );- });-- it("omits file targeting when the page URL has no file", () => {- const prompt = getRawPrompt(CONNECTION_WITHOUT_FILE, null);- expect(prompt).toContain("execute-code.sh --url http://localhost:8000");- expect(prompt).not.toContain("--file");- expect(prompt).not.toContain("--session");- });-- it("omits the token hint when there is no token", () => {- const prompt = getRawPrompt(CONNECTION, null);- expect(prompt).not.toContain("--token");- expect(prompt).not.toContain("auth token");- });-- it("includes a file-scoped token hint when a token is present", () => {- const prompt = getRawPrompt(CONNECTION, "secret-token");- expect(prompt).toContain(- "execute-code.sh --url http://localhost:8000 --file notebooks/example.py --token secret-token",- );- });-- it("shell-escapes a token containing a single quote", () => {- const prompt = getRawPrompt(CONNECTION, "tok'en");- expect(prompt).toContain(`--token 'tok'"'"'en'`);- });-- it("matches the CLI prompt shape", () => {- const prompt = getRawPrompt(CONNECTION, null);- expect(prompt).toMatchInlineSnapshot(`- "Use the /marimo-pair skill to pair-program on a running marimo notebook.-- Connect to the notebook at: http://localhost:8000 (file notebooks/example.py)-- Use \`execute-code.sh --url http://localhost:8000 --file notebooks/example.py\` from the marimo-pair skill to execute code in the notebook.-- Once you are connected, send a fun toast (mo.status.toast(...)) to the user inside marimo letting them know you're ready to pair."- `);+ it("matches the shared prompt without injected templates", () => {+ vi.stubEnv("DEV", false);+ try {+ expect(getRawPrompt(CONNECTION, "secret-token")).toBe(+ getRawPrompt(CONNECTION, "secret-token", PAIR_CONFIG),+ );+ } finally {+ vi.unstubAllEnvs();+ }});});@@ -324,12 +156,8 @@ describe("maskToken", () => {expect(maskToken("ab")).toBe("****");expect(maskToken("abcd")).toBe("****");});-- it("reveals only the last four characters", () => {- expect(maskToken("abcdefgh")).toBe("****efgh");- });-- it("caps the number of mask characters at eight", () => {- expect(maskToken("0123456789abcdef")).toBe("********cdef");- });+ it("reveals only the last four characters", () =>+ expect(maskToken("abcdefgh")).toBe("****efgh"));+ it("caps mask characters at eight", () =>+ expect(maskToken("0123456789abcdef")).toBe("********cdef"));});diff --git a/frontend/src/components/editor/actions/__tests__/pair-with-agent-modal.test.tsx b/frontend/src/components/editor/actions/__tests__/pair-with-agent-modal.test.tsxindex 3f55d63326..f9d47a873a 100644--- a/frontend/src/components/editor/actions/__tests__/pair-with-agent-modal.test.tsx+++ b/frontend/src/components/editor/actions/__tests__/pair-with-agent-modal.test.tsx@@ -11,10 +11,10 @@ import {import { Provider } from "jotai";import type React from "react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { PAIR_PREVIEW } from "@/__tests__/fixtures/pair-preview";+import { PAIR_CONFIG } from "@/__tests__/fixtures/pair-config";import { Dialog } from "@/components/ui/dialog";import { TooltipProvider } from "@/components/ui/tooltip";-import { pairPreviewAtom } from "@/core/config/pair";+import { pairConfigAtom } from "@/core/config/pair";import {type StableSessionId,stableSessionIdAtom,@@ -26,6 +26,7 @@ import {} from "@/core/runtime/config";import { store } from "@/core/state/jotai";import { PairWithAgentModal } from "../pair-with-agent-modal";+import { Deferred } from "@/utils/Deferred";import { copyToClipboard } from "@/utils/copy";vi.mock("@/utils/copy", () => ({@@ -43,11 +44,24 @@ function wrapper({ children }: { children: React.ReactNode }) {}const STABLE_ID = "sess-stable-1" as StableSessionId;+const NOTEBOOK_ID = "nb-one";+function responseFor(url: string | URL | Request, token: string | null = null) {+ return Promise.resolve(+ new Response(+ JSON.stringify(+ String(url).endsWith("/api/sessions")+ ? { one: { session_id: STABLE_ID, notebook_id: NOTEBOOK_ID } }+ : { token },+ ),+ { headers: { "Content-Type": "application/json" } },+ ),+ );+}describe("PairWithAgentModal", () => {beforeEach(() => {vi.clearAllMocks();- store.set(pairPreviewAtom, PAIR_PREVIEW);+ store.set(pairConfigAtom, PAIR_CONFIG);store.set(stableSessionIdAtom, STABLE_ID);store.set(filenameAtom, "/project/my notebook.py");store.set(runtimeConfigAtom, {@@ -57,19 +71,19 @@ describe("PairWithAgentModal", () => {window.history.replaceState({}, "", "/?file=notebook.py");vi.stubGlobal("fetch",- vi.fn().mockResolvedValue(new Response(JSON.stringify({ token: null }))),+ vi.fn().mockImplementation((url) => responseFor(url)),);});afterEach(() => {- store.set(pairPreviewAtom, undefined);+ store.set(pairConfigAtom, undefined);store.set(stableSessionIdAtom, null);store.set(filenameAtom, null);vi.unstubAllGlobals();});it.each(["Claude", "Codex", "OpenCode", "Prompt"])(- "omits skill installation and targets the stable session in %s preview",+ "targets the verified host Notebook in %s",async (tab) => {await act(async () => {render(<PairWithAgentModal onClose={vi.fn()} />, { wrapper });@@ -81,10 +95,13 @@ describe("PairWithAgentModal", () => {const panel = screen.getByRole("tabpanel");expect(within(panel).queryAllByText(/skill/i)).toEqual([]);- expect(panel).toHaveTextContent(STABLE_ID);+ expect(panel).toHaveTextContent(NOTEBOOK_ID);expect(panel).not.toHaveTextContent("--file");expect(panel).not.toHaveTextContent("File:");expect(panel).not.toHaveTextContent("notebook.py");+ expect(+ panel.textContent?.includes("Agent connections require OpenCode 2.x"),+ ).toBe(tab === "OpenCode");expect(panel).toHaveTextContent(tab === "Prompt" ? "1. Copy this prompt" : "1. Run in your terminal",);@@ -95,13 +112,15 @@ describe("PairWithAgentModal", () => {);await waitFor(() => expect(copyToClipboard).toHaveBeenCalledOnce());const copied = vi.mocked(copyToClipboard).mock.calls[0][0];- expect(copied).toContain(STABLE_ID);+ expect(copied).toContain(NOTEBOOK_ID);expect(copied).not.toContain("notebook.py");+ expect(copied).not.toContain(STABLE_ID);+ expect(panel).not.toHaveTextContent(STABLE_ID);},);it.each(["Claude", "Prompt"])(- "omits the session in %s preview before kernel-ready arrives",+ "waits for kernel-ready before copying the %s target",async (tab) => {store.set(stableSessionIdAtom, null);await act(async () => {@@ -113,17 +132,21 @@ describe("PairWithAgentModal", () => {});const panel = screen.getByRole("tabpanel");- expect(panel).not.toHaveTextContent("--session");- expect(panel).not.toHaveTextContent("Session:");+ expect(panel).not.toHaveTextContent("--notebook");+ expect(panel).not.toHaveTextContent("Notebook:");expect(panel).toHaveTextContent("http://localhost:8000");+ expect(+ within(panel).getByRole("button", {+ name: tab === "Prompt" ? "Copy prompt" : "Copy command",+ }),+ ).toBeDisabled();},);it.each(["Claude", "Codex", "OpenCode", "Prompt"])(- "preserves the %s skill flow without preview configuration",+ "uses the editor CLI in %s when host is disabled",async (tab) => {- store.set(pairPreviewAtom, undefined);- window.history.replaceState({}, "", "/");+ store.set(pairConfigAtom, { ...PAIR_CONFIG, hostEnabled: false });await act(async () => {render(<PairWithAgentModal onClose={vi.fn()} />, { wrapper });});@@ -131,27 +154,33 @@ describe("PairWithAgentModal", () => {button: 0,ctrlKey: false,});-const panel = screen.getByRole("tabpanel");- expect(- within(panel).getByText("npx skills add marimo-team/marimo-pair"),- ).toBeVisible();- expect(panel).not.toHaveTextContent(STABLE_ID);- expect(panel).not.toHaveTextContent("--file");+ expect(panel).toHaveTextContent(STABLE_ID);+ expect(panel).not.toHaveTextContent(NOTEBOOK_ID);+ expect(panel).not.toHaveTextContent("skill");+ expect(panel).not.toHaveTextContent("Agent connections require");expect(panel).not.toHaveTextContent("MARIMO_PAIR_NEXT");- expect(panel).not.toHaveTextContent("/project/my notebook.py");- expect(panel).toHaveTextContent(- tab === "Prompt" ? "2. Copy this prompt" : "2. Run in your terminal",+ fireEvent.click(+ within(panel).getByRole("button", {+ name: tab === "Prompt" ? "Copy prompt" : "Copy command",+ }),);+ await waitFor(() => expect(copyToClipboard).toHaveBeenCalledOnce());+ expect(vi.mocked(copyToClipboard).mock.calls[0][0]).toContain(STABLE_ID);+ expect(+ vi+ .mocked(fetch)+ .mock.calls.some(([url]) => String(url).endsWith("/api/sessions")),+ ).toBe(false);},);it.each([true, false])(- "masks the raw token but copies it intact (preview=%s)",- async (preview) => {- store.set(pairPreviewAtom, preview ? PAIR_PREVIEW : undefined);- vi.mocked(fetch).mockResolvedValue(- new Response(JSON.stringify({ token: "secret-token" })),+ "masks the raw token but copies it intact (host mode=%s)",+ async (hostEnabled) => {+ store.set(pairConfigAtom, { ...PAIR_CONFIG, hostEnabled });+ vi.mocked(fetch).mockImplementation((url) =>+ responseFor(url, "secret-token"),);await act(async () => {render(<PairWithAgentModal onClose={vi.fn()} />, { wrapper });@@ -169,7 +198,7 @@ describe("PairWithAgentModal", () => {);await waitFor(() => expect(copyToClipboard).toHaveBeenCalledOnce());expect(vi.mocked(copyToClipboard).mock.calls[0][0]).toContain(- preview ? "export MARIMO_TOKEN=secret-token" : "--token secret-token",+ "export MARIMO_TOKEN=secret-token",);expect(vi.mocked(copyToClipboard).mock.calls[0][0]).not.toContain("********oken",@@ -177,9 +206,132 @@ describe("PairWithAgentModal", () => {},);- it("copies a preview terminal command without the token and lets the user copy the token separately", async () => {- vi.mocked(fetch).mockResolvedValue(- new Response(JSON.stringify({ token: "secret-token" })),+ it("uses the CLI when an older server omits Pair configuration", async () => {+ store.set(pairConfigAtom, undefined);+ await act(async () => {+ render(<PairWithAgentModal onClose={vi.fn()} />, { wrapper });+ });+ const panel = screen.getByRole("tabpanel");+ expect(panel).toHaveTextContent(`--session ${STABLE_ID}`);+ expect(panel).not.toHaveTextContent("skill");+ expect(screen.getByRole("button", { name: "Copy command" })).toBeEnabled();+ });++ it("ignores a previous Session's late Notebook lookup", async () => {+ const previous = new Deferred<Response>();+ const nextId = "sess-next" as StableSessionId;+ let lookups = 0;+ vi.mocked(fetch).mockImplementation((url) => {+ if (!String(url).endsWith("/api/sessions")) {+ return responseFor(url);+ }+ if (lookups++ === 0) {+ return previous.promise;+ }+ return Promise.resolve(+ new Response(+ JSON.stringify({+ next: { session_id: nextId, notebook_id: "nb-next" },+ }),+ { headers: { "Content-Type": "application/json" } },+ ),+ );+ });+ await act(async () => {+ render(<PairWithAgentModal onClose={vi.fn()} />, { wrapper });+ });+ await act(async () => store.set(stableSessionIdAtom, nextId));+ expect(screen.getByRole("tabpanel")).toHaveTextContent("nb-next");+ await act(async () =>+ previous.resolve(+ new Response(+ JSON.stringify({+ previous: { session_id: STABLE_ID, notebook_id: NOTEBOOK_ID },+ }),+ { headers: { "Content-Type": "application/json" } },+ ),+ ),+ );+ expect(screen.getByRole("tabpanel")).toHaveTextContent("nb-next");+ expect(screen.getByRole("tabpanel")).not.toHaveTextContent(NOTEBOOK_ID);+ });++ it("disables target copying while a new Session's Notebook is unverified", async () => {+ await act(async () => {+ render(<PairWithAgentModal onClose={vi.fn()} />, { wrapper });+ });+ expect(screen.getByRole("tabpanel")).toHaveTextContent(NOTEBOOK_ID);+ const pending = new Deferred<Response>();+ vi.mocked(fetch).mockImplementation((url) =>+ String(url).endsWith("/api/sessions")+ ? pending.promise+ : responseFor(url),+ );+ const nextId = "sess-stable-2" as StableSessionId;+ act(() => store.set(stableSessionIdAtom, nextId));+ expect(screen.getByRole("button", { name: "Copy command" })).toBeDisabled();+ expect(screen.getByRole("tabpanel")).not.toHaveTextContent(NOTEBOOK_ID);+ fireEvent.click(screen.getByRole("button", { name: "Copy command" }));+ expect(copyToClipboard).not.toHaveBeenCalled();+ await act(async () =>+ pending.resolve(+ new Response(+ JSON.stringify({+ next: { session_id: nextId, notebook_id: "nb-two" },+ }),+ { headers: { "Content-Type": "application/json" } },+ ),+ ),+ );+ expect(screen.getByRole("button", { name: "Copy command" })).toBeEnabled();+ fireEvent.click(screen.getByRole("button", { name: "Copy command" }));+ await waitFor(() => expect(copyToClipboard).toHaveBeenCalledOnce());+ expect(vi.mocked(copyToClipboard).mock.calls[0][0]).toContain("nb-two");+ expect(vi.mocked(copyToClipboard).mock.calls[0][0]).not.toContain(nextId);+ });++ it("uses the Session after verifying that a notebook is unsaved", async () => {+ vi.mocked(fetch).mockImplementation((url) =>+ String(url).endsWith("/api/sessions")+ ? Promise.resolve(+ new Response(+ JSON.stringify({+ one: { session_id: STABLE_ID, notebook_id: null },+ }),+ { headers: { "Content-Type": "application/json" } },+ ),+ )+ : responseFor(url),+ );+ await act(async () => {+ render(<PairWithAgentModal onClose={vi.fn()} />, { wrapper });+ });+ expect(screen.queryByRole("status")).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Copy command" })).toBeEnabled();+ expect(screen.getByRole("tabpanel")).toHaveTextContent(+ `--session ${STABLE_ID}`,+ );+ expect(screen.getByRole("tabpanel")).not.toHaveTextContent("--notebook");+ });++ it("keeps copying disabled when Notebook verification fails", async () => {+ vi.mocked(fetch).mockImplementation((url) =>+ String(url).endsWith("/api/sessions")+ ? Promise.reject(new Error("offline"))+ : responseFor(url),+ );+ await act(async () => {+ render(<PairWithAgentModal onClose={vi.fn()} />, { wrapper });+ });+ expect(screen.getByRole("status")).toHaveTextContent(+ "Could not verify this notebook",+ );+ expect(screen.getByRole("button", { name: "Copy command" })).toBeDisabled();+ });++ it("copies a host mode terminal command without the token and lets the user copy the token separately", async () => {+ vi.mocked(fetch).mockImplementation((url) =>+ responseFor(url, "secret-token"),);await act(async () => {render(<PairWithAgentModal onClose={vi.fn()} />, { wrapper });@@ -193,9 +345,9 @@ describe("PairWithAgentModal", () => {);await waitFor(() =>expect(copyToClipboard).toHaveBeenCalledWith(- String.raw`claude "$(MARIMO_PAIR_NEXT=1 uvx marimo@latest pair prompt \+ String.raw`claude "$(uvx marimo@latest pair prompt \--url http://localhost:8000/ \- --session ${STABLE_ID} \+ --notebook ${NOTEBOOK_ID} \--with-token)"`,),);diff --git a/frontend/src/components/editor/actions/pair-with-agent-commands.ts b/frontend/src/components/editor/actions/pair-with-agent-commands.tsindex 454ecdbfbb..d80e7fe63b 100644--- a/frontend/src/components/editor/actions/pair-with-agent-commands.ts+++ b/frontend/src/components/editor/actions/pair-with-agent-commands.ts@@ -1,9 +1,8 @@/* Copyright 2026 Marimo. All rights reserved. */import { assertNever } from "@/utils/assertNever";-import { KnownQueryParams } from "@/core/constants";import { shellQuote } from "@/utils/shell";-import type { PairPreviewConfig } from "@/core/config/pair";+import type { PairConfig } from "@/core/config/pair";export type AgentTab = "claude" | "codex" | "opencode" | "prompt";@@ -18,30 +17,18 @@ export const AGENT_LABELS: Record<AgentTab, string> = {prompt: "Prompt",};-export const SKILL_INSTALL = "npx skills add marimo-team/marimo-pair";-/** How to invoke marimo: from the local checkout in dev, else via uvx. */export function getMarimoCommand(): string {return import.meta.env.DEV ? "uv run marimo" : "uvx marimo@latest";}-/** Return the server file key from a page URL, preserving its decoded value. */-export function getFileFromURL(href: string): string | undefined {- const file = new URL(href).searchParams.get(KnownQueryParams.filePath);- return file === null || file === "" ? undefined : file;-}--function getFileFlag(file: string | undefined): string {- return file ? ` --file ${shellQuote(file)}` : "";-}-/** Identifies the specific running notebook to pair on. */export interface ConnectionInfo {url: string;- /** The server's file key, when known. */- file?: string;- /** The stable session ID, when known. */+ /** Stable Session ID for ordinary editor execution. */session?: string;+ /** The host notebook ID, when known. */+ notebook?: string;}/**@@ -50,21 +37,23 @@ export interface ConnectionInfo {*/export function getTerminalCommand(agent: Exclude<AgentTab, "prompt">,- { url, session }: ConnectionInfo,+ { url, notebook, session }: ConnectionInfo,withToken: boolean,- preview?: PairPreviewConfig,+ config?: PairConfig,): string {- const command = preview?.command ?? getMarimoCommand();- const prefix = preview ? "MARIMO_PAIR_NEXT=1 " : "";+ const command = config?.command ?? getMarimoCommand();const base = [- `${prefix}${command} pair prompt`,+ `${command} pair prompt`,`--url ${shellQuote(url)}`,- preview && session ? `--session ${shellQuote(session)}` : "",+ notebook+ ? `--notebook ${shellQuote(notebook)}`+ : session+ ? `--session ${shellQuote(session)}`+ : "",withToken ? "--with-token" : "",- preview ? "" : `--${agent}`,].filter(Boolean)- .join(preview ? " \\\n " : " ");+ .join(" \\\n ");switch (agent) {case "claude":return `claude "$(${base})"`;@@ -83,37 +72,39 @@ export function getTerminalCommand(* an agent behaves the same as the terminal commands.*/export function getRawPrompt(- { url, file, session }: ConnectionInfo,+ { url, notebook, session }: ConnectionInfo,token: string | null,- preview?: PairPreviewConfig,+ config?: PairConfig,): string {- if (preview) {- const { command, templates } = preview;- return formatPrompt(templates.prompt, {+ const command = config?.command ?? getMarimoCommand();+ const templates = config?.templates;+ const authentication = token+ ? formatPrompt(+ templates?.token ??+ "\n\nFor authenticated notebook discovery, set `export MARIMO_TOKEN={token}` in the shell that runs marimo.",+ { token: shellQuote(token) },+ )+ : "";+ return formatPrompt(+ templates?.prompt ??+ "Pair with me on this running marimo notebook.\n\nURL: {url}\n{notebook}{session}\nRun `{command} pair --help` first.\nUse `{command}` for all marimo commands.{authentication}",+ {command,url,- session: session ? formatPrompt(templates.session, { session }) : "",- authentication: token- ? formatPrompt(templates.token, { token: shellQuote(token) })+ notebook: notebook+ ? formatPrompt(templates?.notebook ?? "Notebook: {notebook}\n", {+ notebook,+ }): "",- });- }-- const fileFlag = getFileFlag(file);- const fileHint = file ? ` (file ${file})` : "";- const executeCmd = `execute-code.sh --url ${shellQuote(url)}${fileFlag}`;- const tokenHint = token- ? `\n\nUse this auth token when calling \`execute-code.sh\`: \`${executeCmd} --token ${shellQuote(token)}\`.`- : "";- return [- "Use the /marimo-pair skill to pair-program on a running marimo notebook.",- "",- `Connect to the notebook at: ${url}${fileHint}`,- "",- `Use \`${executeCmd}\` from the marimo-pair skill to execute code in the notebook.${tokenHint}`,- "",- "Once you are connected, send a fun toast (mo.status.toast(...)) to the user inside marimo letting them know you're ready to pair.",- ].join("\n");+ session:+ session && !notebook+ ? formatPrompt(templates?.session ?? "Session: {session}\n", {+ session,+ })+ : "",+ authentication,+ },+ );}function formatPrompt(diff --git a/frontend/src/components/editor/actions/pair-with-agent-modal.tsx b/frontend/src/components/editor/actions/pair-with-agent-modal.tsxindex 289b377eeb..4ff1e29f80 100644--- a/frontend/src/components/editor/actions/pair-with-agent-modal.tsx+++ b/frontend/src/components/editor/actions/pair-with-agent-modal.tsx@@ -17,18 +17,16 @@ import { Events } from "@/utils/events";import { Tooltip } from "@/components/ui/tooltip";import { asRemoteURL, useRuntimeManager } from "@/core/runtime/config";import { API } from "@/core/network/api";-import { pairPreviewAtom } from "@/core/config/pair";+import { pairConfigAtom } from "@/core/config/pair";import { stableSessionIdAtom } from "@/core/kernel/session";import {AGENT_LABELS,AGENT_TABS,type AgentTab,type ConnectionInfo,- getFileFromURL,getRawPrompt,getTerminalCommand,maskToken,- SKILL_INSTALL,TERMINAL_TABS,} from "./pair-with-agent-commands";@@ -52,15 +50,64 @@ export const PairWithAgentModal: React.FC<{}> = ({ onClose }) => {const [activeTab, setActiveTab] = useState<AgentTab>("claude");const runtimeManager = useRuntimeManager();- const preview = useAtomValue(pairPreviewAtom);+ const config = useAtomValue(pairConfigAtom);+ const hostEnabled = config?.hostEnabled ?? false;const stableSessionId = useAtomValue(stableSessionIdAtom);- const commandStep = preview ? 1 : 2;+ const [lookup, setLookup] = useState<+ {+ sessionId: string;+ } & (+ | { status: "ready"; notebookId: string | null }+ | { status: "loading" | "error" }+ )+ >();+ useEffect(() => {+ if (!hostEnabled || !stableSessionId) {+ setLookup(undefined);+ return;+ }+ const sessionId = stableSessionId;+ setLookup({ sessionId, status: "loading" });+ let cancelled = false;+ API.get<Record<string, { session_id: string; notebook_id: string | null }>>(+ "/sessions",+ )+ .then((sessions) => {+ if (!cancelled) {+ const session = Object.values(sessions).find(+ (session) => session.session_id === sessionId,+ );+ setLookup(+ session+ ? { sessionId, status: "ready", notebookId: session.notebook_id }+ : { sessionId, status: "error" },+ );+ }+ })+ .catch(() => {+ if (!cancelled) {+ setLookup({ sessionId, status: "error" });+ }+ });+ return () => {+ cancelled = true;+ };+ }, [hostEnabled, stableSessionId]);+ const currentLookup =+ lookup?.sessionId === stableSessionId ? lookup : undefined;+ const verified = !hostEnabled || currentLookup?.status === "ready";+ const notebookId =+ hostEnabled && currentLookup?.status === "ready"+ ? currentLookup.notebookId+ : undefined;+ const targetReady = Boolean(stableSessionId) && verified;const authToken = useAuthToken();const hasToken = Boolean(authToken);const connection: ConnectionInfo = {url: runtimeManager.httpURL.toString(),- file: preview ? undefined : getFileFromURL(window.location.href),- session: preview ? (stableSessionId ?? undefined) : undefined,+ notebook: notebookId ?? undefined,+ session:+ targetReady && !notebookId ? (stableSessionId ?? undefined) : undefined,};return (@@ -83,6 +130,13 @@ export const PairWithAgentModal: React.FC<{</DialogHeader><div className="flex flex-col gap-4 py-2">+ {!targetReady && (+ <output className="text-sm text-muted-foreground">+ {currentLookup?.status === "error"+ ? "Could not verify this notebook. Close this dialog and try again."+ : "Waiting for the notebook connection…"}+ </output>+ )}<Tabsvalue={activeTab}onValueChange={(v) => setActiveTab(v as AgentTab)}@@ -101,30 +155,27 @@ export const PairWithAgentModal: React.FC<{value={tab}className="mt-4 flex flex-col gap-4">- {!preview && (- <Step- index={1}- title="Install the skill"- hint="Run once per machine."- >- <CommandBlock command={SKILL_INSTALL} />- </Step>- )}- <Step index={commandStep} title="Run in your terminal">+ <Step+ index={1}+ title="Run in your terminal"+ hint={+ hostEnabled && tab === "opencode"+ ? "Agent connections require OpenCode 2.x."+ : undefined+ }+ ><CommandBlockcommand={getTerminalCommand(tab,connection,hasToken,- preview,+ config,)}+ disabled={!targetReady}/></Step>{hasToken && authToken && (- <Step- index={commandStep + 1}- title="Paste when prompted for a token"- >+ <Step index={2} title="Paste when prompted for a token"><CommandBlockcommand={authToken}display={maskToken(authToken)}@@ -136,17 +187,8 @@ export const PairWithAgentModal: React.FC<{))}<TabsContent value="prompt" className="mt-4 flex flex-col gap-4">- {!preview && (- <Step- index={1}- title="Make sure the marimo-pair skill is available to your agent"- hint="Skip if your agent already has it."- >- <CommandBlock command={SKILL_INSTALL} />- </Step>- )}<Step- index={commandStep}+ index={1}title="Copy this prompt into your agent"hint={hasToken@@ -155,13 +197,14 @@ export const PairWithAgentModal: React.FC<{}><CommandBlock- command={getRawPrompt(connection, authToken, preview)}+ command={getRawPrompt(connection, authToken, config)}display={getRawPrompt(connection,authToken ? maskToken(authToken) : null,- preview,+ config,)}multiline={true}+ disabled={!targetReady}/></Step></TabsContent>@@ -199,11 +242,21 @@ const CommandBlock: React.FC<{display?: string;multiline?: boolean;copyLabel?: string;-}> = ({ command, display, multiline = false, copyLabel = "Copy command" }) => {+ disabled?: boolean;+}> = ({+ command,+ display,+ multiline = false,+ copyLabel = "Copy command",+ disabled = false,+}) => {const [copied, setCopied] = useState(false);const copy = Events.stopPropagation(async (e) => {e.preventDefault();+ if (disabled) {+ return;+ }await copyToClipboard(command);setCopied(true);setTimeout(() => setCopied(false), 2000);@@ -218,6 +271,7 @@ const CommandBlock: React.FC<{<Tooltip content="Copied!" open={copied}><Buttonaria-label="Copy prompt"+ disabled={disabled}onClick={copy}size="xs"variant="ghost"@@ -240,7 +294,13 @@ const CommandBlock: React.FC<{{display ?? command}</code><Tooltip content="Copied!" open={copied}>- <Button aria-label={copyLabel} onClick={copy} size="xs" variant="ghost">+ <Button+ aria-label={copyLabel}+ onClick={copy}+ size="xs"+ variant="ghost"+ disabled={disabled}+ >{copied ? (<CheckIcon size={14} strokeWidth={1.5} />) : (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.tsxindex 6d8c21b8fd..5fffb274ff 100644--- a/frontend/src/components/editor/chrome/wrapper/__tests__/attachment-status.test.tsx+++ b/frontend/src/components/editor/chrome/wrapper/__tests__/attachment-status.test.tsx@@ -1,32 +1,48 @@/* Copyright 2026 Marimo. All rights reserved. */// @vitest-environment jsdom-import { act, fireEvent, render, screen } from "@testing-library/react";+import {+ act,+ fireEvent,+ render,+ screen,+ waitFor,+} 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 { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { PAIR_CONFIG } from "@/__tests__/fixtures/pair-config";import { TooltipProvider } from "@/components/ui/tooltip";+import { toast } from "@/components/ui/use-toast";import { type Attachment, attachmentsAtom } from "@/core/attachments/state";-import { pairPreviewAtom } from "@/core/config/pair";+import { pairConfigAtom } from "@/core/config/pair";+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 { AttachmentStatus } from "../footer-items/attachment-status";+vi.mock("@/components/ui/use-toast", () => ({ toast: vi.fn() }));+vi.mock("@/core/network/api", () => ({ API: { post: vi.fn() } }));+const AGENT: Attachment = {id: "a1",kind: "agent",name: "Pi",- notebook_id: "nb-test",- identity: "pi-thread",since: new Date().toISOString(),+ notebook_id: "nb-one",};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(pairConfigAtom, { ...PAIR_CONFIG, hostEnabled: preview });store.set(attachmentsAtom, attachments);+ store.set(stableSessionIdAtom, "stable/test" as StableSessionId);return {store,...render(@@ -40,7 +56,22 @@ function renderStatus(attachments: Attachment[] = [AGENT], preview = true) {}describe("AttachmentStatus", () => {- it("renders nothing outside the preview", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(API.post).mockResolvedValue("");+ vi.mocked(toast).mockReturnValue({+ id: "notice",+ dismiss: vi.fn(),+ update: vi.fn(),+ upsert: vi.fn(),+ });+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it("renders nothing when host is disabled", () => {expect(renderStatus([AGENT], false).container).toBeEmptyDOMElement();});@@ -53,88 +84,262 @@ describe("AttachmentStatus", () => {it("lists each agent by its self-described name", () => {renderStatus([AGENT,- { ...AGENT, id: "a2", identity: "claude-thread", name: "Claude Code" },+ { ...AGENT, id: "a2", 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.getAllByTestId("footer-attachment-status")).toHaveLength(1);+ expect(screen.getByLabelText("2 agents connected")).toBeInTheDocument();+ expect(screen.getByRole("heading", { name: "Pi" })).toBeInTheDocument();+ expect(+ screen.getByRole("heading", { name: "Claude Code" }),+ ).toBeInTheDocument();+ expect(screen.getByText("a1")).toBeInTheDocument();+ expect(screen.getByText("a2")).toBeInTheDocument();expect(screen.queryByText("Browser")).not.toBeInTheDocument();- fireEvent.click(screen.getByLabelText("Pi: Connected"));- expect(screen.getByText(/^Connected /)).toBeInTheDocument();+ expect(screen.getAllByText(/^Connected /)).toHaveLength(2);});it("uses Agent when no name was supplied", () => {renderStatus([{ ...AGENT, name: null }]);- expect(screen.getByLabelText("Agent: Connected")).toBeInTheDocument();+ 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.each(["{Enter}", " "])("opens from the keyboard with %j", async (key) => {+ vi.useFakeTimers();+ renderStatus();+ act(() => vi.advanceTimersByTime(3000));+ vi.useRealTimers();+ const user = userEvent.setup();+ 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("preserves an open popover when the same identity reconnects", () => {+ it("opens for three seconds on connection without moving editor focus", () => {+ vi.useFakeTimers();+ const { store } = renderStatus([]);+ const editor = document.createElement("textarea");+ document.body.append(editor);+ editor.focus();+ act(() => store.set(attachmentsAtom, [AGENT]));+ const trigger = screen.getByRole("button", { name: "Pi connected" });+ expect(trigger).toHaveAttribute("aria-expanded", "true");+ expect(editor).toHaveFocus();+ act(() => vi.advanceTimersByTime(3000));+ expect(trigger).toHaveAttribute("aria-expanded", "false");+ expect(editor).toHaveFocus();+ editor.remove();+ });++ it("reopens on a new agent but not a metadata update or disconnection", () => {+ vi.useFakeTimers();const { store } = renderStatus();- fireEvent.click(screen.getByLabelText("Pi: Connected"));+ act(() => vi.advanceTimersByTime(3000));+ act(() => store.set(attachmentsAtom, [{ ...AGENT, name: "New name" }]));+ expect(screen.getByLabelText("New name connected")).toHaveAttribute(+ "aria-expanded",+ "false",+ );+ act(() => store.set(attachmentsAtom, [AGENT, { ...AGENT, id: "a2" }]));+ expect(screen.getByLabelText("2 agents connected")).toHaveAttribute(+ "aria-expanded",+ "true",+ );+ act(() => vi.advanceTimersByTime(3000));+ act(() => store.set(attachmentsAtom, [AGENT]));+ expect(screen.getByLabelText("Pi connected")).toHaveAttribute(+ "aria-expanded",+ "false",+ );+ });++ it("keeps manually opened details open past the automatic timeout", () => {+ vi.useFakeTimers();+ renderStatus();+ const trigger = screen.getByLabelText("Pi connected");+ fireEvent.click(trigger);+ fireEvent.click(trigger);+ act(() => vi.advanceTimersByTime(5000));+ expect(trigger).toHaveAttribute("aria-expanded", "true");+ });++ it("keeps manual confirmation open when another agent connects", () => {+ vi.useFakeTimers();+ const { store } = renderStatus();+ const trigger = screen.getByLabelText("Pi connected");+ fireEvent.click(trigger);+ fireEvent.click(trigger);+ fireEvent.click(screen.getByRole("button", { name: "Disconnect Pi" }));act(() =>store.set(attachmentsAtom, [- { ...AGENT, id: "a2", since: "2026-10-14T00:00:00Z" },+ AGENT,+ { ...AGENT, id: "a2", name: "Claude" },]),);+ act(() => vi.advanceTimersByTime(5000));expect(- screen.getByRole("button", { name: "Pi: Connected" }),- ).toHaveAttribute("aria-expanded", "true");- expect(screen.queryByText("a1")).not.toBeInTheDocument();- expect(screen.getByText("a2")).toBeInTheDocument();+ screen.getByRole("button", { name: "Confirm disconnect Pi" }),+ ).toBeInTheDocument();+ expect(API.post).not.toHaveBeenCalled();});- it("does not open a closed popover when the same identity reconnects", () => {+ it("keeps focused details open when another agent connects", () => {+ vi.useFakeTimers();const { store } = renderStatus();- act(() => store.set(attachmentsAtom, [{ ...AGENT, id: "a2" }]));- expect(- screen.getByRole("button", { name: "Pi: Connected" }),- ).toHaveAttribute("aria-expanded", "false");+ act(() => screen.getByRole("button", { name: "Disconnect Pi" }).focus());+ act(() => store.set(attachmentsAtom, [AGENT, { ...AGENT, id: "a2" }]));+ act(() => vi.advanceTimersByTime(5000));+ expect(screen.getByRole("dialog")).toBeInTheDocument();+ });++ it("keeps hovered details open when another agent connects", () => {+ vi.useFakeTimers();+ const { store } = renderStatus();+ fireEvent.pointerEnter(screen.getByRole("dialog"));+ act(() => store.set(attachmentsAtom, [AGENT, { ...AGENT, id: "a2" }]));+ act(() => vi.advanceTimersByTime(5000));+ expect(screen.getByRole("dialog")).toBeInTheDocument();});- it("keeps anonymous attachments separate from matching client identities", () => {+ it("pauses the automatic close while the pointer is over the details", () => {+ vi.useFakeTimers();+ renderStatus();+ const details = screen.getByRole("dialog");+ fireEvent.pointerEnter(details);+ act(() => vi.advanceTimersByTime(5000));+ expect(screen.getByLabelText("Pi connected")).toHaveAttribute(+ "aria-expanded",+ "true",+ );+ fireEvent.pointerLeave(details);+ act(() => vi.advanceTimersByTime(3000));+ expect(screen.getByLabelText("Pi connected")).toHaveAttribute(+ "aria-expanded",+ "false",+ );+ });++ it("groups identities while keeping separate attachment rows", () => {renderStatus([- { ...AGENT, identity: undefined },- { ...AGENT, id: "a2", identity: undefined },- { ...AGENT, id: "a3", identity: "a1" },+ { ...AGENT, identity: "same" },+ { ...AGENT, id: "a2", identity: "same" },]);- expect(screen.getAllByTestId("footer-attachment-status")).toHaveLength(3);+ expect(screen.getByLabelText("Pi connected")).toBeInTheDocument();+ expect(+ screen.getAllByRole("button", { name: "Disconnect Pi" }),+ ).toHaveLength(2);+ for (const text of screen.getAllByText(/^Connected /)) {+ expect(text).not.toHaveTextContent("Invalid Date");+ }});- it("accepts client identities that match object property names", () => {- renderStatus([- { ...AGENT, identity: "__proto__" },- { ...AGENT, id: "a2", identity: "constructor" },+ it("keeps the popover closed across a same-identity reconnect gap", () => {+ vi.useFakeTimers();+ const { store } = renderStatus([{ ...AGENT, identity: "same" }]);+ act(() => vi.advanceTimersByTime(3000));+ act(() => store.set(attachmentsAtom, []));+ act(() =>+ store.set(attachmentsAtom, [{ ...AGENT, id: "a2", identity: "same" }]),+ );+ expect(screen.getByLabelText("Pi connected")).toHaveAttribute(+ "aria-expanded",+ "false",+ );+ });++ it("disconnects only the selected attachment and waits for the server update", async () => {+ const { store } = renderStatus([+ AGENT,+ { ...AGENT, id: "a2", name: "Codex" },]);- expect(screen.getAllByTestId("footer-attachment-status")).toHaveLength(2);+ fireEvent.click(screen.getByRole("button", { name: "Disconnect Pi" }));+ expect(API.post).not.toHaveBeenCalled();+ fireEvent.click(+ screen.getByRole("button", { name: "Confirm disconnect Pi" }),+ );+ await waitFor(() =>+ expect(API.post).toHaveBeenCalledWith(+ "/pair/notebooks/stable%2Ftest/attachments/detach",+ { attachment_id: "a1" },+ ),+ );+ expect(screen.getByLabelText("2 agents connected")).toBeInTheDocument();+ act(() =>+ store.set(attachmentsAtom, [{ ...AGENT, id: "a2", name: "Codex" }]),+ );+ expect(screen.getByLabelText("Codex connected")).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Disconnect Pi" }),+ ).not.toBeInTheDocument();});- it.each(["{Enter}", " "])("opens from the keyboard with %j", async (key) => {- const user = userEvent.setup();+ it("disables duplicate disconnects while pending", async () => {+ const deferred = new Deferred<string>();+ vi.mocked(API.post).mockReturnValue(deferred.promise);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();+ const button = screen.getByRole("button", { name: "Disconnect Pi" });+ fireEvent.click(button);+ fireEvent.click(+ screen.getByRole("button", { name: "Confirm disconnect Pi" }),+ );+ expect(button).toBeDisabled();+ expect(+ screen.getByRole("button", { name: "Cancel disconnect Pi" }),+ ).toBeDisabled();+ fireEvent.click(button);+ expect(API.post).toHaveBeenCalledOnce();+ await act(async () => deferred.resolve(""));+ });++ it("shows disconnect failures and retains the attachment", async () => {+ vi.mocked(API.post).mockRejectedValue(new Error("offline"));+ renderStatus();+ fireEvent.click(screen.getByRole("button", { name: "Disconnect Pi" }));+ fireEvent.click(+ screen.getByRole("button", { name: "Confirm disconnect Pi" }),+ );+ await waitFor(() =>+ expect(toast).toHaveBeenCalledWith({+ variant: "danger",+ title: "Could not disconnect Pi",+ duration: 5000,+ }),+ );+ expect(screen.getByLabelText("Pi connected")).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Disconnect Pi" })).toBeEnabled();+ });++ it("cancels confirmation without disconnecting and restores focus", () => {+ renderStatus();+ fireEvent.click(screen.getByRole("button", { name: "Disconnect Pi" }));+ expect(screen.getByText("Disconnect?")).toBeVisible();+ expect(+ screen.getByRole("button", { name: "Confirm disconnect Pi" }),+ ).toBeEnabled();+ fireEvent.click(+ screen.getByRole("button", { name: "Cancel disconnect Pi" }),+ );+ expect(API.post).not.toHaveBeenCalled();+ expect(screen.getByRole("button", { name: "Disconnect Pi" })).toHaveFocus();+ expect(+ screen.queryByRole("button", { name: "Confirm disconnect Pi" }),+ ).not.toBeInTheDocument();+ });++ it("disables disconnect without a stable session ID", () => {+ const { store } = renderStatus();+ act(() => store.set(stableSessionIdAtom, null));+ expect(+ screen.getByRole("button", { name: "Disconnect Pi" }),+ ).toBeDisabled();});it.each([@@ -155,11 +360,11 @@ describe("AttachmentStatus", () => {it("removes detached agents when the list is replaced", () => {const { store, container } = renderStatus([AGENT,- { ...AGENT, id: "a2", identity: "claude-thread", name: "Claude Code" },+ { ...AGENT, id: "a2", name: "Claude Code" },]);act(() => store.set(attachmentsAtom, [AGENT]));expect(- screen.queryByLabelText("Claude Code: Connected"),+ screen.queryByRole("heading", { name: "Claude Code" }),).not.toBeInTheDocument();act(() => store.set(attachmentsAtom, []));expect(container).toBeEmptyDOMElement();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.tsxindex 115a041bb8..e44a17232d 100644--- a/frontend/src/components/editor/chrome/wrapper/footer-items/attachment-status.tsx+++ b/frontend/src/components/editor/chrome/wrapper/footer-items/attachment-status.tsx@@ -1,8 +1,15 @@/* Copyright 2026 Marimo. All rights reserved. */import { useAtomValue } from "jotai";-import { BotIcon } from "lucide-react";-import { useState } from "react";+import {+ BotIcon,+ CheckIcon,+ Loader2Icon,+ UnplugIcon,+ XIcon,+} from "lucide-react";+import { useCallback, useEffect, useRef, useState } from "react";+import { Button } from "@/components/ui/button";import {Popover,PopoverContent,@@ -13,43 +20,86 @@ import {agentAttachmentsAtom,attachmentLabel,} from "@/core/attachments/state";-import { pairPreviewAtom } from "@/core/config/pair";+import { agentToast } from "@/core/attachments/toast";+import { pairConfigAtom } from "@/core/config/pair";+import { stableSessionIdAtom } from "@/core/kernel/session";+import { API } from "@/core/network/api";import { useTimeAgo } from "@/hooks/useFormatting";-import { Objects } from "@/utils/objects";import { FooterItem } from "../footer-item";export function AttachmentStatus() {- const pairPreview = useAtomValue(pairPreviewAtom);+ const hostEnabled = useAtomValue(pairConfigAtom)?.hostEnabled;const agents = useAtomValue(agentAttachmentsAtom);- if (!pairPreview) {+ const [open, setOpen] = useState(false);+ const previous = useRef(new Set<string>());+ const automatic = useRef(false);+ const pointerInside = useRef(false);+ const timeout = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);++ const stopTimer = useCallback(() => clearTimeout(timeout.current), []);+ const startTimer = useCallback(() => {+ stopTimer();+ timeout.current = setTimeout(() => setOpen(false), 3000);+ }, [stopTimer]);+ const preserveEditorFocus = (event: Event) => {+ if (automatic.current) {+ event.preventDefault();+ }+ };++ useEffect(() => {+ if (!open) {+ pointerInside.current = false;+ }+ const current = new Set(+ hostEnabled ? agents.map((agent) => agent.identity ?? agent.id) : [],+ );+ const connected = [...current].some((id) => !previous.current.has(id));+ for (const id of current) {+ previous.current.add(id);+ }+ if (current.size === 0) {+ stopTimer();+ setOpen(false);+ } else if (connected) {+ if (open && !automatic.current) {+ return;+ }+ automatic.current = true;+ setOpen(true);+ if (!pointerInside.current) {+ startTimer();+ }+ }+ }, [agents, hostEnabled, open, startTimer, stopTimer]);++ useEffect(() => stopTimer, [stopTimer]);++ if (!hostEnabled || agents.length === 0) {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} />- ));-}+ const identities = new Set(agents.map((agent) => agent.identity ?? agent.id));+ const label =+ identities.size === 1+ ? `${attachmentLabel(agents[0])} connected`+ : `${identities.size} agents connected`;-function AttachmentStatusItem({ attachments }: { attachments: Attachment[] }) {- const [open, setOpen] = useState(false);- const timeAgo = useTimeAgo();- const label = attachmentLabel(attachments[0]);return (- <Popover open={open} onOpenChange={setOpen}>+ <Popover+ open={open}+ onOpenChange={(nextOpen) => {+ automatic.current = false;+ stopTimer();+ setOpen(nextOpen);+ }}+ ><PopoverTrigger asChild={true}><FooterItemasChild={true}- tooltip={`${label}: connected`}+ tooltip={label}selected={open}data-testid="footer-attachment-status"- aria-label={`${label}: Connected`}+ aria-label={label}><button type="button"><span className="flex items-center gap-1.5">@@ -59,24 +109,129 @@ function AttachmentStatusItem({ attachments }: { attachments: Attachment[] }) {</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>+ <PopoverContent+ className="w-80 p-0 text-sm"+ side="top"+ align="start"+ onOpenAutoFocus={preserveEditorFocus}+ onCloseAutoFocus={preserveEditorFocus}+ onPointerEnter={() => {+ pointerInside.current = true;+ stopTimer();+ }}+ onPointerLeave={() => {+ pointerInside.current = false;+ if (automatic.current) {+ startTimer();+ }+ }}+ onFocusCapture={() => {+ automatic.current = false;+ stopTimer();+ }}+ >+ <h4 className="font-medium px-4 py-3 border-b">{label}</h4>+ <div className="max-h-72 overflow-auto divide-y">+ {agents.map((attachment) => (+ <AttachmentStatusItem key={attachment.id} attachment={attachment} />))}- </ul>+ </div>+ <p className="px-4 py-3 border-t text-xs text-muted-foreground">+ Disconnect removes the notebook connection. The agent session keeps+ running.+ </p></PopoverContent></Popover>);}++function AttachmentStatusItem({ attachment }: { attachment: Attachment }) {+ const stableSessionId = useAtomValue(stableSessionIdAtom);+ const [state, setState] = useState<"idle" | "confirming" | "disconnecting">(+ "idle",+ );+ const confirming = state !== "idle";+ const disconnecting = state === "disconnecting";+ const disconnectButton = useRef<HTMLButtonElement>(null);+ const timeAgo = useTimeAgo();+ const label = attachmentLabel(attachment);+ const disconnectLabel = disconnecting+ ? `Disconnecting ${label}`+ : confirming+ ? `Confirm disconnect ${label}`+ : `Disconnect ${label}`;++ const disconnect = async () => {+ if (disconnecting || !stableSessionId) {+ return;+ }+ setState("disconnecting");+ try {+ await API.post(+ `/pair/notebooks/${encodeURIComponent(stableSessionId)}/attachments/detach`,+ { attachment_id: attachment.id },+ );+ } catch {+ agentToast({ variant: "danger", title: `Could not disconnect ${label}` });+ } finally {+ setState("idle");+ }+ };++ return (+ <div className="flex items-start gap-3 px-4 py-3">+ <div className="min-w-0 flex-1">+ <h5 className="font-medium">{label}</h5>+ <p className="text-xs text-muted-foreground mt-1">+ Connected {timeAgo(attachment.since)}+ </p>+ <p+ className="text-xs font-mono text-muted-foreground truncate mt-1"+ title={attachment.id}+ >+ {attachment.id}+ </p>+ </div>+ <div className="flex shrink-0 items-center gap-1">+ {confirming && (+ <span className="text-xs text-muted-foreground">+ {disconnecting ? "Disconnecting…" : "Disconnect?"}+ </span>+ )}+ <Button+ ref={disconnectButton}+ size="icon"+ variant="outlineDestructive"+ disabled={disconnecting || !stableSessionId}+ onClick={confirming ? disconnect : () => setState("confirming")}+ aria-label={disconnectLabel}+ title={disconnectLabel}+ aria-busy={disconnecting}+ >+ {disconnecting ? (+ <Loader2Icon className="size-3.5 animate-spin" aria-hidden={true} />+ ) : confirming ? (+ <CheckIcon className="size-3.5" aria-hidden={true} />+ ) : (+ <UnplugIcon className="size-3.5" aria-hidden={true} />+ )}+ </Button>+ {confirming && (+ <Button+ size="icon"+ variant="outline"+ disabled={disconnecting}+ onClick={() => {+ setState("idle");+ disconnectButton.current?.focus();+ }}+ aria-label={`Cancel disconnect ${label}`}+ title={`Cancel disconnect ${label}`}+ >+ <XIcon className="size-3.5" aria-hidden={true} />+ </Button>+ )}+ </div>+ </div>+ );+}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.tsxindex a406ad2514..8f7bd0d0f1 100644--- a/frontend/src/components/editor/errors/__tests__/send-error-report-button.test.tsx+++ b/frontend/src/components/editor/errors/__tests__/send-error-report-button.test.tsx@@ -13,16 +13,18 @@ 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 { PAIR_CONFIG } from "@/__tests__/fixtures/pair-config";import { TooltipProvider } from "@/components/ui/tooltip";import { toast } from "@/components/ui/use-toast";import { type Attachment, attachmentsAtom } from "@/core/attachments/state";import { exportedForTesting, notebookAtom } from "@/core/cells/cells";-import type {- CellOutputHandoff,- ErrorHandoffOutput,+import {+ type CellOutputMessage,+ type ErrorMessageOutput,+ ERROR_MESSAGE_INSTRUCTIONS,} from "@/core/cells/error-report";-import { pairPreviewAtom } from "@/core/config/pair";+import { pairConfigAtom } from "@/core/config/pair";+import { notebookStateFromSession } from "@/core/cells/session";import type { MarimoError, OutputMessage } from "@/core/kernel/messages";import {type StableSessionId,@@ -57,11 +59,15 @@ const AGENT: Attachment = {const ROUTE = "/pair/notebooks/stable%2Ftest/messages";const MESSAGE = "df is not defined";const CODE = "df.head()";-const REPORT: CellOutputHandoff<ErrorHandoffOutput> = {+const REPORT: CellOutputMessage<ErrorMessageOutput> = {type: "cell-output",cell_id: CELL_ID,code: CODE,- output: { type: "error", message: MESSAGE },+ output: {+ type: "error",+ instructions: ERROR_MESSAGE_INSTRUCTIONS,+ message: MESSAGE,+ },};const ERRORS: MarimoError[] = [{@@ -86,7 +92,7 @@ function renderButton({} = {}) {const store = createStore();store.set(connectionAtom, { state: ConnectionState.OPEN });- store.set(pairPreviewAtom, preview ? PAIR_PREVIEW : undefined);+ store.set(pairConfigAtom, { ...PAIR_CONFIG, hostEnabled: preview });store.set(attachmentsAtom, attachments);store.set(stableSessionIdAtom, stableId);const wrapper = ({ children }: { children: React.ReactNode }) => (@@ -105,9 +111,15 @@ describe("SendErrorReportButton", () => {beforeEach(() => {vi.clearAllMocks();vi.mocked(API.post).mockResolvedValue("");+ vi.mocked(toast).mockReturnValue({+ id: "notice",+ dismiss: vi.fn(),+ update: vi.fn(),+ upsert: vi.fn(),+ });});- it("hides outside the preview without building content", () => {+ it("hides when host is disabled without building content", () => {const getContent = vi.fn(() => REPORT);expect(renderButton({@@ -138,7 +150,10 @@ describe("SendErrorReportButton", () => {expect(getContent).not.toHaveBeenCalled();send();await waitFor(() =>- expect(toast).toHaveBeenCalledWith({ title: "Sent to Pi, Claude Code" }),+ expect(toast).toHaveBeenCalledWith({+ title: "Sent to Pi, Claude Code",+ duration: 3000,+ }),);expect(API.post).toHaveBeenCalledWith(ROUTE, REPORT);expect(getContent).toHaveBeenCalledOnce();@@ -190,12 +205,20 @@ describe("SendErrorReportButton", () => {renderButton();send();await waitFor(() =>- expect(toast).toHaveBeenCalledWith({ variant: "danger", title }),+ expect(toast).toHaveBeenCalledWith({+ variant: "danger",+ title,+ description: error.message,+ duration: 5000,+ }),);expect(screen.getByRole("button")).toBeEnabled();send();await waitFor(() =>- expect(toast).toHaveBeenCalledWith({ title: "Sent to Pi" }),+ expect(toast).toHaveBeenCalledWith({+ title: "Sent to Pi",+ duration: 3000,+ }),);expect(API.post).toHaveBeenCalledTimes(2);expect(API.post).toHaveBeenLastCalledWith(ROUTE, REPORT);@@ -222,6 +245,7 @@ describe("SendErrorReportButton", () => {...REPORT,output: {type: "error",+ instructions: ERROR_MESSAGE_INSTRUCTIONS,message: MESSAGE,traceback: "Traceback\nNameError: df is not defined",},@@ -264,6 +288,7 @@ describe("SendErrorReportButton", () => {...REPORT,output: {type: "error",+ instructions: ERROR_MESSAGE_INSTRUCTIONS,message: "ValueError: bad <value>",traceback: "Traceback\nValueError: bad <value>",},@@ -271,6 +296,90 @@ describe("SendErrorReportButton", () => {);});+ it("sends plain code-mode traceback text without parsing it as HTML", async () => {+ const traceback =+ ' File "<cell>", line 1\nValueError: bad <value> & <other>';+ renderButton({+ content: (+ <OutputRenderer+ cellId={CELL_ID}+ message={{+ channel: "stderr",+ mimetype: "application/vnd.marimo+traceback",+ traceback_format: "text",+ code: CODE,+ data: traceback,+ }}+ />+ ),+ });+ expect(screen.getByText(/ValueError: bad <value>/)).toHaveTextContent(+ "<cell>",+ );+ send();+ await waitFor(() =>+ expect(API.post).toHaveBeenCalledWith(ROUTE, {+ ...REPORT,+ output: {+ type: "error",+ instructions: ERROR_MESSAGE_INSTRUCTIONS,+ message: "ValueError: bad <value> & <other>",+ traceback,+ },+ }),+ );+ });++ it("sends the restored exception type and complete traceback", async () => {+ const state = notebookStateFromSession(+ {+ version: "1",+ metadata: { marimo_version: "1", script_metadata_hash: null },+ cells: [+ {+ id: CELL_ID,+ code_hash: null,+ console: [],+ outputs: [+ {+ type: "error",+ ename: "ValueError",+ evalue: "cached failure",+ traceback: [+ "<pre>Traceback",+ " failed()\n",+ "ValueError: cached failure</pre>",+ ],+ code: CODE,+ },+ ],+ },+ ],+ },+ null,+ );+ const message = state?.cellRuntime[CELL_ID].output;+ expect(message).toBeDefined();+ renderButton({+ content: message && <OutputRenderer cellId={CELL_ID} message={message} />,+ });+ send();+ await waitFor(() =>+ expect(API.post).toHaveBeenCalledWith(ROUTE, {+ ...REPORT,+ output: {+ type: "error",+ instructions: ERROR_MESSAGE_INSTRUCTIONS,+ message: "cached failure",+ traceback: "Traceback\n failed()\nValueError: cached failure",+ },+ }),+ );+ expect(message?.data).toEqual([+ expect.objectContaining({ exception_type: "ValueError" }),+ ]);+ });+it("sends updated content after the error changes", async () => {const { rerender } = renderButton();const updated = {@@ -385,7 +494,11 @@ describe("SendErrorReportButton", () => {type: "cell-output",cell_id: CELL_ID,code: "x + 1",- output: { type: "error", message: "Ancestor failed" },+ output: {+ type: "error",+ instructions: ERROR_MESSAGE_INSTRUCTIONS,+ message: "Ancestor failed",+ },}),);});@@ -408,6 +521,7 @@ describe("SendErrorReportButton", () => {code: "slow()",output: {type: "error",+ instructions: ERROR_MESSAGE_INSTRUCTIONS,message: "This cell was interrupted and needs to be re-run",},}),diff --git a/frontend/src/components/editor/errors/send-error-report-button.tsx b/frontend/src/components/editor/errors/send-error-report-button.tsxindex 9902bc0c2f..b8ad1afd19 100644--- a/frontend/src/components/editor/errors/send-error-report-button.tsx+++ b/frontend/src/components/editor/errors/send-error-report-button.tsx@@ -4,27 +4,27 @@ 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 { agentToast } from "@/core/attachments/toast";+import { pairConfigAtom } from "@/core/config/pair";import { stableSessionIdAtom } from "@/core/kernel/session";import { API } from "@/core/network/api";-import { HTTPError } from "@/utils/errors";+import { HTTPError, prettyError } from "@/utils/errors";export function SendErrorReportButton({getContent,}: {getContent: () => unknown;}) {- const pairPreview = useAtomValue(pairPreviewAtom);+ const hostEnabled = useAtomValue(pairConfigAtom)?.hostEnabled;const agents = useAtomValue(agentAttachmentsAtom);const stableSessionId = useAtomValue(stableSessionIdAtom);const [sending, setSending] = useState(false);- if (!pairPreview) {+ if (!hostEnabled) {return null;}@@ -38,14 +38,17 @@ export function SendErrorReportButton({`/pair/notebooks/${encodeURIComponent(stableSessionId)}/messages`,getContent(),);- toast({ title: `Sent to ${agents.map(attachmentLabel).join(", ")}` });+ agentToast({+ title: `Sent to ${agents.map(attachmentLabel).join(", ")}`,+ });} catch (error) {- toast({+ agentToast({variant: "danger",title:error instanceof HTTPError && error.status === 409? "No agent attached": "Could not send error",+ description: prettyError(error),});} finally {setSending(false);diff --git a/frontend/src/components/editor/output/MarimoTracebackOutput.tsx b/frontend/src/components/editor/output/MarimoTracebackOutput.tsxindex 1b6a7cc688..8df7e60bee 100644--- a/frontend/src/components/editor/output/MarimoTracebackOutput.tsx+++ b/frontend/src/components/editor/output/MarimoTracebackOutput.tsx@@ -35,6 +35,7 @@ import { isWasm } from "@/core/wasm/utils";import { renderHTML } from "@/plugins/core/RenderHTML";import { sanitizeHtml } from "@/plugins/core/sanitize-html";import { copyToClipboard } from "@/utils/copy";+import { parseHtmlContent } from "@/utils/dom";import {containsMangledLocal,splitMangledLocals,@@ -54,29 +55,38 @@ import type { OnRefactorWithAI } from "../Output";interface Props {cellId: CellId | undefined;traceback: string;+ tracebackFormat?: "html" | "text";code?: string;onRefactorWithAI?: OnRefactorWithAI;}-/**- * List of errors due to violations of Marimo semantics.- */+/** Render a traceback and actions for its captured execution. */export const MarimoTracebackOutput = ({onRefactorWithAI,traceback,+ tracebackFormat = "html",cellId,code,}: Props): JSX.Element => {- const htmlTraceback = renderHTML({- html: traceback,- additionalReplacements: [- replaceTracebackFilenames,- replaceTracebackPrefix,- replaceMangledLocal,- ],- });+ const htmlTraceback =+ tracebackFormat === "text" ? (+ <pre>{traceback}</pre>+ ) : (+ renderHTML({+ html: traceback,+ additionalReplacements: [+ replaceTracebackFilenames,+ replaceTracebackPrefix,+ replaceMangledLocal,+ ],+ })+ );- const lastTracebackLine = lastLine(traceback);+ const textTraceback =+ tracebackFormat === "html"+ ? parseHtmlContent(sanitizeHtml(traceback))+ : traceback;+ const lastTracebackLine = lastLine(textTraceback);const aiFeaturesEnabled = useAtomValue(aiFeaturesEnabledAtom);const openAiAssistant = useOpenAiAssistant();@@ -137,7 +147,9 @@ export const MarimoTracebackOutput = ({<div className="flex gap-2">{cellId && lastTracebackLine && (<SendErrorReportButton- getContent={() => buildErrorReport(cellId, { code, traceback })}+ getContent={() =>+ buildErrorReport(cellId, { code, traceback, tracebackFormat })+ }/>)}{showAIFix && (@@ -195,11 +207,7 @@ export const MarimoTracebackOutput = ({</DropdownMenuItem><DropdownMenuItemonClick={() => {- // Strip HTML from the traceback (sanitize first to prevent XSS)- const div = document.createElement("div");- div.innerHTML = sanitizeHtml(traceback);- const textContent = div.textContent || "";- copyToClipboard(textContent);+ copyToClipboard(textTraceback);}}><CopyIcon className="h-4 w-4 mr-2" />@@ -214,9 +222,7 @@ export const MarimoTracebackOutput = ({};function lastLine(text: string): string {- const el = document.createElement("div");- el.innerHTML = sanitizeHtml(text);- const lines = el.textContent?.split("\n").filter(Boolean);+ const lines = text.split("\n").filter(Boolean);return lines?.at(-1) || "";}diff --git a/frontend/src/core/attachments/__tests__/toast.test.tsx b/frontend/src/core/attachments/__tests__/toast.test.tsxnew file mode 100644index 0000000000..3df9cd5f13--- /dev/null+++ b/frontend/src/core/attachments/__tests__/toast.test.tsx@@ -0,0 +1,58 @@+/* Copyright 2026 Marimo. All rights reserved. */+// @vitest-environment jsdom++import { act, render, renderHook } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { Toaster } from "@/components/ui/toaster";+import { clearToasts, toast, useToast } from "@/components/ui/use-toast";+import { agentToast } from "../toast";++describe("agent notifications", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ clearToasts();+ });++ afterEach(() => {+ act(() => {+ clearToasts();+ vi.runOnlyPendingTimers();+ });+ vi.useRealTimers();+ });++ it.each([+ { variant: undefined, duration: 3000 },+ { variant: "danger" as const, duration: 5000 },+ ])("expires while the window is blurred: %j", ({ variant, duration }) => {+ const { result } = renderHook(useToast);+ render(<Toaster />);+ act(() => agentToast({ title: "Agent notice", variant }));+ act(() => window.dispatchEvent(new Event("blur")));+ act(() => vi.advanceTimersByTime(duration - 1));+ expect(result.current.toasts[0].open).toBe(true);+ act(() => vi.advanceTimersByTime(1));+ expect(result.current.toasts[0].open).toBe(false);+ });++ it("preserves pause behavior for ordinary notifications", () => {+ const { result } = renderHook(useToast);+ render(<Toaster />);+ act(() => toast({ title: "Ordinary notice", duration: 3000 }));+ act(() => window.dispatchEvent(new Event("blur")));+ act(() => vi.advanceTimersByTime(5000));+ expect(result.current.toasts[0].open).toBe(true);+ });++ it("does not let an older timer dismiss a newer notification", () => {+ const { result } = renderHook(useToast);+ act(() => agentToast({ title: "First" }));+ act(() => vi.advanceTimersByTime(1000));+ act(() => agentToast({ title: "Second" }));+ act(() => vi.advanceTimersByTime(2000));+ expect(result.current.toasts[0].title).toBe("Second");+ expect(result.current.toasts[0].open).toBe(true);+ act(() => vi.advanceTimersByTime(1000));+ expect(result.current.toasts[0].open).toBe(false);+ });+});diff --git a/frontend/src/core/attachments/toast.ts b/frontend/src/core/attachments/toast.tsnew file mode 100644index 0000000000..2fa68e9e24--- /dev/null+++ b/frontend/src/core/attachments/toast.ts@@ -0,0 +1,15 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { toast } from "@/components/ui/use-toast";++export function agentToast(+ options: Pick<+ Parameters<typeof toast>[0],+ "title" | "variant" | "description"+ >,+) {+ const duration = options.variant === "danger" ? 5000 : 3000;+ const { dismiss } = toast({ ...options, duration });+ // Agent notices must also expire while the user focuses the agent terminal.+ window.setTimeout(dismiss, duration);+}diff --git a/frontend/src/core/cells/__tests__/error-report.test.ts b/frontend/src/core/cells/__tests__/error-report.test.tsindex c4c1092c4f..1e0f20f881 100644--- a/frontend/src/core/cells/__tests__/error-report.test.ts+++ b/frontend/src/core/cells/__tests__/error-report.test.ts@@ -4,11 +4,51 @@import { describe, expect, it } from "vitest";import { cellId } from "@/__tests__/branded";import type { MarimoError } from "@/core/kernel/messages";-import { buildErrorReport } from "../error-report";+import { buildErrorReport, ERROR_MESSAGE_INSTRUCTIONS } from "../error-report";const CELL_ID = cellId("failed-cell");describe("buildErrorReport", () => {+ it("preserves plain traceback text without treating angle brackets as HTML", () => {+ const traceback =+ ' File "<cell>", line 1\nValueError: expected <value> & got <other>';+ expect(+ buildErrorReport(CELL_ID, { traceback, tracebackFormat: "text" }).output,+ ).toEqual({+ type: "error",+ instructions: ERROR_MESSAGE_INSTRUCTIONS,+ message: "ValueError: expected <value> & got <other>",+ traceback,+ });+ });+ it("owns the instruction to repair the live notebook", () => {+ const report = buildErrorReport(CELL_ID, {+ errors: [{ type: "syntax", msg: "invalid code" }],+ });+ expect(report.output.instructions).toEqual("Fix this notebook error.");+ });++ it("keeps repair intent visible before oversized evidence", () => {+ const report = buildErrorReport(CELL_ID, {+ code: "# long code\n".repeat(10_000),+ errors: [+ {+ type: "exception",+ exception_type: "ValueError",+ msg: "long error ".repeat(10_000),+ raising_cell: null,+ traceback: `<pre>Traceback\n${"long frame\n".repeat(10_000)}</pre>`,+ },+ ],+ });+ const serialized = JSON.stringify(report);++ expect(serialized.length).toBeGreaterThan(8192);+ expect(serialized.slice(0, 256)).toContain(+ '"instructions":"Fix this notebook error."',+ );+ });+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[] = [@@ -27,6 +67,7 @@ describe("buildErrorReport", () => {code: "failed()",output: {type: "error",+ instructions: ERROR_MESSAGE_INSTRUCTIONS,message: "bad <value>\nanother error",traceback,},@@ -49,7 +90,11 @@ describe("buildErrorReport", () => {).toEqual({type: "cell-output",cell_id: CELL_ID,- output: { type: "error", message: "legacy error" },+ output: {+ type: "error",+ instructions: ERROR_MESSAGE_INSTRUCTIONS,+ message: "legacy error",+ },});});@@ -63,7 +108,11 @@ describe("buildErrorReport", () => {type: "cell-output",cell_id: CELL_ID,code: "",- output: { type: "error", message: "invalid code" },+ output: {+ type: "error",+ instructions: ERROR_MESSAGE_INSTRUCTIONS,+ message: "invalid code",+ },});});@@ -80,6 +129,7 @@ describe("buildErrorReport", () => {cell_id: CELL_ID,output: {type: "error",+ instructions: ERROR_MESSAGE_INSTRUCTIONS,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.tsindex 8a2889e4a1..1e0ac4658b 100644--- a/frontend/src/core/cells/__tests__/session.test.ts+++ b/frontend/src/core/cells/__tests__/session.test.ts@@ -174,8 +174,11 @@ describe("notebookStateFromSession", () => {channel: "marimo-error",data: [{- type: "unknown",+ type: "exception",+ exception_type: "ValueError",msg: "Something went wrong",+ raising_cell: null,+ traceback: "Traceback line 1",},],mimetype: "application/vnd.marimo+error",@@ -201,8 +204,9 @@ describe("notebookStateFromSession", () => {{type: "stream",name: "stderr",- text: "<pre>ValueError: cached failure</pre>",+ text: "ValueError: cached <failure>",mimetype: "application/vnd.marimo+traceback",+ traceback_format: "text",code,},],@@ -212,9 +216,20 @@ describe("notebookStateFromSession", () => {invariant(state, "state is null");expect(state.cellRuntime[CELL_1].output).toMatchObject({code,- data: [{ type: "unknown", msg: "cached failure" }],+ data: [+ {+ type: "exception",+ exception_type: "ValueError",+ msg: "cached failure",+ traceback: "Traceback\nValueError: cached failure",+ },+ ],});expect(state.cellRuntime[CELL_1].consoleOutputs[0].code).toBe(code);+ expect(state.cellRuntime[CELL_1].consoleOutputs[0]).toMatchObject({+ traceback_format: "text",+ data: "ValueError: cached <failure>",+ });});it("handles data output in session cell", () => {diff --git a/frontend/src/core/cells/error-report.ts b/frontend/src/core/cells/error-report.tsindex 356edd276c..253b2a216b 100644--- a/frontend/src/core/cells/error-report.ts+++ b/frontend/src/core/cells/error-report.ts@@ -6,26 +6,29 @@ import { sanitizeHtml } from "@/plugins/core/sanitize-html";import { parseHtmlContent } from "@/utils/dom";import type { CellId } from "./ids";-export interface CellOutputHandoff<Output> {+export interface CellOutputMessage<Output> {type: "cell-output";cell_id: CellId;code?: string;output: Output;}-export interface ErrorHandoffOutput {+export interface ErrorMessageOutput {type: "error";+ instructions: string;message: string;traceback?: string;}+export const ERROR_MESSAGE_INSTRUCTIONS = "Fix this notebook error.";+export function buildErrorReport(cellId: CellId,evidence: { code?: string } & (| { errors: MarimoError[] }- | { traceback: string }+ | { traceback: string; tracebackFormat: "html" | "text" }),-): CellOutputHandoff<ErrorHandoffOutput> {+): CellOutputMessage<ErrorMessageOutput> {let message: string;let traceback: string;if ("errors" in evidence) {@@ -38,18 +41,23 @@ export function buildErrorReport().join("\n\n");} else {- traceback = parseHtmlContent(sanitizeHtml(evidence.traceback));+ traceback =+ evidence.tracebackFormat === "html"+ ? parseHtmlContent(sanitizeHtml(evidence.traceback))+ : evidence.traceback;message = traceback.split("\n").findLast((line) => line.length > 0) ?? "";}+ // Put repair intent before evidence so it survives prefix truncation.return {type: "cell-output",cell_id: cellId,- ...(evidence.code === undefined ? {} : { code: evidence.code }),output: {type: "error",+ instructions: ERROR_MESSAGE_INSTRUCTIONS,message,...(traceback ? { traceback } : {}),},+ ...(evidence.code === undefined ? {} : { code: evidence.code }),};}diff --git a/frontend/src/core/cells/session.ts b/frontend/src/core/cells/session.tsindex e5aab56199..4b84d4c46a 100644--- a/frontend/src/core/cells/session.ts+++ b/frontend/src/core/cells/session.ts@@ -206,8 +206,20 @@ function createCellRuntimeFromSession(channel: "marimo-error",data: [{- type: "unknown",+ type: "exception",+ exception_type: primaryOutput.ename,msg: primaryOutput.evalue,+ raising_cell: null,+ traceback:+ primaryOutput.traceback.length === 0+ ? null+ : primaryOutput.traceback+ .map((line, index, lines) =>+ index < lines.length - 1 && !line.endsWith("\n")+ ? `${line}\n`+ : line,+ )+ .join(""),},],mimetype: "application/vnd.marimo+error",@@ -240,6 +252,9 @@ function createCellRuntimeFromSession(channel: "media",data: consoleOutput.data,mimetype: consoleOutput.mimetype,+ ...(consoleOutput.traceback_format === undefined+ ? {}+ : { traceback_format: consoleOutput.traceback_format }),timestamp: DEFAULT_TIMESTAMP,...(consoleOutput.code === undefined? {}@@ -251,6 +266,9 @@ function createCellRuntimeFromSession(channel: consoleOutput.name === "stderr" ? "stderr" : "stdout",data: consoleOutput.text,mimetype: consoleOutput.mimetype ?? "text/plain",+ ...(consoleOutput.traceback_format === undefined+ ? {}+ : { traceback_format: consoleOutput.traceback_format }),timestamp: DEFAULT_TIMESTAMP,...(consoleOutput.code === undefined? {}diff --git a/frontend/src/core/config/pair.ts b/frontend/src/core/config/pair.tsindex bb5756b0c9..f19bbc60c4 100644--- a/frontend/src/core/config/pair.ts+++ b/frontend/src/core/config/pair.ts@@ -3,16 +3,18 @@import { atom } from "jotai";import { z } from "zod";-export const pairPreviewSchema = z.object({+export const pairConfigSchema = z.object({command: z.string(),+ hostEnabled: z.boolean().default(false),templates: z.object({prompt: z.string(),+ notebook: z.string(),session: z.string(),token_file: z.string(),token: z.string(),}),});-export type PairPreviewConfig = z.infer<typeof pairPreviewSchema>;+export type PairConfig = z.infer<typeof pairConfigSchema>;-export const pairPreviewAtom = atom<PairPreviewConfig | undefined>(undefined);+export const pairConfigAtom = atom<PairConfig | undefined>(undefined);diff --git a/frontend/src/mount.tsx b/frontend/src/mount.tsxindex a4bd3bcf59..213da3ea2a 100644--- a/frontend/src/mount.tsx+++ b/frontend/src/mount.tsx@@ -10,7 +10,7 @@ import {userConfigAtom,} from "@/core/config/config";import { KnownQueryParams } from "@/core/constants";-import { pairPreviewAtom, pairPreviewSchema } from "@/core/config/pair";+import { pairConfigAtom, pairConfigSchema } from "@/core/config/pair";import { getFilenameFromDOM } from "@/core/dom/htmlUtils";import { getMarimoCode } from "@/core/meta/globals";import {@@ -209,7 +209,7 @@ const mountOptionsSchema = z.object({* marimo config overrides*/configOverrides: passthroughObject,- pairPreview: pairPreviewSchema.optional(),+ pairConfig: pairConfigSchema.optional(),/*** marimo app config*/@@ -347,7 +347,7 @@ function initStore(options: unknown) {);store.set(userConfigAtom, parseUserConfig(parsedOptions.data.config));store.set(appConfigAtom, parseAppConfig(parsedOptions.data.appConfig));- store.set(pairPreviewAtom, parsedOptions.data.pairPreview);+ store.set(pairConfigAtom, parsedOptions.data.pairConfig);// Runtime configif (parsedOptions.data.runtimeConfig.length > 0) {diff --git a/marimo/_cli/pair/artifacts.py b/marimo/_cli/pair/artifacts.pynew file mode 100644index 0000000000..b45f10ea48--- /dev/null+++ b/marimo/_cli/pair/artifacts.py@@ -0,0 +1,111 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import json+import os+import stat+import tempfile+import time+import uuid+from pathlib import Path++from marimo._cli.pair.client import PairError++_PREFIX = "marimo-pair-messages-"+_MAX_AGE = 24 * 60 * 60+++class AgentMessageFiles:+ """Preserve oversized inbox payloads in private JSON files.++ Files outlive the connection so agents can read them after detach.+ """++ def __init__(self) -> None:+ self.directory: Path | None = None++ def write(self, payload: object) -> Path:+ try:+ if self.directory is None or not self.directory.exists():+ self.directory = Path(+ tempfile.mkdtemp(prefix=_PREFIX)+ ).resolve()+ info = self.directory.lstat()+ if not stat.S_ISDIR(info.st_mode) or (+ hasattr(os, "getuid") and info.st_uid != os.getuid()+ ):+ raise ValueError("The message directory is no longer owned.")+ path = self.directory / f"{uuid.uuid4().hex}.json"+ descriptor = os.open(+ path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600+ )+ try:+ with os.fdopen(+ descriptor, "w", encoding="utf-8", newline="\n"+ ) as stream:+ json.dump(payload, stream, ensure_ascii=True)+ except BaseException:+ path.unlink(missing_ok=True)+ raise+ return path+ except (OSError, ValueError) as error:+ raise PairError(+ "Could not save the complete agent message. No shortened message was sent."+ ) from error++ @staticmethod+ def cleanup(*, now: float | None = None) -> None:+ cutoff = (time.time() if now is None else now) - _MAX_AGE+ for directory in Path(tempfile.gettempdir()).glob(f"{_PREFIX}*"):+ try:+ if directory.is_symlink() or not directory.is_dir():+ continue+ if (+ hasattr(os, "getuid")+ and directory.stat().st_uid != os.getuid()+ ):+ continue+ directory_mtime = directory.stat().st_mtime+ for path in directory.iterdir():+ if (+ not path.is_symlink()+ and len(path.stem) == 32+ and all(+ char in "0123456789abcdef" for char in path.stem+ )+ and path.suffix == ".json"+ and path.is_file()+ and path.stat().st_mtime < cutoff+ ):+ path.unlink()+ if directory_mtime < cutoff:+ directory.rmdir()+ except OSError:+ continue+++def inbox_message(+ payload: object, *, notebook: str, budget: int, files: AgentMessageFiles+) -> str:+ prefix = f"Agent message from marimo (notebook {notebook}).\n"+ text = (+ payload+ if isinstance(payload, str)+ else json.dumps(payload, ensure_ascii=True)+ )+ # NUL cannot travel in a subprocess argument. Preserve its JSON spelling.+ text = text.replace("\0", "\\u0000")+ encoded = (prefix + text).encode("utf-8", errors="backslashreplace")+ if len(encoded) <= budget:+ return encoded.decode("utf-8")+ path = files.write(payload)+ suffix = f"\n[Truncated. Complete JSON agent message: {path}]"+ available = budget - len((prefix + suffix).encode("utf-8"))+ if available < 0:+ raise PairError(+ "The inbox budget cannot fit the complete agent message file reference."+ )+ preview = text.encode("utf-8", errors="backslashreplace")[+ :available+ ].decode("utf-8", errors="ignore")+ return prefix + preview + suffixdiff --git a/marimo/_cli/pair/client.py b/marimo/_cli/pair/client.pyindex 811779788d..350faff4e8 100644--- a/marimo/_cli/pair/client.py+++ b/marimo/_cli/pair/client.py@@ -3,17 +3,29 @@ from __future__ import annotationsimport http.clientimport json-from dataclasses import dataclass+import queue+import signal+import socket+import threading+from dataclasses import dataclass, fieldfrom typing import TYPE_CHECKING-from urllib.parse import urlsplit+from urllib.parse import quote, urlsplit+from uuid import uuid4from marimo._server.api.utils import format_url_host+from marimo._server.host import (+ ATTACHMENT_IDENTITY,+ ATTACHMENT_KIND,+ ATTACHMENT_NAME,+ HOST_API_PATH,+)from marimo._server.server_registry import _servers_dirif TYPE_CHECKING:from collections.abc import Iterable, Iterator, Mappingfrom http.client import HTTPResponsefrom pathlib import Path+ from types import FrameTypefrom typing import TextIO@@ -25,13 +37,29 @@ class PairInputError(PairError):"""Invalid local input that prevents a server operation."""-class NoSessionError(PairError):+class PairConnectionError(PairError):+ """A transport failure while connecting to the notebook server."""+++class NoRuntimeError(PairError):+ """The notebook has no running kernel."""+++class RunConflictError(PairError):+ """The notebook already has an active run."""+++class NoNotebookError(PairError):+ """No notebook was found at the requested server URL."""+def __init__(self, message: str, *, url: str) -> None:super().__init__(message)self.url = url-class AmbiguousSessionError(PairError):+class AmbiguousNotebookError(PairError):+ """Discovery found several notebooks and requires an explicit selection."""+def __init__(self, message: str, *, url: str, candidates: tuple[str, ...]) -> None:@@ -40,26 +68,32 @@ class AmbiguousSessionError(PairError):self.candidates = candidates-class StaleSessionError(PairError):- """The server rejected the session ID as unknown."""+class StaleNotebookError(PairError):+ """The server rejected the Notebook ID as unknown."""-class StableSessionUnsupportedError(PairError):- """The server cannot resolve stable session IDs."""+class NotebookUnsupportedError(PairError):+ """The server discovery does not expose host notebooks."""@dataclass(frozen=True)class SSEEvent:+ """A parsed server-sent event with an optional stream resume cursor."""+name: strdata: str+ id: str | None = None@dataclass(frozen=True)class ExecutionResult:+ """Captured output and final outcome of a notebook execution."""+success: booloutput: dict[str, str] | Nonestdout: strstderr: str+ outcome: str = "succeeded"def load_token(@@ -98,19 +132,24 @@ def _endpoint_url(url: str, path: str) -> str:).geturl()-def iter_sse(lines: Iterable[bytes]) -> Iterator[SSEEvent]:+def iter_sse(+ lines: Iterable[bytes], *, heartbeats: bool = False+) -> Iterator[SSEEvent]:name = "message"data: list[str] = []+ cursor: str | None = Nonefor raw_line in lines:line = raw_line.decode("utf-8").rstrip("\r\n")if not line:if data:- yield SSEEvent(name=name, data="\n".join(data))+ yield SSEEvent(name=name, data="\n".join(data), id=cursor)name = "message"data = []continueif line.startswith(":"):+ if heartbeats:+ yield SSEEvent(name="heartbeat", data="")continuefield, separator, value = line.partition(":")@@ -118,16 +157,55 @@ def iter_sse(lines: Iterable[bytes]) -> Iterator[SSEEvent]:value = value[1:]if field == "event":name = value+ elif field == "id" and "\0" not in value:+ cursor = valueelif field == "data":data.append(value)if data:- yield SSEEvent(name=name, data="\n".join(data))+ yield SSEEvent(name=name, data="\n".join(data), id=cursor)+++def pump_events(+ events: Iterable[SSEEvent],+ incoming: queue.Queue[SSEEvent | Exception | None],+ stopped: threading.Event,+) -> None:+ """Read events on a worker thread with bounded, cancellable delivery."""++ def put(value: SSEEvent | Exception | None) -> None:+ while not stopped.is_set():+ try:+ incoming.put(value, timeout=0.1)+ return+ except queue.Full:+ continue++ try:+ for event in events:+ if stopped.is_set():+ return+ put(event)+ except (+ PairError,+ OSError,+ http.client.HTTPException,+ ValueError,+ AttributeError,+ ) as error:+ put(error)+ finally:+ put(None)def open_response(- *, method: str, url: str, headers: dict[str, str], body: bytes | None-) -> HTTPResponse:+ *,+ method: str,+ url: str,+ headers: dict[str, str],+ body: bytes | None,+ read_timeout: float | None = None,+) -> EventStream:try:parsed = urlsplit(url)port = parsed.port@@ -150,32 +228,44 @@ def open_response(timeout=5.0,)connection.connect()- if connection.sock is not None:- connection.sock.settimeout(None)+ assert connection.sock is not None+ response_socket = connection.sock+ response_socket.settimeout(read_timeout)path = parsed.path or "/"if parsed.query:path = f"{path}?{parsed.query}"connection.request(method, path, body=body, headers=headers)response = connection.getresponse()except (ValueError, http.client.InvalidURL) as error:+ connection.close()raise PairInputError("The server URL is invalid.") from errorexcept (OSError, http.client.HTTPException) as error:- raise PairError("Could not connect to the server.") from error+ connection.close()+ raise PairConnectionError(+ "Could not connect to the server."+ ) from error- _raise_for_status(response)- return response+ try:+ _raise_for_status(response)+ except PairError:+ connection.close()+ raise+ return EventStream(response, response_socket)-def _response_detail(response: HTTPResponse) -> str | None:+def _response_problem(response: HTTPResponse) -> tuple[str | None, str | None]:try:payload = json.loads(response.read())except (OSError, UnicodeError, ValueError, http.client.HTTPException):- return None+ return None, Noneif isinstance(payload, dict):detail = payload.get("detail")- if isinstance(detail, str):- return detail- return None+ problem = payload.get("type")+ return (+ detail if isinstance(detail, str) else None,+ problem if isinstance(problem, str) else None,+ )+ return None, Nonedef _raise_for_status(response: HTTPResponse) -> None:@@ -184,20 +274,210 @@ def _raise_for_status(response: HTTPResponse) -> None:raise PairError("Authentication failed.")if 200 <= response.status < 300:return- detail = _response_detail(response)+ detail, problem = _response_problem(response)response.close()if isinstance(detail, str) and detail.startswith(("Invalid session id", "Invalid stable session id")):- raise StaleSessionError(detail)+ raise StaleNotebookError(detail)if detail == "Missing Marimo-Session-Id header":- raise StableSessionUnsupportedError+ raise NotebookUnsupportedError+ if response.status == 404:+ raise StaleNotebookError(detail or "Unknown notebook.")+ if problem == "tag:marimo.io,2026:host/no-runtime":+ raise NoRuntimeError(detail or "The notebook has no running kernel.")+ if problem == "tag:marimo.io,2026:host/conflict":+ raise RunConflictError(+ detail or "The notebook already has an active run."+ )if detail:raise PairError(detail)raise PairError(f"Server returned {response.status}.")def execute(+ *,+ url: str,+ notebook_id: str,+ token: str,+ code: str,+ stdout: TextIO,+ stderr: TextIO,+ stream: bool,+) -> ExecutionResult:+ response = open_events(+ url=url,+ notebook=notebook_id,+ token=token,+ identity=str(uuid4()),+ name="pair execute",+ kind="client",+ types="run,execution,console",+ read_timeout=45,+ )+ stdout_parts: list[str] = []+ stderr_parts: list[str] = []+ executions: set[str] = set()+ output: dict[str, str] | None = None+ run_url = _endpoint_url(+ url, f"/notebooks/{quote(notebook_id, safe='')}/runtime/runs"+ )+ headers = {+ "Authorization": f"Bearer {token}",+ "Content-Type": "application/json",+ }++ def mutation(+ method: str, endpoint: str, body: bytes | None = None+ ) -> object:+ reply = open_response(+ method=method,+ url=endpoint,+ headers={**headers, "Idempotency-Key": str(uuid4())},+ body=body,+ )+ try:+ return json.load(reply.response)+ finally:+ reply.close()++ def write(target: TextIO, parts: list[str], value: str) -> None:+ if stream:+ target.write(value)+ target.flush()+ else:+ parts.append(value)++ stopped = threading.Event()+ interrupted = threading.Event()+ interrupt_sent = False+ reader: threading.Thread | None = None+ previous_handler = None++ def request_interrupt(_signum: int, _frame: FrameType | None) -> None:+ interrupted.set()++ try:+ events = iter_sse(response)+ for initial_event in events:+ if initial_event.name == "ready":+ break+ else:+ raise PairError("The notebook stream ended before it was ready.")+ if threading.current_thread() is threading.main_thread():+ previous_handler = signal.signal(signal.SIGINT, request_interrupt)+ started = mutation(+ "POST", run_url, json.dumps({"code": code}).encode()+ )+ if not isinstance(started, dict) or not isinstance(+ started.get("id"), str+ ):+ raise PairError("The server returned an invalid run.")+ run_id = str(started["id"])+ incoming: queue.Queue[SSEEvent | Exception | None] = queue.Queue(+ maxsize=64+ )++ reader = threading.Thread(+ target=pump_events, args=(events, incoming, stopped), daemon=True+ )+ reader.start()+ while True:+ if interrupted.is_set() and not interrupt_sent:+ interrupt_sent = True+ try:+ mutation("DELETE", f"{run_url}/{quote(run_id, safe='')}")+ except RunConflictError:+ # Completion can win the race with the interrupt request.+ pass+ try:+ event = incoming.get(timeout=0.1)+ except queue.Empty:+ continue+ except KeyboardInterrupt:+ interrupted.set()+ continue+ if event is None:+ raise StopIteration+ if isinstance(event, BaseException):+ raise event+ payload = json.loads(event.data)+ if event.name == "execution":+ execution = payload["execution"]+ if execution.get("run_id") != run_id:+ continue+ executions.add(execution["id"])+ outcome = execution.get("outcome")+ if isinstance(outcome, dict):+ if outcome.get("kind") == "value":+ output = outcome.get("display")+ elif (+ outcome.get("kind") == "error"+ and execution.get("status") == "completed"+ ):+ error = outcome["error"]+ traceback = error.get("traceback")+ if (+ isinstance(traceback, dict)+ and traceback.get("mimetype") == "text/plain"+ ):+ text = traceback["data"]+ else:+ name = error.get("name")+ text = (+ f"{name}: {error['message']}"+ if name+ else error["message"]+ )+ write(stderr, stderr_parts, text.rstrip("\n") + "\n")+ elif event.name == "console":+ console = payload["console"]+ if console["execution_id"] in executions:+ if console["name"] == "stdout":+ write(stdout, stdout_parts, console["text"])+ else:+ write(stderr, stderr_parts, console["text"])+ elif event.name == "run":+ run = payload["run"]+ if run["id"] == run_id and run["status"] == "completed":+ if stream and output is not None:+ stdout.write(f"{output['data']}\n")+ if run["outcome"] not in (+ "succeeded",+ "failed",+ "interrupted",+ ):+ raise ValueError("Missing run outcome")+ return ExecutionResult(+ success=run["outcome"] == "succeeded",+ output=output,+ stdout="".join(stdout_parts),+ stderr="".join(stderr_parts),+ outcome=run["outcome"],+ )+ except (+ StopIteration,+ PairConnectionError,+ OSError,+ http.client.HTTPException,+ ValueError,+ KeyError,+ TypeError,+ AttributeError,+ ) as error:+ raise PairError(+ "The execution response ended before completion was confirmed."+ ) from error+ finally:+ if previous_handler is not None:+ signal.signal(signal.SIGINT, previous_handler)+ stopped.set()+ response.close()+ if reader is not None:+ reader.join(timeout=1)+++def execute_editor(*,url: str,session_id: str,@@ -215,12 +495,14 @@ def execute(if token is not None:headers["Authorization"] = f"Bearer {token}"body = json.dumps({"code": code}).encode("utf-8")- response = open_response(- method="POST",- url=request_url,- headers=headers,- body=body,- )+ try:+ response = open_response(+ method="POST", url=request_url, headers=headers, body=body+ )+ except PairConnectionError as error:+ raise PairError(+ "The execution response ended before completion was confirmed."+ ) from errorstdout_parts: list[str] = []stderr_parts: list[str] = []@@ -257,6 +539,9 @@ def execute(stdout.write(f"{output['data']}\n")return ExecutionResult(success=bool(payload["success"]),+ outcome="succeeded"+ if payload["success"]+ else "failed",output=output,stdout="".join(stdout_parts),stderr="".join(stderr_parts),@@ -281,6 +566,141 @@ def execute(response.close()+@dataclass(frozen=True)+class EventStream:+ """An HTTP response whose socket can be closed to unblock its reader."""++ response: HTTPResponse+ socket: socket.socket++ def __iter__(self) -> Iterator[bytes]:+ return iter(self.response)++ def close(self) -> None:+ # Shutdown interrupts a blocked reader before closing its file handle.+ try:+ self.socket.shutdown(socket.SHUT_RDWR)+ except OSError:+ pass+ try:+ self.response.close()+ finally:+ self.socket.close()+++def open_events(+ *,+ url: str,+ notebook: str,+ token: str | None,+ identity: str,+ name: str,+ cursor: str | None = None,+ kind: str = "agent",+ types: str = "custom,attachment",+ read_timeout: float | None = 45,+) -> EventStream:+ headers = {+ ATTACHMENT_IDENTITY: identity,+ ATTACHMENT_KIND: kind,+ ATTACHMENT_NAME: name,+ }+ if token is not None:+ headers["Authorization"] = f"Bearer {token}"+ if cursor is not None:+ headers["Last-Event-ID"] = cursor+ return open_response(+ method="GET",+ url=_endpoint_url(url, f"/notebooks/{quote(notebook, safe='')}/events")+ + f"?types={types}",+ headers=headers,+ body=None,+ read_timeout=read_timeout,+ )+++@dataclass(frozen=True)+class HostEndpoint:+ """Host API address and bearer token from a validated live host record."""++ url: str+ token: str = field(repr=False)+++def resolve_host(url: str, *, root: Path | None = None) -> HostEndpoint:+ import os+ import stat++ import msgspec+ import psutil++ from marimo._core import protocol+ from marimo._utils.xdg import marimo_state_dir++ def normalized(value: str) -> tuple[str, str | None, int, str]:+ parsed = urlsplit(value)+ if parsed.scheme not in ("http", "https") or parsed.hostname is None:+ raise PairInputError("The server URL must use http or https.")+ host = parsed.hostname.lower()+ if host == "localhost":+ host = "127.0.0.1"+ path = parsed.path.rstrip("/")+ path = path.removesuffix(HOST_API_PATH)+ return (+ parsed.scheme,+ host,+ parsed.port or (443 if parsed.scheme == "https" else 80),+ path,+ )++ try:+ selected = normalized(url)+ except ValueError as error:+ raise PairInputError("The server URL is invalid.") from error+ directory = root if root is not None else marimo_state_dir() / "hosts-v1"+ for path in sorted(directory.glob("*.json")):+ try:+ descriptor = os.open(+ path,+ os.O_RDONLY+ | getattr(os, "O_NOFOLLOW", 0)+ | getattr(os, "O_NONBLOCK", 0),+ )+ with os.fdopen(descriptor, "rb") as record_file:+ info = os.fstat(record_file.fileno())+ if not stat.S_ISREG(info.st_mode):+ continue+ if os.name == "posix" and (+ info.st_uid != os.getuid() or info.st_mode & 0o077+ ):+ continue+ record = msgspec.json.decode(+ record_file.read(), type=protocol.HostRecord+ )+ if normalized(record.url) != selected:+ continue+ process = psutil.Process(record.process.pid)+ if (+ not process.is_running()+ or process.status() == psutil.STATUS_ZOMBIE+ ):+ continue+ if (+ abs(+ process.create_time()+ - record.process.started_at.timestamp()+ )+ > 1e-6+ ):+ continue+ return HostEndpoint(record.url, record.token)+ except (OSError, ValueError, msgspec.DecodeError, psutil.Error):+ continue+ raise PairError(+ "No live host record matches this URL. Start a local edit server with MARIMO_ENABLE_HOST=1, or restart the existing server with it."+ )++def list_sessions(*, url: str, token: str | None) -> dict[str, dict[str, str | None]]:@@ -296,7 +716,7 @@ def list_sessions()try:try:- payload = json.load(response)+ payload = json.load(response.response)except (OSError,UnicodeError,@@ -320,7 +740,7 @@ def list_sessions(if "filename" not in session or "path" not in session:raise PairError(message)if "session_id" not in session:- raise StableSessionUnsupportedError+ raise NotebookUnsupportedErrorstable_session_id = session["session_id"]filename = session["filename"]path = session["path"]@@ -330,36 +750,74 @@ def list_sessions(or (path is not None and not isinstance(path, str))):raise PairError(message)+ notebook_id = session.get("notebook_id")+ if notebook_id is not None and not isinstance(notebook_id, str):+ raise PairError(message)sessions[session_id] = {"session_id": stable_session_id,"filename": filename,"path": path,+ "notebook_id": notebook_id,}return sessions-def resolve_session(*, url: str, token: str | None) -> str:+def resolve_notebook(*, url: str, token: str | None) -> str:sessions = list_sessions(url=url, token=token)- safe_url = display_url(url)- if len(sessions) == 1:- stable_session_id = next(iter(sessions.values()))["session_id"]- assert stable_session_id is not None- return stable_session_id- if not sessions:- message = f"No running session on {safe_url}."- raise NoSessionError(message, url=safe_url)-candidates = sorted(- session["session_id"]- for session in sessions.values()- if session["session_id"] is not None+ {+ session["notebook_id"]+ for session in sessions.values()+ if session["notebook_id"] is not None+ })- message = f"Server {safe_url} has {len(candidates)} running sessions."- raise AmbiguousSessionError(- message, url=safe_url, candidates=tuple(candidates)+ safe_url = display_url(url)+ if len(candidates) == 1:+ return candidates[0]+ if not candidates:+ raise NoNotebookError(+ f"No host notebook on {safe_url}. Save and open the notebook in edit mode.",+ url=safe_url,+ )+ raise AmbiguousNotebookError(+ f"Server {safe_url} has {len(candidates)} notebooks.",+ url=safe_url,+ candidates=tuple(candidates),)+def resolve_execution_target(+ *, url: str, token: str | None, session_id: str | None = None+) -> tuple[str | None, str]:+ """Choose a host Notebook or editor Session before submitting code."""+ sessions = list_sessions(url=url, token=token)+ found = [+ value+ for value in sessions.values()+ if session_id is None or value["session_id"] == session_id+ ]+ if not found:+ if session_id is not None:+ raise StaleNotebookError(+ f"Invalid stable session id: {session_id}"+ )+ raise NoNotebookError(+ f"No running session on {display_url(url)}.", url=display_url(url)+ )+ if len(found) != 1:+ raise AmbiguousNotebookError(+ f"Server {display_url(url)} has {len(found)} running sessions.",+ url=display_url(url),+ candidates=tuple(+ sorted(str(value["session_id"]) for value in found)+ ),+ )+ selected = found[0]+ stable_id = selected["session_id"]+ assert stable_id is not None+ return selected.get("notebook_id"), stable_id++def registry_urls() -> list[str]:import psutildiff --git a/marimo/_cli/pair/commands.py b/marimo/_cli/pair/commands.pyindex 1fe8290b8f..2756436014 100644--- a/marimo/_cli/pair/commands.py+++ b/marimo/_cli/pair/commands.py@@ -7,32 +7,38 @@ import osimport reimport shleximport sys-from dataclasses import dataclass, fieldfrom pathlib import Pathimport clickfrom marimo._cli.help_formatter import ColoredCommand, ColoredGroupfrom marimo._cli.pair.client import (- AmbiguousSessionError,- NoSessionError,+ AmbiguousNotebookError,+ NoNotebookError,+ NoRuntimeError,+ NotebookUnsupportedError,+ PairConnectionError,PairError,PairInputError,- StableSessionUnsupportedError,- StaleSessionError,+ RunConflictError,+ StaleNotebookError,display_url,execute as execute_code,+ execute_editor,list_sessions,load_token,registry_urls,- resolve_session,+ resolve_execution_target,+ resolve_host,)+from marimo._cli.pair.connection import (+ ConnectionStore,+ connection_identity,+)+from marimo._cli.pair.forwarder import ForwarderConfig, start_forwarder+from marimo._cli.pair.harnesses import detect_target, environment_identityfrom marimo._cli.pair.prompts import render_promptfrom marimo._server.ai.skills import utils as skills_utils-from marimo._utils.env import pair_preview_enabled--SKILL_NAME = "marimo-pair"-SKILL_FILE = "SKILL.md"_REFERENCES_DIR = (Path(skills_utils.__file__).parent / "marimo-pair" / "references"@@ -51,136 +57,6 @@ def _token_dir() -> Path:return _cached_token_dir-@dataclass(frozen=True)-class AgentConfig:- name: str- skill_dirs: list[Path] = field(default_factory=list)-- def has_skill(self) -> bool:- for directory in self.skill_dirs:- try:- if (directory / SKILL_NAME / SKILL_FILE).exists():- return True- except OSError:- # Skill detection is advisory. An inaccessible directory must- # not prevent marimo from generating the pairing prompt.- continue- return False---def _claude_skill_dirs() -> list[Path]:- """Return all directories where a Claude Code skill may be installed.-- Skills can be installed directly or bundled in a marketplace plugin in- both the global (`~/.claude`) and local (`.claude`) config directories.- """- roots = [Path.home() / ".claude", Path.cwd() / ".claude"]- subdirs = ["skills", "plugins", str(Path("plugins") / "marketplaces")]- return [- *[root / sub for root in roots for sub in subdirs],- *[- skill_dir- for root in roots- for skill_dir in _plugin_skill_dirs(root)- ],- ]---def _plugin_skill_dirs(root: Path) -> list[Path]:- """Return skill directories from marketplace and cached plugins."""- plugins = root / "plugins"- return [- *plugins.glob("marketplaces/*/skills"),- *plugins.glob(f"cache/*/{SKILL_NAME}/*/skills"),- ]---def _codex_skill_dirs() -> list[Path]:- """Return directories where a Codex skill may be installed.-- Codex loads repository skills from `.agents/skills` directories between- the current directory and repository root. It also loads user and admin- skills from `~/.agents/skills` and `/etc/codex/skills`, respectively.-- Keep checking `.codex` for existing direct and plugin installations.- """- cwd = Path.cwd()- home = Path.home()- roots = [home / ".codex", cwd / ".codex"]- return [- *_codex_repository_skill_dirs(cwd),- home / ".agents" / "skills",- Path("/etc/codex/skills"),- *[root / "skills" for root in roots],- *[- skill_dir- for root in roots- for skill_dir in _plugin_skill_dirs(root)- ],- ]---def _codex_repository_skill_dirs(cwd: Path) -> list[Path]:- """Return Codex skill directories from `cwd` through the repository root."""- skill_dirs: list[Path] = []- for directory in (cwd, *cwd.parents):- skill_dirs.append(directory / ".agents" / "skills")- try:- is_repository_root = (directory / ".git").exists()- except OSError:- # Do not search above an ancestor whose repository status cannot- # be determined. The global user and admin paths remain available.- return skill_dirs- if is_repository_root:- return skill_dirs-- # Outside a Git repository, Codex still checks the current directory.- return skill_dirs[:1]---def _opencode_skill_dirs() -> list[Path]:- """Return directories where an opencode skill (or compatible layout) may live.-- https://opencode.ai/docs/skills/- Checked roots are the parent of `<skill-name>/SKILL.md` for:-- - Project opencode: `.opencode/skills/`- - Global opencode: `~/.config/opencode/skills/`- - Project Claude-compatible: `.claude/skills/`- - Global Claude-compatible: `~/.claude/skills/`- - Project agent-compatible: `.agents/skills/`- - Global agent-compatible: `~/.agents/skills/`- """- cwd = Path.cwd()- home = Path.home()- return [- cwd / ".opencode" / "skills",- home / ".config" / "opencode" / "skills",- cwd / ".claude" / "skills",- home / ".claude" / "skills",- cwd / ".agents" / "skills",- home / ".agents" / "skills",- ]---def pair_agents() -> dict[str, AgentConfig]:- """Return agent configs; paths use `Path.cwd()` at call time."""- return {- "claude": AgentConfig(- name="Claude Code",- skill_dirs=_claude_skill_dirs(),- ),- "codex": AgentConfig(- name="Codex",- skill_dirs=_codex_skill_dirs(),- ),- "opencode": AgentConfig(- name="opencode",- skill_dirs=_opencode_skill_dirs(),- ),- }--def _doc_topics() -> dict[str, str]:return {path.stem: path.read_text(encoding="utf-8")@@ -207,15 +83,23 @@ class _DocsCommand(ColoredCommand):\bAuthentication:- If a token-file path is supplied, add --token-file <PATH> to every- execute and notebook list command. Pass the path, not the file contents.+ Notebook discovery uses the editor token. Pass --token-file <PATH> to+ notebook list or execute without --notebook when a token is required.+ Host commands read their token from the private local host record.+ With host support off, execution uses the editor token and stable Session.\bWorkflow:If no server is running, start one in the background:marimo edit <notebook.py> --no-token- If you do not have the server URL or session:+ If you do not have the server URL or notebook ID:marimo pair notebook list+ Connect to the notebook before waiting for work.+ Run marimo pair connect --help to check supported harnesses.+ If your harness is supported, start the server with MARIMO_ENABLE_HOST=1,+ then run (restart an existing server to enable host support):+ marimo pair connect --url <URL> --notebook <NOTEBOOK>+ Otherwise, work with the notebook using pair execute:marimo pair execute --url <URL> --session <SESSION> --code-file - <<'PY'import marimo._code_mode as cmasync with cm.get_context() as ctx:@@ -223,7 +107,7 @@ class _DocsCommand(ColoredCommand):cid = ctx.create_cell("import pandas as pd")ctx.run_cell(cid)PY- marimo pair execute --url <URL> --session <SESSION> --code-file - <<'PY'+ marimo pair execute --url <URL> --notebook <NOTEBOOK> --code-file - <<'PY'import marimo._code_mode as cmasync with cm.get_context() as ctx:cell = ctx.cells["<CELL_ID>"]@@ -232,14 +116,28 @@ class _DocsCommand(ColoredCommand):\bTarget selection:- --session takes the session_id from marimo pair notebook list. It does not- change when the page reloads or the notebook is renamed. If a command reports- an unknown session, the notebook was closed or restarted: run- marimo pair notebook list again and pick the new session_id.- If one notebook has several sessions, ask the user which one.- Do not switch sessions after authentication or connection errors,+ --session takes a stable session_id for editor execution.+ --notebook takes notebook_id for host execution. It survives+ kernel restarts and page reloads. Only saved notebooks inside the project+ root have a host notebook ID. Host commands need a local edit server.+ If several notebooks are open, ask the user which one.+ Do not switch notebooks after authentication or connection errors,or when execution is unconfirmed.+ \b+ Agent messages (preview):+ Start the server with MARIMO_ENABLE_HOST=1. The CLI needs no flag.+ Inside Codex, Claude Code, or OpenCode, run:+ marimo pair connect --url <URL> --notebook <NOTEBOOK>.+ Codex must use its shared daemon and support codex queue.+ Claude Code requires its native inbox on macOS or Linux.+ OpenCode 2.x requires its registered local service.+ Inbound message settings still apply; messages can be held or refused.+ Notebook agent messages arrive here as messages from marimo.+ Oversized agent messages include a complete JSON file on this machine.+ Files remain after detach. Cleanup removes owned files older than 24 hours.+ Use pair detach --notebook <NOTEBOOK> to stop the inbox.+\bRules:Cells are the unit of work. The scratchpad is temporary; only code mode edits persist.@@ -261,7 +159,7 @@ class _DocsCommand(ColoredCommand):ctx.delete_cell(cid)ctx.packages.add("pandas>=2") # queued, installs on exitIf a cm call fails, run help(cm):- marimo pair execute --url <URL> --session <SESSION> -c 'import marimo._code_mode as cm; help(cm)'+ marimo pair execute --url <URL> --notebook <NOTEBOOK> -c 'import marimo._code_mode as cm; help(cm)'""",)def pair() -> None:@@ -271,7 +169,7 @@ def pair() -> None:@click.command(cls=ColoredCommand,help="""Run Python in the selected live notebook kernel's scratchpad.""",- short_help="""Run Python in a live notebook session.""",+ short_help="""Run Python in a live notebook.""",)@click.option("--url",@@ -280,11 +178,17 @@ def pair() -> None:help="Server URL.",)@click.option(- "--session",- "session_id",+ "--notebook",+ "notebook_id",required=False,metavar="ID",- help="Stable session_id from marimo pair notebook list.",+ help="Host notebook_id from marimo pair notebook list.",+)+ "--session",+ "session_id",+ default=None,+ help="Stable Session ID from notebook list. Host execution is preferred when available.",)@click.option("--token-file",@@ -312,12 +216,15 @@ def pair() -> None:def execute(ctx: click.Context,url: str,+ notebook_id: str | None,session_id: str | None,token_file: Path | None,code: str | None,code_file: str | None,stream: bool,) -> None:+ if notebook_id is not None and session_id is not None:+ raise click.UsageError("Pass --session or --notebook, not both.")if (code is None) == (code_file is None):raise click.UsageError("Specify -c or --code-file.")@@ -332,35 +239,69 @@ def execute(if not code:raise click.UsageError("Code must not be empty.")+ editor = notebook_id is None+ selector = "--session" if editor else "--notebook"try:- token = load_token(token_file, os.environ)- if session_id is None:- session_id = resolve_session(url=url, token=token)- result = execute_code(- url=url,- session_id=session_id,- token=token,- code=code,- stdout=sys.stdout,- stderr=sys.stderr,- stream=stream,+ token = (+ load_token(token_file, os.environ) if notebook_id is None else None)+ if notebook_id is None:+ notebook_id, session_id = resolve_execution_target(+ url=url, token=token, session_id=session_id+ )+ editor = notebook_id is None+ selector = "--session" if editor else "--notebook"+ if editor:+ assert session_id is not None+ result = execute_editor(+ url=url,+ session_id=session_id,+ token=token,+ code=code,+ stdout=sys.stdout,+ stderr=sys.stderr,+ stream=stream,+ )+ else:+ assert notebook_id is not None+ host = resolve_host(url)+ result = execute_code(+ url=host.url,+ notebook_id=notebook_id,+ token=host.token,+ code=code,+ stdout=sys.stdout,+ stderr=sys.stderr,+ stream=stream,+ )except PairError as error:error_text, next_text = _failure_guidance(- error, url=url, session_id=session_id+ error,+ url=url,+ notebook_id=notebook_id or session_id,+ selector=selector,)_emit_failure(- error_text, next_text, session_id=session_id, stream=stream+ error_text,+ next_text,+ notebook_id=notebook_id,+ session_id=session_id if notebook_id is None else None,+ stream=stream,)ctx.exit(2)except KeyboardInterrupt:click.echo("Interrupted.", err=True)ctx.exit(1)+ target_id = notebook_id or session_id+ assert target_id is not Nonenext_text = Noneif not result.success:next_text = _kernel_next(- result.stderr, url=display_url(url), session_id=session_id+ result.stderr,+ url=display_url(url),+ notebook_id=target_id,+ selector=selector,)if stream:@@ -369,7 +310,7 @@ def execute(_emit_failure("Execution failed.",next_text,- session_id=session_id,+ notebook_id=notebook_id,stream=True,)ctx.exit(1)@@ -377,11 +318,16 @@ def execute(payload: dict[str, object] = {"success": result.success,+ "outcome": result.outcome,"output": result.output,"stdout": result.stdout,"stderr": result.stderr,- "session": {"id": session_id},+ ("session" if editor else "notebook"): {+ "id": session_id if editor else notebook_id+ },}+ if session_id is not None:+ payload["session"] = {"id": session_id}if next_text:payload["next"] = next_textclick.echo(json.dumps(payload, indent=2))@@ -389,27 +335,22 @@ def execute(ctx.exit(1)-_TOKEN_NEXT = (- "Pass --token-file <path>. If no file exists, check for MARIMO_TOKEN "- 'with `test -n "$MARIMO_TOKEN"`; the commands use it when set. '- "Never print the token. If you have no token, ask the user."-)_HEADLESS_NEXT = ("A headless server has no session until a browser opens the notebook.")-def _execute_prefix(url: str, session_id: str) -> str:- """Shell-safe start of an execute command that targets one session."""+def _execute_prefix(url: str, notebook_id: str, selector: str) -> str:+ """Shell-safe start of an execute command that targets one notebook."""return ("marimo pair execute "- f"--url {shlex.quote(url)} --session {shlex.quote(session_id)}"+ f"--url {shlex.quote(url)} {selector} {shlex.quote(notebook_id)}")-def _inspect_command(url: str, session_id: str) -> str:+def _inspect_command(url: str, notebook_id: str, selector: str) -> str:return (- f"{_execute_prefix(url, session_id)} --code-file - <<'PY'\n"+ f"{_execute_prefix(url, notebook_id, selector)} --code-file - <<'PY'\n""import marimo._code_mode as cm\n""async with cm.get_context() as ctx:\n"" for cell in ctx.cells.values():\n"@@ -418,9 +359,11 @@ def _inspect_command(url: str, session_id: str) -> str:)-def _read_cell_command(url: str, session_id: str, cell_id: str) -> str:+def _read_cell_command(+ url: str, notebook_id: str, cell_id: str, selector: str+) -> str:return (- f"{_execute_prefix(url, session_id)} --code-file - <<'PY'\n"+ f"{_execute_prefix(url, notebook_id, selector)} --code-file - <<'PY'\n""import marimo._code_mode as cm\n""async with cm.get_context() as ctx:\n"f" cell = ctx.cells[{cell_id!r}]\n"@@ -430,14 +373,16 @@ def _read_cell_command(url: str, session_id: str, cell_id: str) -> str:)-def _help_cm_command(url: str, session_id: str) -> str:+def _help_cm_command(url: str, notebook_id: str, selector: str) -> str:return (- f"{_execute_prefix(url, session_id)} "+ f"{_execute_prefix(url, notebook_id, selector)} ""-c 'import marimo._code_mode as cm; help(cm)'")-def _kernel_next(stderr: str, *, url: str, session_id: str) -> str | None:+def _kernel_next(+ stderr: str, *, url: str, notebook_id: str, selector: str+) -> str | None:"""Recovery guidance for the code-mode mistakes agents make most.Matches the traceback text the kernel returned. Unknown failures get@@ -458,7 +403,7 @@ def _kernel_next(stderr: str, *, url: str, session_id: str) -> str | None:f"Edits apply when the async with block exits, so '{cell_id}' ""does not exist yet in this block. ""Read it in a separate execute:\n"- + _read_cell_command(url, session_id, cell_id)+ + _read_cell_command(url, notebook_id, cell_id, selector))match = re.search(r"AttributeError: '?([\w.]+)'? (?:object )?has no attribute '(\w+)'",@@ -471,53 +416,67 @@ def _kernel_next(stderr: str, *, url: str, session_id: str) -> str | None:hint = " Use ctx.cells[cid] or ctx.cells.values()."return (f"'{owner}' has no attribute '{name}'.{hint} For the full API:\n"- + _help_cm_command(url, session_id)+ + _help_cm_command(url, notebook_id, selector))return Nonedef _failure_guidance(- error: PairError, *, url: str, session_id: str | None+ error: PairError, *, url: str, notebook_id: str | None, selector: str) -> tuple[str, str | None]:"""Error text and one `next` step for a failure before the kernel ran."""safe_url = display_url(url)- if isinstance(error, AmbiguousSessionError):+ if isinstance(error, NoRuntimeError):+ return str(+ error+ ), "Open the saved notebook and start its kernel, then retry."+ if isinstance(error, RunConflictError):+ return (+ str(error),+ "Wait for the active run to finish. Inspect its results before retrying.",+ )+ if isinstance(error, AmbiguousNotebookError):lines = [- "Pass --session to choose one. Never switch sessions silently."+ f"Pass {selector} to choose one. Never switch notebooks silently."]lines.extend(- f"{session_id}: marimo pair execute --url "- f"{display_url(error.url)} --session {session_id} ..."- for session_id in error.candidates+ f"{notebook_id}: marimo pair execute --url "+ f"{display_url(error.url)} {selector} {shlex.quote(notebook_id)} ..."+ for notebook_id in error.candidates)return str(error), "\n".join(lines)- if isinstance(error, NoSessionError):+ if isinstance(error, NoNotebookError):return str(error), (f"{_HEADLESS_NEXT} Ask the user to open it, then:\n"f"marimo pair notebook list --url {display_url(error.url)}")- if isinstance(error, StableSessionUnsupportedError):+ if isinstance(error, NotebookUnsupportedError):return ((f"Server {safe_url} runs a marimo version without "- "session_id. Upgrade marimo on the server."+ "notebook_id. Upgrade marimo on the server."),None,)- if isinstance(error, StaleSessionError):+ if isinstance(error, StaleNotebookError):return ((- f"No session {session_id or '<ID>'} on {safe_url}. "- "The notebook was closed or restarted."+ f"No notebook {notebook_id or '<ID>'} on {safe_url}. "+ "Run notebook list to find the current host notebook."),f"marimo pair notebook list --url {safe_url}",)message = str(error)if message == "Authentication failed.":- return message, _TOKEN_NEXT+ return (+ message,+ "Restart the local edit server and retry host discovery."+ if selector == "--notebook"+ else "Pass --token-file <path> or set MARIMO_TOKEN for editor authentication.",+ )if message.startswith("The server URL"):return message, ("Use the url field from:\nmarimo pair notebook list")- if message == "Could not connect to the server.":+ if isinstance(error, PairConnectionError):return f"Could not connect to {safe_url}.", ("Check the URL. To find live servers: marimo pair notebook list")@@ -526,7 +485,7 @@ def _failure_guidance():return "Outcome unknown. The code may have run. Do not retry it.", ("Inspect the notebook first:\n"- + _inspect_command(safe_url, session_id or "<SESSION>")+ + _inspect_command(safe_url, notebook_id or "<ID>", selector))return message, None@@ -535,8 +494,9 @@ def _emit_failure(error_text: str,next_text: str | None,*,- session_id: str | None,+ notebook_id: str | None,stream: bool,+ session_id: str | None = None,) -> None:if stream:click.echo(f"error: {error_text}", err=True)@@ -557,7 +517,9 @@ def _emit_failure("output": None,"stdout": None,"stderr": None,- "session": {"id": session_id},+ ("session" if session_id is not None else "notebook"): {+ "id": session_id if session_id is not None else notebook_id+ },})click.echo(json.dumps(payload, indent=2))@@ -599,30 +561,21 @@ def docs(topic: str | None) -> None:help="URL of the running marimo kernel.",)@click.option(- "--session",- "session_id",+ "--notebook",+ "notebook_id",default=None,type=str,- help="Stable session_id to include in the prompt.",-)- "--claude",- is_flag=True,- default=False,- help="Validate that the marimo-pair Claude Code skill is installed.",-)- "--codex",- is_flag=True,- default=False,- help="Validate that the marimo-pair Codex skill is installed.",+ help="Host notebook_id to include in the prompt.",)@click.option(- "--opencode",- is_flag=True,- default=False,- help="Validate that the marimo-pair opencode skill is installed.",+ "--session",+ "session_id",+ default=None,+ help="Stable Session ID from notebook list. Host execution is preferred when available.",)[email protected]("--claude", is_flag=True, hidden=True, expose_value=False)[email protected]("--codex", is_flag=True, hidden=True, expose_value=False)[email protected]("--opencode", is_flag=True, hidden=True, expose_value=False)@click.option("--with-token",is_flag=True,@@ -631,49 +584,13 @@ def docs(topic: str | None) -> None:)def prompt(url: str,+ notebook_id: str | None,session_id: str | None,- claude: bool,- codex: bool,- opencode: bool,with_token: bool,) -> None:- """- Generate a prompt for pair programming.-- Example usage:-- claude "$(uvx marimo@latest pair prompt --url 'https://localhost:8000' --claude)"- codex "$(uvx marimo@latest pair prompt --url 'https://localhost:8000' --codex)"- opencode "$(uvx marimo@latest pair prompt --url 'https://localhost:8000' --opencode)"-- # Connect to a specific notebook- claude "$(uvx marimo@latest pair prompt --url 'https://localhost:8000' --session 'sess-example' --claude)"-- # With an auth token- claude "$(uvx marimo@latest pair prompt --url 'https://localhost:8000' --claude --with-token)"- """- preview = pair_preview_enabled()- if not preview:- selected_agents = {- "claude": claude,- "codex": codex,- "opencode": opencode,- }- for key, agent in pair_agents().items():- if not selected_agents[key]:- continue- if not agent.has_skill():- click.echo(- f"The marimo-pair skill for {agent.name} could not be found.\n\n"- "Please install it with:\n\n"- " npx skills add marimo-team/marimo-pair\n\n"- "or\n\n"- " uvx deno -A npm:skills add marimo-team/marimo-pair\n\n"- "More instructions at "- "https://github.com/marimo-team/marimo-pair",- err=True,- )-+ """Generate CLI instructions for one Notebook or Session."""+ if notebook_id is not None and session_id is not None:+ raise click.UsageError("Pass --session or --notebook, not both.")token_file: Path | None = Noneif with_token:token = click.prompt(@@ -697,39 +614,13 @@ def prompt(finally:os.close(fd)- if preview:- click.echo(- render_prompt(- url=url,- session_id=session_id,- token_file=token_file,- )- )- return-- # Shell-quote dynamic values because this command is copy-pasted into a- # shell and values may contain spaces or metacharacters.- execute_cmd = f"execute-code.sh --url {shlex.quote(url)}"- if session_id:- execute_cmd += f" --session {shlex.quote(session_id)}"-- token_hint = ""- if token_file is not None:- token_hint = (- f"\n\nAn auth token is stored at {token_file}. "- f"Pass it via `{execute_cmd} "- f"--token \"$(cat '{token_file}')\"`."- )-- # Output the prompt to the wrapper agent CLIclick.echo(- "Use the /marimo-pair skill to pair-program on a running "- "marimo notebook.\n\n"- f"Connect to the notebook at: {url}\n\n"- f"Use `{execute_cmd}` from the marimo-pair "- "skill to execute code in the notebook."- f"{token_hint}\n\n"- "Once you are connected, send a fun toast (mo.status.toast(...)) to the user inside marimo letting them know you're ready to pair."+ render_prompt(+ url=url,+ notebook_id=notebook_id,+ session_id=session_id,+ token_file=token_file,+ ))@@ -755,6 +646,7 @@ def _group_notebooks("server": {"url": url},"name": session.get("filename"),"path": session.get("path"),+ "notebook_id": session.get("notebook_id"),"sessions": [],},)@@ -773,8 +665,8 @@ def _group_notebooks(@click.group(cls=ColoredGroup,- help="Find active notebooks and their sessions.",- short_help="""Find active notebooks and their sessions.""",+ help="Find active notebooks and their IDs.",+ short_help="""Find active notebooks and their IDs.""",)def notebook() -> None:pass@@ -783,8 +675,8 @@ def notebook() -> None:@click.command(name="list",cls=ColoredCommand,- help="List active notebooks and their session IDs.",- short_help="""List active notebooks and their session IDs.""",+ help="List active notebooks and their host IDs.",+ short_help="""List active notebooks and their host IDs.""",)@click.option("--url",@@ -814,10 +706,10 @@ def list_notebooks(urls: tuple[str, ...], token_file: Path | None) -> None:except PairError as error:if isinstance(error, PairInputError) and urls:raise click.UsageError(str(error)) from error- if isinstance(error, StableSessionUnsupportedError):+ if isinstance(error, NotebookUnsupportedError):warnings.append(f"Server {display_url(url)} runs a marimo version "- "without session_id. Upgrade marimo on the server."+ "without notebook_id. Upgrade marimo on the server.")else:message = str(error).rstrip(".")@@ -846,6 +738,96 @@ def list_notebooks(urls: tuple[str, ...], token_file: Path | None) -> None:notebook.add_command(list_notebooks)+++ cls=ColoredCommand,+ help=(+ "Connect this harness inbox to a live notebook.\n\n"+ "Supported harnesses: Codex, Claude Code, and OpenCode (macOS/Linux).\n\n"+ "OpenCode 2.x requires its registered local service.\n\n"+ "For other harnesses, use pair execute to work with the notebook."+ ),+)[email protected]("--url", required=True, help="Server URL.")+ "--notebook",+ "notebook_id",+ required=True,+ help="Host notebook ID from notebook list.",+)+ "--harness",+ type=click.Choice(["codex", "claude", "opencode"]),+ help="Select the inbox harness.",+)+ "--pid",+ type=click.IntRange(min=1),+ help=(+ "Process to track for connection lifetime. Defaults to the current harness. "+ "Its start time is captured automatically."+ ),+)+def connect(+ url: str, notebook_id: str, harness: str | None, pid: int | None+) -> None:+ try:+ _selected_harness, target = detect_target(os.environ, harness, pid)+ host = resolve_host(url)+ identity = connection_identity(+ notebook_id, target.kind, target.address+ )+ store = ConnectionStore()+ with store.locked(identity):+ store.stop(identity)+ start_forwarder(+ ForwarderConfig(+ host.url, notebook_id, identity, host.token, target+ ),+ store,+ )+ click.echo(+ f"Connected as {target.label}. Agent messages from this notebook arrive here as messages from marimo."+ )+ except (PairError, OSError) as error:+ raise click.ClickException(str(error)) from error+++ cls=ColoredCommand,+ help="Stop the forwarder and detach its notebook inbox.",+)+ "--notebook",+ "notebook_id",+ required=True,+ help="Host notebook ID from notebook list.",+)+ "--harness",+ type=click.Choice(["codex", "claude", "opencode"]),+ help="Select the harness to disconnect.",+)+def detach(notebook_id: str, harness: str | None) -> None:+ try:+ store = ConnectionStore()+ kind, conversation = environment_identity(os.environ, kind=harness)+ selected = store.select(+ notebook_id, kind=kind, conversation=conversation+ )+ if selected is not None:+ with store.locked(selected.identity):+ store.stop(selected.identity)+ click.echo(+ "Detached." if selected is not None else "No matching connection."+ )+ except (PairError, OSError) as error:+ raise click.ClickException(str(error)) from error+++pair.add_command(connect)+pair.add_command(detach)pair.add_command(execute)pair.add_command(docs)pair.add_command(notebook)diff --git a/marimo/_cli/pair/connection.py b/marimo/_cli/pair/connection.pynew file mode 100644index 0000000000..0aa57d04c3--- /dev/null+++ b/marimo/_cli/pair/connection.py@@ -0,0 +1,171 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import hashlib+import json+import os+import re+import tempfile+from contextlib import contextmanager+from pathlib import Path+from typing import TYPE_CHECKING, Literal++import msgspec++from marimo import _loggers+from marimo._cli.pair.client import PairInputError+from marimo._cli.pair.delivery import ProcessHandle+from marimo._utils.file_lock import file_lock+from marimo._utils.xdg import marimo_state_dir++if TYPE_CHECKING:+ from collections.abc import Iterator++_ID = re.compile(r"p1_[0-9a-f]{64}\Z")+LOGGER = _loggers.marimo_logger()+++class _InvalidConnection(PairInputError):+ """A malformed record that cannot establish process ownership."""+++def connection_identity(+ notebook: str, kind: str, conversation: str | None+) -> str:+ values = [+ "marimo-participant-v1",+ notebook,+ kind,+ "conversation" if conversation else "harness",+ conversation,+ ]+ raw = json.dumps(values, ensure_ascii=True, separators=(",", ":"))+ return "p1_" + hashlib.sha256(raw.encode("utf-8")).hexdigest()+++class Connection(msgspec.Struct, frozen=True):+ """Persisted ownership of a notebook-to-conversation forwarder.++ Process start times protect against PID reuse; credentials are not stored.+ """++ version: Literal[1]+ identity: str+ notebook: str+ harness_kind: str+ harness_pid: int+ harness_start: float+ forwarder_pid: int+ forwarder_start: float+ created_at: float++ @property+ def forwarder(self) -> ProcessHandle:+ return ProcessHandle(self.forwarder_pid, self.forwarder_start)+++class ConnectionStore:+ """Local connection records with atomic writes and per-identity locks."""++ def __init__(self, root: Path | None = None) -> None:+ self.root = root or marimo_state_dir() / "pair" / "connections-v1"++ def path(self, identity: str) -> Path:+ if _ID.fullmatch(identity) is None:+ raise PairInputError("Invalid Pair attachment identity.")+ return self.root / f"{identity}.json"++ def load(self, identity: str) -> Connection | None:+ try:+ raw = self.path(identity).read_bytes()+ except FileNotFoundError:+ return None+ except OSError as error:+ raise PairInputError(+ "Could not read the Pair connection."+ ) from error+ try:+ record = msgspec.json.decode(raw, type=Connection)+ except msgspec.DecodeError as error:+ raise _InvalidConnection(+ "Invalid Pair connection. Run connect again."+ ) from error+ if record.identity != identity:+ raise _InvalidConnection("Mismatched Pair connection identity.")+ if record.harness_pid <= 0 or record.forwarder_pid <= 0:+ raise _InvalidConnection("Invalid Pair process identity.")+ return record++ def select(+ self, notebook: str, *, kind: str, conversation: str | None+ ) -> Connection | None:+ if conversation is not None:+ record = self.load(+ connection_identity(notebook, kind, conversation)+ )+ if record is not None and (+ record.notebook != notebook or record.harness_kind != kind+ ):+ raise PairInputError("Mismatched Pair connection target.")+ return record+ candidates = []+ for path in self.root.glob("p1_*.json"):+ if _ID.fullmatch(path.stem) is None:+ continue+ try:+ record = self.load(path.stem)+ except _InvalidConnection:+ LOGGER.warning(+ "Skipped an invalid Pair connection record. "+ "Run connect inside its harness to replace it."+ )+ continue+ if record is not None and record.notebook == notebook:+ candidates.append(record)+ if len(candidates) > 1:+ raise PairInputError(+ "Several Pair connections match. Run this command inside the harness."+ )+ return candidates[0] if candidates else None++ def save(self, record: Connection) -> None:+ try:+ self.root.mkdir(parents=True, mode=0o700, exist_ok=True)+ descriptor, temporary = tempfile.mkstemp(+ dir=self.root, suffix=".tmp"+ )+ try:+ with os.fdopen(descriptor, "wb") as stream:+ stream.write(msgspec.json.encode(record))+ os.replace(temporary, self.path(record.identity))+ finally:+ Path(temporary).unlink(missing_ok=True)+ except OSError as error:+ raise PairInputError(+ "Could not save the Pair connection."+ ) from error++ def remove(self, record: Connection) -> None:+ # A replaced forwarder cannot delete the new owner's record.+ if self.load(record.identity) == record:+ self.path(record.identity).unlink(missing_ok=True)++ def stop(self, identity: str) -> None:+ """Stop and remove a connection while the caller holds its lock."""+ try:+ record = self.load(identity)+ except _InvalidConnection:+ # Malformed records cannot authorize signalling a process.+ self.path(identity).unlink(missing_ok=True)+ return+ if record is not None:+ record.forwarder.stop()+ self.remove(record)++ @contextmanager+ def locked(self, identity: str) -> Iterator[None]:+ self.root.mkdir(parents=True, mode=0o700, exist_ok=True)+ with file_lock(+ self.path(identity).with_suffix(".lock"), blocking=True+ ):+ yielddiff --git a/marimo/_cli/pair/delivery.py b/marimo/_cli/pair/delivery.pynew file mode 100644index 0000000000..e8a3a4fb84--- /dev/null+++ b/marimo/_cli/pair/delivery.py@@ -0,0 +1,114 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++from dataclasses import dataclass, field+from typing import TYPE_CHECKING, Protocol++if TYPE_CHECKING:+ from collections.abc import Mapping+++@dataclass(frozen=True)+class ProcessHandle:+ """A process identified by both PID and start time to detect PID reuse."""++ pid: int+ started: float++ @classmethod+ def capture(cls, pid: int) -> ProcessHandle:+ import psutil++ return cls(pid, psutil.Process(pid).create_time())++ def alive(self) -> bool:+ import psutil++ try:+ process = psutil.Process(self.pid)+ return (+ process.create_time() == self.started+ and process.is_running()+ and process.status() != psutil.STATUS_ZOMBIE+ )+ except psutil.Error:+ return False++ def stop(self) -> None:+ import psutil++ try:+ process = psutil.Process(self.pid)+ if (+ process.create_time() != self.started+ or not process.is_running()+ or process.status() == psutil.STATUS_ZOMBIE+ ):+ return+ process.terminate()+ try:+ process.wait(timeout=5)+ except psutil.TimeoutExpired:+ if process.status() == psutil.STATUS_ZOMBIE:+ return+ process.kill()+ try:+ process.wait(timeout=5)+ except psutil.TimeoutExpired:+ if process.status() != psutil.STATUS_ZOMBIE:+ raise+ except psutil.NoSuchProcess:+ pass+ except psutil.Error as error:+ from marimo._cli.pair.client import PairError++ raise PairError(+ "Could not stop the Pair forwarder process."+ ) from error+++@dataclass(frozen=True)+class DeliveryTarget:+ """An inbox address and the process that controls its connection lifetime.++ Credentials stay in memory and are excluded from diagnostic representations.+ """++ kind: str+ address: str+ label: str+ process: ProcessHandle | None = None+ auth_token: str | None = field(default=None, repr=False)+++class Harness(Protocol):+ """Discover a ready harness destination and bind its inbox.++ Each adapter checks readiness during detection, before returning a target.+ """++ kind: str++ def identity(self, env: Mapping[str, str]) -> str | None: ...++ def detect(+ self,+ env: Mapping[str, str],+ *,+ process: ProcessHandle | None = None,+ ) -> DeliveryTarget | None: ...++ def check(self) -> None: ...++ def open_inbox(self, target: DeliveryTarget) -> Inbox: ...+++class Inbox(Protocol):+ """Delivery and lifetime checks for one already-selected conversation."""++ @property+ def inbox_bytes(self) -> int: ...++ def send(self, text: str) -> None: ...++ def alive(self) -> bool: ...diff --git a/marimo/_cli/pair/forwarder.py b/marimo/_cli/pair/forwarder.pynew file mode 100644index 0000000000..81c55b5e7a--- /dev/null+++ b/marimo/_cli/pair/forwarder.py@@ -0,0 +1,366 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import http.client+import json+import logging+import os+import queue+import subprocess+import sys+import threading+import time+from dataclasses import dataclass+from logging.handlers import RotatingFileHandler+from pathlib import Path+from typing import TYPE_CHECKING, TypedDict++import msgspec++from marimo._cli.pair.artifacts import AgentMessageFiles, inbox_message+from marimo._cli.pair.client import (+ EventStream,+ PairConnectionError,+ PairError,+ SSEEvent,+ StaleNotebookError,+ iter_sse,+ open_events,+ pump_events,+)+from marimo._cli.pair.connection import Connection, ConnectionStore+from marimo._cli.pair.delivery import DeliveryTarget, ProcessHandle+from marimo._cli.pair.harnesses import harness_for+from marimo._messaging.messages import AGENT_MESSAGE_TYPE+from marimo._utils.subprocess import kill_subprocess++if TYPE_CHECKING:+ from collections.abc import Callable, Iterator++ from marimo._cli.pair.delivery import Inbox++_LOGGER = logging.getLogger(__name__)+_LIVENESS_SECONDS = 15.0+_BURST_SECONDS = 1.0+_RECONNECT_MAX_SECONDS = 5.0+++@dataclass(frozen=True)+class ForwarderConfig:+ """One notebook subscription and its destination inbox, including credentials."""++ url: str+ notebook: str+ identity: str+ token: str | None+ target: DeliveryTarget+++class _Bootstrap(msgspec.Struct):+ """Private stdin payload for starting a forwarder and locating its record."""++ config: ForwarderConfig+ root: str+++class _DetachedOptions(TypedDict, total=False):+ creationflags: int+ start_new_session: bool+++def detached_options() -> _DetachedOptions:+ if sys.platform == "win32":+ return {+ "creationflags": subprocess.DETACHED_PROCESS+ | subprocess.CREATE_NEW_PROCESS_GROUP+ }+ return {"start_new_session": True}+++def start_forwarder(+ config: ForwarderConfig, store: ConnectionStore+) -> Connection:+ import psutil++ assert config.target.process is not None+ process = subprocess.Popen(+ [sys.executable, "-m", "marimo._cli.pair.forwarder"],+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.DEVNULL,+ **detached_options(),+ )+ record = None+ handle = None+ try:+ handle = ProcessHandle.capture(process.pid)+ record = Connection(+ version=1,+ identity=config.identity,+ notebook=config.notebook,+ harness_kind=config.target.kind,+ harness_pid=config.target.process.pid,+ harness_start=config.target.process.started,+ forwarder_pid=handle.pid,+ forwarder_start=handle.started,+ created_at=time.time(),+ )+ store.save(record)+ assert process.stdin is not None+ assert process.stdout is not None+ output = process.stdout+ # Secrets travel through the private pipe, never argv or a state file.+ process.stdin.write(+ msgspec.json.encode(_Bootstrap(config, str(store.root)))+ )+ process.stdin.close()+ ready: queue.Queue[bytes] = queue.Queue(maxsize=1)+ threading.Thread(+ target=lambda: ready.put(output.readline()), daemon=True+ ).start()+ try:+ line = ready.get(timeout=10)+ except queue.Empty as error:+ raise PairError(+ "The agent message forwarder did not attach within 10 seconds."+ ) from error+ if line != b"attached\n" or process.poll() is not None:+ raise PairError(+ "The agent message forwarder could not attach. Check the server, token and MARIMO_ENABLE_HOST=1."+ )+ return record+ except (OSError, psutil.Error, PairError):+ if process.poll() is None:+ if handle is not None:+ handle.stop()+ else:+ # Capture can fail before there is a reusable process handle.+ kill_subprocess(process, start_new_session=True)+ if record is not None:+ store.remove(record)+ raise+ finally:+ if process.stdin is not None and not process.stdin.closed:+ process.stdin.close()+ if process.stdout is not None:+ process.stdout.close()+++def _read_stream(+ config: ForwarderConfig,+ incoming: queue.Queue[SSEEvent | Exception | None],+ stopped: threading.Event,+ responses: list[EventStream],+ cursor: str | None = None,+) -> None:+ def events() -> Iterator[SSEEvent]:+ response = open_events(+ url=config.url,+ notebook=config.notebook,+ token=config.token,+ identity=config.identity,+ cursor=cursor,+ name=config.target.label,+ )+ responses.append(response)+ try:+ if not stopped.is_set():+ yield from iter_sse(response)+ finally:+ response.close()++ pump_events(events(), incoming, stopped)+++def _wait_reconnect(inbox: Inbox, delay: float) -> bool:+ deadline = time.monotonic() + delay+ while inbox.alive():+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ return True+ time.sleep(min(remaining, 0.1))+ return False+++def run_forwarder(+ config: ForwarderConfig,+ inbox: Inbox,+ *,+ ready: Callable[[], None],+) -> None:+ files = AgentMessageFiles()+ files.cleanup()+ pending = ""+ flush_at = 0.0+ check_at = time.monotonic()+ attached = False+ attachment: str | None = None+ cursor: str | None = None+ reconnect_delay = 0.1++ def flush() -> None:+ nonlocal pending+ if pending:+ inbox.send(pending)+ pending = ""++ while inbox.alive():+ attachment = None+ incoming: queue.Queue[SSEEvent | Exception | None] = queue.Queue(+ maxsize=64+ )+ stopped = threading.Event()+ responses: list[EventStream] = []+ reader = threading.Thread(+ target=_read_stream,+ args=(config, incoming, stopped, responses, cursor),+ daemon=True,+ )+ reader.start()+ reconnect = False+ try:+ while True:+ now = time.monotonic()+ if now >= check_at:+ if not inbox.alive():+ return+ check_at = now + _LIVENESS_SECONDS+ if pending and now >= flush_at:+ flush()+ try:+ event = incoming.get(+ timeout=min(0.1, max(0.0, check_at - now))+ )+ except queue.Empty:+ continue+ if event is None:+ flush()+ if not attached:+ raise PairError(+ "The notebook stream ended before attachment was confirmed."+ )+ reconnect = True+ break+ if isinstance(event, Exception):+ flush()+ if isinstance(event, StaleNotebookError) and attached:+ return+ if not attached or not isinstance(+ event,+ (+ PairConnectionError,+ OSError,+ http.client.HTTPException,+ ),+ ):+ raise PairError(+ "The agent message stream could not continue."+ ) from event+ reconnect = True+ break+ if event.name == "reset":+ attachment = None+ elif event.name == "attachment":+ payload = json.loads(event.data)["attachment"]+ if payload.get("identity") == config.identity:+ attachment = payload["id"]+ if not attached:+ attached = True+ ready()+ elif event.name == "ready":+ if attachment is None:+ raise PairError(+ "The notebook stream did not confirm its attachment."+ )+ reconnect_delay = 0.1+ elif event.name == "attachment.removed":+ if json.loads(event.data)["id"] == attachment:+ flush()+ return+ elif event.name == "custom":+ payload = json.loads(event.data)["custom"]+ if payload["type"] != AGENT_MESSAGE_TYPE:+ if event.id is not None:+ cursor = event.id+ continue+ if not attached:+ raise PairError(+ "The notebook stream did not confirm its attachment."+ )+ message = inbox_message(+ payload["data"],+ notebook=config.notebook,+ budget=inbox.inbox_bytes,+ files=files,+ )+ combined = (+ f"{pending}\n\n{message}" if pending else message+ )+ if len(combined.encode("utf-8")) > inbox.inbox_bytes:+ flush()+ combined = message+ if not pending:+ flush_at = time.monotonic() + _BURST_SECONDS+ pending = combined+ if event.id is not None:+ cursor = event.id+ finally:+ stopped.set()+ for response in responses:+ response.close()+ reader.join(timeout=1)+ if reconnect:+ if not _wait_reconnect(inbox, reconnect_delay):+ return+ reconnect_delay = min(reconnect_delay * 2, _RECONNECT_MAX_SECONDS)+++def main() -> None:+ record = None+ store = None+ try:+ bootstrap = msgspec.json.decode(sys.stdin.read(), type=_Bootstrap)+ config = bootstrap.config+ store = ConnectionStore(root=Path(bootstrap.root))+ record = store.load(config.identity)+ if record is None or record.forwarder != ProcessHandle.capture(+ os.getpid()+ ):+ raise PairError(+ "The agent message forwarder does not own its connection."+ )+ log_path = store.root.parent / f"forwarder-{config.identity}.log"+ handler = RotatingFileHandler(+ log_path, maxBytes=64 * 1024, backupCount=1, encoding="utf-8"+ )+ os.chmod(log_path, 0o600)+ _LOGGER.addHandler(handler)+ _LOGGER.setLevel(logging.INFO)++ def ready() -> None:+ sys.stdout.write("attached\n")+ sys.stdout.flush()++ inbox = harness_for(config.target.kind).open_inbox(config.target)+ run_forwarder(config, inbox, ready=ready)+ except (PairError, OSError, ValueError, KeyError, TypeError) as error:+ try:+ sys.stdout.write("failed\n")+ sys.stdout.flush()+ except OSError:+ pass+ # Native command output can contain tokens or agent message content.+ _LOGGER.error(+ "%s",+ str(error)+ if isinstance(error, PairError)+ else "The agent message forwarder stopped after a malformed stream or I/O error.",+ )+ finally:+ if record is not None and store is not None:+ with store.locked(record.identity):+ store.remove(record)+++if __name__ == "__main__":+ main()diff --git a/marimo/_cli/pair/harnesses/__init__.py b/marimo/_cli/pair/harnesses/__init__.pynew file mode 100644index 0000000000..a740481504--- /dev/null+++ b/marimo/_cli/pair/harnesses/__init__.py@@ -0,0 +1,83 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++from typing import TYPE_CHECKING++from marimo._cli.pair.client import PairInputError+from marimo._cli.pair.delivery import ProcessHandle+from marimo._cli.pair.harnesses.claude import ClaudeHarness+from marimo._cli.pair.harnesses.codex import CodexHarness+from marimo._cli.pair.harnesses.opencode import OpenCodeHarness++if TYPE_CHECKING:+ from collections.abc import Mapping++ from marimo._cli.pair.delivery import DeliveryTarget, Harness+++def registered_harnesses() -> list[Harness]:+ return [CodexHarness(), ClaudeHarness(), OpenCodeHarness()]+++def environment_identity(+ env: Mapping[str, str], kind: str | None = None+) -> tuple[str, str | None]:+ candidates = [harness_for(kind)] if kind else registered_harnesses()+ found = [+ (candidate.kind, identity)+ for candidate in candidates+ if (identity := candidate.identity(env)) is not None+ ]+ if len(found) > 1:+ raise PairInputError(+ "Nested harnesses detected. Pass --harness <kind>."+ )+ if kind and not found:+ raise PairInputError(+ f"No {kind} conversation detected. Run detach inside that harness."+ )+ return found[0] if found else ("unknown", None)+++def harness_for(kind: str) -> Harness:+ for candidate in registered_harnesses():+ if candidate.kind == kind:+ return candidate+ raise PairInputError(f"Unsupported harness: {kind}.")+++def detect_target(+ env: Mapping[str, str], harness: str | None, pid: int | None = None+) -> tuple[Harness, DeliveryTarget]:+ process = None+ if pid is not None:+ import psutil++ if pid <= 0:+ raise PairInputError("--pid must be a positive process ID.")+ try:+ process = ProcessHandle.capture(pid)+ if not process.alive():+ raise PairInputError(+ "The process selected by --pid is not running."+ )+ except psutil.Error as error:+ raise PairInputError(+ "Could not inspect the process selected by --pid."+ ) from error+ found = []+ for candidate in registered_harnesses():+ if harness is not None and candidate.kind != harness:+ continue+ target = candidate.detect(env, process=process)+ if target is not None:+ found.append((candidate, target))+ if len(found) > 1:+ raise PairInputError(+ "Nested harnesses detected. Pass --harness <kind>."+ )+ if not found:+ raise PairInputError(+ "No supported inbox detected. Run connect inside Codex, Claude Code, or OpenCode."+ )+ return found[0]diff --git a/marimo/_cli/pair/harnesses/claude.py b/marimo/_cli/pair/harnesses/claude.pynew file mode 100644index 0000000000..1af06a0cab--- /dev/null+++ b/marimo/_cli/pair/harnesses/claude.py@@ -0,0 +1,151 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import json+import os+import socket+import stat+from dataclasses import dataclass+from pathlib import Path+from typing import TYPE_CHECKING, ClassVar++from marimo._cli.pair.client import PairError, PairInputError+from marimo._cli.pair.delivery import DeliveryTarget, ProcessHandle++if TYPE_CHECKING:+ from collections.abc import Mapping+++def _socket_exists(address: str) -> bool:+ try:+ info = Path(address).lstat()+ return stat.S_ISSOCK(info.st_mode) and info.st_uid == os.getuid()+ except OSError:+ return False+++class ClaudeHarness:+ """Discover a Claude Code session's native inbox and process owner."""++ kind = "claude"++ def identity(self, env: Mapping[str, str]) -> str | None:+ address = env.get("CLAUDE_CODE_MESSAGING_SOCKET")+ if address:+ return address+ if any(+ key in env+ for key in (+ "CLAUDE_PID",+ "CLAUDE_CODE_MESSAGING_SOCKET",+ "CLAUDE_CODE_MESSAGING_TOKEN",+ )+ ):+ raise PairInputError(+ "Claude Code did not export its inbox socket. "+ "Run this command inside a current Claude Code session."+ )+ return None++ def detect(+ self,+ env: Mapping[str, str],+ *,+ process: ProcessHandle | None = None,+ ) -> DeliveryTarget | None:+ import psutil++ address = self.identity(env)+ if address is None:+ return None+ self.check()+ if not _socket_exists(address):+ raise PairInputError(+ "The Claude Code inbox socket is unavailable."+ )+ token = env.get("CLAUDE_CODE_MESSAGING_TOKEN")+ if not token:+ raise PairInputError(+ "Claude Code did not export its inbox token. "+ "Run connect inside a current Claude Code session."+ )+ if process is not None:+ return DeliveryTarget(+ self.kind,+ address,+ "Claude Code",+ process=process,+ auth_token=token,+ )+ try:+ owner_pid = int(env.get("CLAUDE_PID", ""))+ if owner_pid <= 0:+ raise ValueError+ except ValueError as error:+ raise PairInputError(+ "Claude Code did not export a valid CLAUDE_PID. "+ "Run connect inside a current Claude Code session."+ ) from error+ try:+ for ancestor in psutil.Process().parents():+ if ancestor.pid == owner_pid:+ return DeliveryTarget(+ self.kind,+ address,+ "Claude Code",+ process=ProcessHandle.capture(ancestor.pid),+ auth_token=token,+ )+ except psutil.Error as error:+ raise PairInputError(+ "Could not identify the Claude Code process."+ ) from error+ raise PairInputError(+ "Run connect inside a native Claude Code session."+ )++ def check(self) -> None:+ if os.name == "nt" or not hasattr(socket, "AF_UNIX"):+ raise PairInputError(+ "Claude Code inbox delivery requires macOS or Linux."+ )++ def open_inbox(self, target: DeliveryTarget) -> ClaudeInbox:+ return ClaudeInbox(target)+++@dataclass(frozen=True)+class ClaudeInbox:+ """Send messages to one Claude socket while its owner and socket exist."""++ target: DeliveryTarget+ inbox_bytes: ClassVar[int] = 64 * 1024++ def send(self, text: str) -> None:+ if not self.target.auth_token:+ raise PairError("The Claude Code inbox token is unavailable.")+ # The socket and auth line are documented; the user frame is private.+ # Keep this encoding covered by a native Claude acceptance test.+ frames = [+ {"type": "auth", "token": self.target.auth_token},+ {"type": "user", "message": {"role": "user", "content": text}},+ ]+ data = "".join(json.dumps(frame) + "\n" for frame in frames).encode()+ try:+ with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as inbox:+ inbox.settimeout(5)+ inbox.connect(self.target.address)+ inbox.sendall(data)+ inbox.shutdown(socket.SHUT_WR)+ except (OSError, ValueError) as error:+ raise PairError(+ "Could not deliver the message to Claude Code. "+ "Check that its inbox is available and inbound messages are allowed."+ ) from error++ def alive(self) -> bool:+ return (+ self.target.process is not None+ and self.target.process.alive()+ and _socket_exists(self.target.address)+ )diff --git a/marimo/_cli/pair/harnesses/codex.py b/marimo/_cli/pair/harnesses/codex.pynew file mode 100644index 0000000000..98ab22aeb7--- /dev/null+++ b/marimo/_cli/pair/harnesses/codex.py@@ -0,0 +1,149 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import json+import subprocess+from dataclasses import dataclass+from pathlib import Path+from typing import TYPE_CHECKING, ClassVar++from marimo._cli.pair.client import PairError, PairInputError+from marimo._cli.pair.delivery import DeliveryTarget, ProcessHandle+from marimo._utils.platform import is_windows++if TYPE_CHECKING:+ from collections.abc import Mapping+++class CodexHarness:+ """Discover Codex conversations and check shared-daemon support."""++ kind = "codex"++ @staticmethod+ def executable() -> str:+ # Batch shims can interpret message text as shell syntax on Windows.+ return "codex.exe" if is_windows() else "codex"++ def detect(+ self,+ env: Mapping[str, str],+ *,+ process: ProcessHandle | None = None,+ ) -> DeliveryTarget | None:+ import psutil++ address = self.identity(env)+ if not address:+ return None+ if process is not None:+ self.check()+ return DeliveryTarget(self.kind, address, "Codex", process=process)+ owner = None+ try:+ for ancestor in psutil.Process().parents():+ if Path(ancestor.name()).stem.lower().startswith("codex"):+ arguments = ancestor.cmdline()+ if "--no-daemon" in arguments or any(+ argument.endswith("stdio://") for argument in arguments+ ):+ raise PairInputError(+ "This Codex session does not use the shared daemon. "+ "Run connect inside a native Codex daemon session."+ )+ owner = ProcessHandle.capture(ancestor.pid)+ break+ except psutil.Error as error:+ raise PairInputError(+ "Could not identify the Codex process."+ ) from error+ if owner is None:+ raise PairInputError("Run connect inside a native Codex session.")+ self.check()+ return DeliveryTarget(self.kind, address, "Codex", process=owner)++ def identity(self, env: Mapping[str, str]) -> str | None:+ address = env.get("CODEX_SESSION_ID") or env.get("CODEX_THREAD_ID")+ if not address:+ if "CODEX_SESSION_ID" in env or "CODEX_THREAD_ID" in env:+ raise PairInputError(+ "Codex did not export a conversation ID. "+ "Run this command inside a native Codex session."+ )+ return None+ return address++ def check(self) -> None:+ try:+ result = subprocess.run(+ [self.executable(), "app-server", "daemon", "version"],+ capture_output=True,+ timeout=5,+ check=False,+ )+ info = json.loads(result.stdout)+ running = (+ isinstance(info, dict) and info.get("status") == "running"+ )+ if result.returncode == 0 and running:+ queue_help = subprocess.run(+ [self.executable(), "queue", "--help"],+ capture_output=True,+ timeout=5,+ check=False,+ )+ if queue_help.returncode != 0:+ raise PairInputError(+ "Install a Codex CLI with queue support."+ )+ except (OSError, subprocess.TimeoutExpired, ValueError) as error:+ raise PairInputError(+ "Could not check the Codex daemon. "+ "Install a Codex CLI with queue support."+ ) from error+ if result.returncode != 0 or not running:+ raise PairInputError(+ "The Codex daemon is not running. "+ "Run codex app-server daemon start, then reconnect."+ )++ def open_inbox(self, target: DeliveryTarget) -> CodexInbox:+ return CodexInbox(target, self.executable())+++@dataclass(frozen=True)+class CodexInbox:+ """Queue messages for one Codex conversation while its owner is alive."""++ target: DeliveryTarget+ executable: str+ # Leave room for the executable and options within Windows command limits.+ inbox_bytes: ClassVar[int] = 8 * 1024++ def send(self, text: str) -> None:+ try:+ result = subprocess.run(+ [+ self.executable,+ "queue",+ "--thread",+ self.target.address,+ "--message",+ text,+ ],+ capture_output=True,+ timeout=15,+ check=False,+ )+ except (OSError, ValueError, subprocess.TimeoutExpired) as error:+ raise PairError(+ "Could not deliver the message to Codex."+ ) from error+ if result.returncode != 0:+ raise PairError(+ "Codex rejected the message. Check that the conversation "+ "uses the shared daemon and supports codex queue."+ )++ def alive(self) -> bool:+ return self.target.process is not None and self.target.process.alive()diff --git a/marimo/_cli/pair/harnesses/opencode.py b/marimo/_cli/pair/harnesses/opencode.pynew file mode 100644index 0000000000..33358ac90f--- /dev/null+++ b/marimo/_cli/pair/harnesses/opencode.py@@ -0,0 +1,239 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import base64+import http.client+import os+import stat+from dataclasses import dataclass, field+from pathlib import Path+from typing import TYPE_CHECKING, ClassVar, TypeVar+from urllib.parse import quote, urlencode, urlsplit++import msgspec++from marimo._cli.pair.client import PairError, PairInputError+from marimo._cli.pair.delivery import DeliveryTarget, ProcessHandle++if TYPE_CHECKING:+ from collections.abc import Mapping++T = TypeVar("T")+_SETUP = (+ "OpenCode agent messages require OpenCode 2.x. "+ "Run connect in a native OpenCode 2.x shell with a registered local service."+)+++def _request(+ url: str,+ authorization: str | None,+ result_type: type[T],+ *,+ text: str | None = None,+) -> T:+ try:+ endpoint = urlsplit(url)+ port = endpoint.port+ except ValueError as error:+ raise PairInputError("The OpenCode inbox URL is invalid.") from error+ if (+ endpoint.scheme != "http"+ or endpoint.hostname not in {"127.0.0.1", "localhost", "::1"}+ or endpoint.username is not None+ or endpoint.password is not None+ or endpoint.fragment+ ):+ raise PairInputError(+ "OpenCode delivery requires a local HTTP endpoint."+ )+ connection = http.client.HTTPConnection(+ endpoint.hostname, port, timeout=10+ )+ headers = {"Content-Type": "application/json"}+ if authorization:+ headers["Authorization"] = authorization+ try:+ body = (+ None+ if text is None+ else msgspec.json.encode({"text": text, "delivery": "queue"})+ )+ path = endpoint.path + ("?" + endpoint.query if endpoint.query else "")+ connection.request(+ "GET" if text is None else "POST", path, body, headers+ )+ response = connection.getresponse()+ if response.status != 200:+ raise PairError(+ "OpenCode rejected the inbox request. Check the session and credentials."+ )+ data = response.read(1024 * 1024 + 1)+ if len(data) > 1024 * 1024:+ raise PairError("OpenCode returned an oversized inbox response.")+ return msgspec.json.decode(data, type=result_type)+ except (+ OSError,+ http.client.HTTPException,+ ValueError,+ msgspec.DecodeError,+ ) as error:+ raise PairError("Could not reach the OpenCode inbox.") from error+ finally:+ connection.close()+++@dataclass(frozen=True)+class _Service:+ url: str+ pid: int+ version: str+ password: str | None = field(default=None, repr=False)+++class _Info(msgspec.Struct):+ pid: int+ version: str+++class _Metadata(msgspec.Struct):+ sessionID: str | None = None+++class _Shell(msgspec.Struct):+ metadata: _Metadata+ pid: int | None = None+++class _Shells(msgspec.Struct):+ data: list[_Shell]+++class _Session(msgspec.Struct):+ id: str+++class _SessionResponse(msgspec.Struct):+ data: _Session+++class OpenCodeHarness:+ """Verify an OpenCode 2.x session from native identity or its shell PID."""++ kind = "opencode"++ def identity(self, env: Mapping[str, str]) -> str | None:+ target = self.detect(env)+ return target.address if target else None++ def detect(+ self, env: Mapping[str, str], *, process: ProcessHandle | None = None+ ) -> DeliveryTarget | None:+ import psutil++ if env.get("OPENCODE_TERMINAL") != "1":+ if env.get("OPENCODE"):+ raise PairInputError(_SETUP)+ return None+ self.check()+ state = Path(+ env.get("XDG_STATE_HOME") or Path.home() / ".local" / "state"+ )+ path = state / "opencode" / "service.json"+ try:+ info = path.lstat()+ if (+ not stat.S_ISREG(info.st_mode)+ or info.st_uid != os.getuid()+ or info.st_mode & 0o077+ ):+ raise ValueError+ service = msgspec.json.decode(path.read_bytes(), type=_Service)+ if not service.version.startswith("2.") or service.pid <= 0:+ raise ValueError+ owner = ProcessHandle.capture(service.pid)+ except (+ OSError,+ ValueError,+ msgspec.DecodeError,+ psutil.Error,+ ) as error:+ raise PairInputError(+ "No valid private OpenCode v2 service record. " + _SETUP+ ) from error+ base = service.url.rstrip("/")+ authorization = None+ if service.password is not None:+ authorization = (+ "Basic "+ + base64.b64encode(+ ("opencode:" + service.password).encode()+ ).decode()+ )+ remote = _request(base + "/api/info", authorization, _Info)+ if remote.pid != service.pid or remote.version != service.version:+ raise PairInputError(+ "The OpenCode service record does not match the running service."+ )+ query = "?" + urlencode({"location[directory]": os.getcwd()})+ session = env.get("OPENCODE_SESSION_ID")+ if not session:+ shells = _request(+ base + "/api/shell" + query, authorization, _Shells+ )+ try:+ ancestors = {+ os.getpid(),+ *(parent.pid for parent in psutil.Process().parents()),+ }+ except psutil.Error as error:+ raise PairInputError(+ "Could not inspect the OpenCode shell process."+ ) from error+ sessions = {+ shell.metadata.sessionID+ for shell in shells.data+ if shell.pid in ancestors and shell.metadata.sessionID+ }+ if len(sessions) != 1:+ raise PairInputError(+ "Could not identify one OpenCode conversation from the current shell PID. "+ + _SETUP+ )+ session = sessions.pop()+ if not owner.alive():+ raise PairInputError("The OpenCode inbox owner is not running.")+ address = base + "/api/session/" + quote(session, safe="")+ current = _request(address + query, authorization, _SessionResponse)+ if current.data.id != session:+ raise PairInputError("OpenCode returned a different conversation.")+ return DeliveryTarget(+ self.kind,+ address + "/prompt" + query,+ "OpenCode",+ process or owner,+ authorization,+ )++ def check(self) -> None:+ if os.name == "nt":+ raise PairInputError(+ "OpenCode inbox discovery requires macOS or Linux."+ )++ def open_inbox(self, target: DeliveryTarget) -> OpenCodeInbox:+ return OpenCodeInbox(target)+++@dataclass(frozen=True)+class OpenCodeInbox:+ """Queue messages in one verified OpenCode conversation without starting a service."""++ target: DeliveryTarget+ inbox_bytes: ClassVar[int] = 64 * 1024++ def send(self, text: str) -> None:+ _request(self.target.address, self.target.auth_token, dict, text=text)++ def alive(self) -> bool:+ return self.target.process is not None and self.target.process.alive()diff --git a/marimo/_cli/pair/prompt.json b/marimo/_cli/pair/prompt.jsonindex 15f445719d..ed9df2f69f 100644--- a/marimo/_cli/pair/prompt.json+++ b/marimo/_cli/pair/prompt.json@@ -1,6 +1,7 @@{- "prompt": "Pair with me on this running marimo notebook.\n\nURL: {url}\n{session}\nRun `{command} pair --help` first.\nUse `{command}` for all marimo commands.\n\nOnce connected, send a fun toast using `mo.status.toast(...)` (`import marimo as mo`).{authentication}",- "session": "Session: {session}\n",- "token_file": "\n\nFor authenticated Pair commands, pass `--token-file {token_file}`.",- "token": "\n\nFor authenticated Pair commands, set `export MARIMO_TOKEN={token}` in the shell that runs marimo."+ "prompt": "Pair with me on this running marimo notebook.\n\nURL: {url}\n{notebook}{session}\nRun `{command} pair --help` first.\nUse `{command}` for all marimo commands.{authentication}",+ "notebook": "Notebook: {notebook}\n",+ "token_file": "\n\nFor authenticated notebook discovery, pass `--token-file {token_file}`.",+ "token": "\n\nFor authenticated notebook discovery, set `export MARIMO_TOKEN={token}` in the shell that runs marimo.",+ "session": "Session: {session}\n"}diff --git a/marimo/_cli/pair/prompts.py b/marimo/_cli/pair/prompts.pyindex 34640929d1..4964444a4e 100644--- a/marimo/_cli/pair/prompts.py+++ b/marimo/_cli/pair/prompts.py@@ -16,6 +16,7 @@ def get_pair_command() -> str:@dataclass(frozen=True)class PromptTemplates:prompt: str+ notebook: strsession: strtoken_file: strtoken: str@@ -31,6 +32,7 @@ def load_prompt_templates() -> PromptTemplates:def render_prompt(*,url: str,+ notebook_id: str | None = None,session_id: str | None = None,token_file: Path | None = None,) -> str:@@ -38,9 +40,14 @@ def render_prompt(return templates.prompt.format(command=get_pair_command(),url=url,- session=(- templates.session.format(session=session_id) if session_id else ""+ notebook=(+ templates.notebook.format(notebook=notebook_id)+ if notebook_id+ else ""),+ session=templates.session.format(session=session_id)+ if session_id and not notebook_id+ else "",authentication=(templates.token_file.format(token_file=shlex.quote(str(token_file))diff --git a/marimo/_environments/script_metadata.py b/marimo/_environments/script_metadata.pyindex c5f32a5196..007b800a22 100644--- a/marimo/_environments/script_metadata.py+++ b/marimo/_environments/script_metadata.py@@ -18,16 +18,12 @@ from __future__ import annotationsimport asyncioimport contextlib-import errnoimport hashlibimport osimport platformimport re-import statimport subprocess-import sysimport tempfile-import timefrom dataclasses import dataclassfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any@@ -44,6 +40,7 @@ from marimo._environments.uv import (uv_async,uv_stream,)+from marimo._utils.file_lock import file_lock as _file_lockfrom marimo._utils.toml import toml_readerfrom marimo._utils.xdg import marimo_state_dir@@ -501,53 +498,6 @@ def _stable_carrier_lock(yield-def _file_lock(target: Path, *, blocking: bool) -> Iterator[None]:- """Hold an OS lock on a persistent file.-- The lock file stays in place: unlinking it would let a new caller lock- a different inode while existing callers still wait on the old one.- Process exit releases the lock, including after a crash.- """- # Never truncate or follow a pre-existing link, even for the lock file.- if target.is_symlink():- raise OSError(f"Refusing to use symlink as lock file: {target}")- descriptor = os.open(- target, os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0), 0o600- )- with os.fdopen(descriptor, "r+b", buffering=0) as lock:- if not stat.S_ISREG(os.fstat(lock.fileno()).st_mode):- raise OSError(f"Lock file is not a regular file: {target}")- if sys.platform == "win32":- import msvcrt-- while True:- try:- msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1)- break- except OSError as error:- if error.errno not in (errno.EACCES, errno.EDEADLK):- raise- if not blocking:- raise BlockingIOError from error- time.sleep(0.05)- try:- yield- finally:- msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1)- else:- import fcntl-- fcntl.flock(- lock.fileno(),- fcntl.LOCK_EX | (0 if blocking else fcntl.LOCK_NB),- )- try:- yield- finally:- fcntl.flock(lock.fileno(), fcntl.LOCK_UN)--@contextlib.contextmanagerdef _carrier(notebook: str, content: str, *, stable: bool = Falsediff --git a/marimo/_server/api/deps.py b/marimo/_server/api/deps.pyindex 90d57e1f52..80ea31d44d 100644--- a/marimo/_server/api/deps.py+++ b/marimo/_server/api/deps.py@@ -6,12 +6,12 @@ from typing import TYPE_CHECKING, Any, castfrom marimo import _loggers as loggersfrom marimo._cli.tips import CliTipfrom marimo._config.manager import MarimoConfigManager, ScriptConfigReader+from marimo._config.settings import GLOBAL_SETTINGSfrom marimo._server.config import StarletteServerStatefrom marimo._server.session_manager import SessionManagerfrom marimo._server.tokens import SkewProtectionTokenfrom marimo._session.model import SessionModefrom marimo._types.ids import SessionId, StableSessionId-from marimo._utils.env import pair_preview_enabledfrom marimo._utils.http import HTTPException, HTTPStatusif TYPE_CHECKING:@@ -64,15 +64,6 @@ class AppStateBase: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)- )-@propertydef mode(self) -> SessionMode:return self.session_manager.mode@@ -214,9 +205,9 @@ 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():+ def require_host(self) -> None:+ """Reject agent-aware routes when host support is disabled."""+ if not GLOBAL_SETTINGS.ENABLE_HOST:raise HTTPException(status_code=HTTPStatus.NOT_FOUND)def session_by_stable_id(self, stable_id: str) -> Session:diff --git a/marimo/_server/api/endpoints/pair.py b/marimo/_server/api/endpoints/pair.pyindex 90563f0cd6..6a19437653 100644--- a/marimo/_server/api/endpoints/pair.py+++ b/marimo/_server/api/endpoints/pair.py@@ -23,7 +23,7 @@ pair_router = APIRouter()async def messages(request: Request) -> Response:"""Send any JSON content to all agents attached to the notebook."""state = AppState(request)- state.require_pair_preview()+ state.require_host()session = state.session_by_stable_id(request.path_params["id"])try:payload = msgspec.json.decode(await request.body())@@ -43,6 +43,8 @@ async def messages(request: Request) -> Response:class DetachRequest(msgspec.Struct):+ """Select a host attachment to remove without stopping its notebook runtime."""+attachment_id: str@@ -53,7 +55,7 @@ class DetachRequest(msgspec.Struct):async def detach(request: Request) -> Response:"""Disconnect one attachment without stopping its notebook runtime."""state = AppState(request)- state.require_pair_preview()+ state.require_host()session = state.session_by_stable_id(request.path_params["id"])try:body = msgspec.json.decode(await request.body(), type=DetachRequest)diff --git a/marimo/_server/host/__init__.py b/marimo/_server/host/__init__.pyindex 54df84d09b..8754d3e7dc 100644--- a/marimo/_server/host/__init__.py+++ b/marimo/_server/host/__init__.py@@ -17,3 +17,7 @@ OPERATIONS = ["runtime.run",]"""Supported operations advertised in the `host` object."""++ATTACHMENT_IDENTITY = "Marimo-Attachment-Identity"+ATTACHMENT_KIND = "Marimo-Attachment-Kind"+ATTACHMENT_NAME = "Marimo-Attachment-Name"diff --git a/marimo/_server/host/api.py b/marimo/_server/host/api.pyindex 7ecdeef58e..2674ca4e83 100644--- a/marimo/_server/host/api.py+++ b/marimo/_server/host/api.py@@ -39,7 +39,12 @@ from marimo._server.api.endpoints.ws.ws_connection_validator import ()from marimo._server.api.endpoints.ws_endpoint import DOC_MANAGERfrom marimo._server.api.utils import format_url_host, open_url_in_browser-from marimo._server.host import HOST_API_PATH+from marimo._server.host import (+ ATTACHMENT_IDENTITY,+ ATTACHMENT_KIND,+ ATTACHMENT_NAME,+ HOST_API_PATH,+)from marimo._server.host.context import CachedMutationfrom marimo._server.host.events import serialize_eventfrom marimo._server.host.websocket import EditorEventSocket@@ -65,9 +70,6 @@ _Body = TypeVar("_Body", bound=msgspec.Struct)PROBLEM_TYPE_PREFIX = "tag:marimo.io,2026:host/""""Prefix for host protocol problem types."""-ATTACHMENT_IDENTITY = "Marimo-Attachment-Identity"-ATTACHMENT_KIND = "Marimo-Attachment-Kind"-ATTACHMENT_NAME = "Marimo-Attachment-Name"_ATTACHMENT_HEADERS = {"identity": ATTACHMENT_IDENTITY,diff --git a/marimo/_templates.py b/marimo/_templates.pyindex f4c7dc41bd..75d232487a 100644--- a/marimo/_templates.py+++ b/marimo/_templates.py@@ -14,6 +14,7 @@ from typing import TYPE_CHECKING, Any, Literal, castfrom marimo._ast.app_config import _AppConfigfrom marimo._cli.pair.prompts import get_pair_command, load_prompt_templatesfrom marimo._config.config import MarimoConfig, PartialMarimoConfig+from marimo._config.settings import GLOBAL_SETTINGSfrom marimo._convert.common.filename import parse_titlefrom marimo._convert.converters import MarimoConvertfrom marimo._messaging.notification import ModelLifecycleNotification@@ -23,7 +24,6 @@ from marimo._schemas.session import NotebookSessionV1from marimo._server.tokens import SkewProtectionTokenfrom marimo._session.model import SessionModefrom marimo._session.notebook import read_css_file, read_html_head_file-from marimo._utils.env import pair_preview_enabledfrom marimo._utils.versions import is_editablefrom marimo._version import __version__@@ -139,14 +139,13 @@ def _get_mount_config("runtime_config": runtime_config,}- pair_preview = ""- if pair_preview_enabled():- pair_preview = ',\n "pairPreview": ' + json_script(- {- "command": get_pair_command(),- "templates": asdict(load_prompt_templates()),- }- )+ pair_config = json_script(+ {+ "command": get_pair_command(),+ "templates": asdict(load_prompt_templates()),+ "hostEnabled": GLOBAL_SETTINGS.ENABLE_HOST and mode == "edit",+ }+ )return """{{"filename": {filename},@@ -162,11 +161,12 @@ def _get_mount_config("view": {view},"notebook": {notebook},"session": {session},- "runtimeConfig": {runtime_config}{pair_preview}+ "runtimeConfig": {runtime_config},+ "pairConfig": {pair_config}}}""".format(**{k: json_script(v) for k, v in options.items()},- pair_preview=pair_preview,+ pair_config=pair_config,).strip()diff --git a/marimo/_utils/env.py b/marimo/_utils/env.pyindex 29d6571ebc..8ba8316c7a 100644--- a/marimo/_utils/env.py+++ b/marimo/_utils/env.py@@ -3,13 +3,6 @@ from __future__ import annotationsimport 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/marimo/_utils/file_lock.py b/marimo/_utils/file_lock.pynew file mode 100644index 0000000000..33709500d2--- /dev/null+++ b/marimo/_utils/file_lock.py@@ -0,0 +1,61 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import errno+import os+import stat+import sys+import time+from contextlib import contextmanager+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from collections.abc import Iterator+ from pathlib import Path+++@contextmanager+def file_lock(target: Path, *, blocking: bool) -> Iterator[None]:+ """Hold an OS lock on a persistent file.++ The lock file stays in place: unlinking it would let a new caller lock+ a different inode while existing callers still wait on the old one.+ Process exit releases the lock, including after a crash.+ """+ # Never truncate or follow a pre-existing link, even for the lock file.+ if target.is_symlink():+ raise OSError(f"Refusing to use symlink as lock file: {target}")+ descriptor = os.open(+ target, os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0), 0o600+ )+ with os.fdopen(descriptor, "r+b", buffering=0) as lock:+ if not stat.S_ISREG(os.fstat(lock.fileno()).st_mode):+ raise OSError(f"Lock file is not a regular file: {target}")+ if sys.platform == "win32":+ import msvcrt++ while True:+ try:+ msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1)+ break+ except OSError as error:+ if error.errno not in (errno.EACCES, errno.EDEADLK):+ raise+ if not blocking:+ raise BlockingIOError from error+ time.sleep(0.05)+ try:+ yield+ finally:+ msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1)+ else:+ import fcntl++ fcntl.flock(+ lock.fileno(),+ fcntl.LOCK_EX | (0 if blocking else fcntl.LOCK_NB),+ )+ try:+ yield+ finally:+ fcntl.flock(lock.fileno(), fcntl.LOCK_UN)diff --git a/tests/_cli/_pair_replay.py b/tests/_cli/_pair_replay.pynew file mode 100644index 0000000000..f42f9d9c22--- /dev/null+++ b/tests/_cli/_pair_replay.py@@ -0,0 +1,89 @@+# Copyright 2026 Marimo. All rights reserved.+"""Subprocess driver for a controlled interruption of a real host stream."""++from __future__ import annotations++import json+import socket+import sys+import threading+import time+from pathlib import Path+from typing import TYPE_CHECKING+from unittest.mock import patch++import msgspec++from marimo._cli.pair import forwarder+from marimo._cli.pair.client import EventStream, open_events+from marimo._cli.pair.forwarder import ForwarderConfig++if TYPE_CHECKING:+ from marimo._cli.pair.delivery import ProcessHandle+++class RecordingInbox:+ inbox_bytes = 8192++ def __init__(self, directory: Path, owner: ProcessHandle | None) -> None:+ self.directory = directory+ self.owner = owner++ def alive(self) -> bool:+ return self.owner is not None and self.owner.alive()++ def send(self, text: str) -> None:+ with (self.directory / "inbox.jsonl").open("a") as output:+ output.write(json.dumps({"message": text}) + "\n")+++def main() -> None:+ directory = Path(sys.argv[1])+ config = msgspec.json.decode(sys.stdin.read(), type=ForwarderConfig)+ calls = 0++ def controlled_events(+ *,+ url: str,+ notebook: str,+ token: str | None,+ identity: str,+ name: str,+ cursor: str | None = None,+ ) -> EventStream:+ nonlocal calls+ calls += 1+ if calls == 2:+ (directory / "reconnecting.json").write_text(+ json.dumps({"cursor": cursor})+ )+ while not (directory / "resume").exists():+ time.sleep(0.01)+ response = open_events(+ url=url,+ notebook=notebook,+ token=token,+ identity=identity,+ name=name,+ cursor=cursor,+ )+ if calls == 1:++ def drop() -> None:+ while not (directory / "drop").exists():+ time.sleep(0.01)+ response.socket.shutdown(socket.SHUT_RDWR)++ threading.Thread(target=drop, daemon=True).start()+ return response++ with patch.object(forwarder, "open_events", side_effect=controlled_events):+ forwarder.run_forwarder(+ config,+ RecordingInbox(directory, config.target.process),+ ready=lambda: print("attached", flush=True),+ )+++if __name__ == "__main__":+ main()diff --git a/tests/_cli/_pair_server.py b/tests/_cli/_pair_server.pyindex ae1b46b3bc..f8b61c95ae 100644--- a/tests/_cli/_pair_server.py+++ b/tests/_cli/_pair_server.py@@ -2,6 +2,7 @@from __future__ import annotationsimport json+import osimport socketimport subprocessimport sys@@ -26,9 +27,17 @@ class PairTestServer:url: strsession_id: strstable_session_id: str+ notebook_id: str | None_process: subprocess.Popen[bytes]_websocket: ClientConnection_stderr_path: Path+ _token: str | None = None++ @property+ def _headers(self) -> dict[str, str]:+ return (+ {"Authorization": f"Bearer {self._token}"} if self._token else {}+ )def wait_for_kernel(self,@@ -45,7 +54,10 @@ class PairTestServer:)request = urllib.request.Request(f"{self.url}/api/kernel/status",- headers={"Marimo-Session-Id": self.session_id},+ headers={+ **self._headers,+ "Marimo-Session-Id": self.session_id,+ },)try:with urllib.request.urlopen(request, timeout=1) as response:@@ -66,6 +78,7 @@ class PairTestServer:method="POST",data=b"{}",headers={+ **self._headers,"Content-Type": "application/json","Marimo-Session-Id": self.session_id,},@@ -101,6 +114,7 @@ def _wait_for_server(stderr_path: Path,*,timeout: float = 15.0,+ token: str | None = None,) -> None:deadline = time.monotonic() + timeoutwhile time.monotonic() < deadline:@@ -110,7 +124,11 @@ def _wait_for_server(f"{_tail(stderr_path)}")try:- with urllib.request.urlopen(url, timeout=1):+ request = urllib.request.Request(+ url,+ headers={"Authorization": f"Bearer {token}"} if token else {},+ )+ with urllib.request.urlopen(request, timeout=1):returnexcept OSError:time.sleep(0.05)@@ -147,7 +165,12 @@ def _stop_process(process: subprocess.Popen[bytes]) -> None:def _start_server(- notebook: Path, stderr_path: Path, *, attempts: int = 3+ notebook: Path,+ stderr_path: Path,+ *,+ host_enabled: bool,+ token: str | None,+ attempts: int = 3,) -> tuple[subprocess.Popen[bytes], str]:for attempt in range(attempts):port = _free_port()@@ -160,17 +183,26 @@ def _start_server("edit",str(notebook),"--headless",- "--no-token",+ *(+ ["--token-password", token]+ if token+ else ["--no-token"]+ ),"--no-skew-protection","--port",str(port),],stdout=subprocess.DEVNULL,stderr=stderr_file,+ cwd=notebook.parent,+ env={+ **os.environ,+ "MARIMO_ENABLE_HOST": "1" if host_enabled else "0",+ },)url = f"http://127.0.0.1:{port}"try:- _wait_for_server(url, process, stderr_path)+ _wait_for_server(url, process, stderr_path, token=token)except RuntimeError:_stop_process(process)if attempt + 1 == attempts:@@ -181,31 +213,42 @@ def _start_server(@contextmanager-def pair_test_server(tmp_path: Path) -> Generator[PairTestServer, None, None]:+def pair_test_server(+ tmp_path: Path, *, host_enabled: bool = True, token: str | None = None+) -> Generator[PairTestServer, None, None]:notebook = tmp_path / "pair-integration.py"notebook.write_text("import marimo\napp = marimo.App()\n")stderr_path = tmp_path / "marimo-stderr.log"- process, url = _start_server(notebook, stderr_path)+ process, url = _start_server(+ notebook, stderr_path, host_enabled=host_enabled, token=token+ )try:session_id = f"pair_{uuid.uuid4().hex[:8]}"websocket = websockets.sync.client.connect(f"{url.replace('http://', 'ws://', 1)}/ws?session_id={session_id}",open_timeout=5,+ additional_headers={"Authorization": f"Bearer {token}"}+ if token+ else {},)_wait_for_kernel_ready(websocket)- with urllib.request.urlopen(- f"{url}/api/sessions", timeout=5- ) as response:+ request = urllib.request.Request(+ f"{url}/api/sessions",+ headers={"Authorization": f"Bearer {token}"} if token else {},+ )+ with urllib.request.urlopen(request, timeout=5) as response:sessions = json.load(response)stable_session_id = sessions[session_id]["session_id"]server = PairTestServer(url=url,session_id=session_id,stable_session_id=stable_session_id,+ notebook_id=sessions[session_id].get("notebook_id"),_process=process,_websocket=websocket,_stderr_path=stderr_path,+ _token=token,)try:yield serverdiff --git a/tests/_cli/fixtures/pair/execute-failure.sse b/tests/_cli/fixtures/pair/execute-failure.ssedeleted file mode 100644index 60e96bb352..0000000000--- a/tests/_cli/fixtures/pair/execute-failure.sse+++ /dev/null@@ -1,6 +0,0 @@-event: stderr-data: {"data":"ValueError: boom\n"}--event: done-data: {"success":false,"output":{"mimetype":"text/plain","data":""}}-diff --git a/tests/_cli/fixtures/pair/execute-success.sse b/tests/_cli/fixtures/pair/execute-success.ssedeleted file mode 100644index f01bc8076e..0000000000--- a/tests/_cli/fixtures/pair/execute-success.sse+++ /dev/null@@ -1,6 +0,0 @@-event: stdout-data: {"data":"hello\n"}--event: done-data: {"success":true,"output":{"mimetype":"text/plain","data":"2"}}-diff --git a/tests/_cli/fixtures/pair/host-run-failed.sse b/tests/_cli/fixtures/pair/host-run-failed.ssenew file mode 100644index 0000000000..34a28dbe8c--- /dev/null+++ b/tests/_cli/fixtures/pair/host-run-failed.sse@@ -0,0 +1,26 @@+event: ready+data: {}++event: execution+data: {"execution": {"id": "ex-other", "run_id": "run-other"}}++event: console+data: {"console": {"execution_id": "ex-other", "name": "stdout", "text": "ignored"}}++event: execution+data: {"execution": {"id": "ex-one", "run_id": "run-one"}}++event: console+data: {"console": {"execution_id": "ex-one", "name": "stdout", "text": "hello\n"}}++event: console+data: {"console": {"execution_id": "ex-one", "name": "stderr", "text": "warning\n"}}++event: execution+data: {"execution": {"id": "ex-one", "run_id": "run-one", "outcome": {"kind": "value", "display": {"mimetype": "text/plain", "data": "42"}}}}++event: run+data: {"run": {"id": "run-other", "status": "completed", "outcome": "failed"}}++event: run+data: {"run": {"id": "run-one", "status": "completed", "outcome": "failed"}}diff --git a/tests/_cli/fixtures/pair/host-run-interrupted.sse b/tests/_cli/fixtures/pair/host-run-interrupted.ssenew file mode 100644index 0000000000..07131dcb89--- /dev/null+++ b/tests/_cli/fixtures/pair/host-run-interrupted.sse@@ -0,0 +1,26 @@+event: ready+data: {}++event: execution+data: {"execution": {"id": "ex-other", "run_id": "run-other"}}++event: console+data: {"console": {"execution_id": "ex-other", "name": "stdout", "text": "ignored"}}++event: execution+data: {"execution": {"id": "ex-one", "run_id": "run-one"}}++event: console+data: {"console": {"execution_id": "ex-one", "name": "stdout", "text": "hello\n"}}++event: console+data: {"console": {"execution_id": "ex-one", "name": "stderr", "text": "warning\n"}}++event: execution+data: {"execution": {"id": "ex-one", "run_id": "run-one", "outcome": {"kind": "value", "display": {"mimetype": "text/plain", "data": "42"}}}}++event: run+data: {"run": {"id": "run-other", "status": "completed", "outcome": "failed"}}++event: run+data: {"run": {"id": "run-one", "status": "completed", "outcome": "interrupted"}}diff --git a/tests/_cli/fixtures/pair/host-run-succeeded.sse b/tests/_cli/fixtures/pair/host-run-succeeded.ssenew file mode 100644index 0000000000..2c26bc2bba--- /dev/null+++ b/tests/_cli/fixtures/pair/host-run-succeeded.sse@@ -0,0 +1,26 @@+event: ready+data: {}++event: execution+data: {"execution": {"id": "ex-other", "run_id": "run-other"}}++event: console+data: {"console": {"execution_id": "ex-other", "name": "stdout", "text": "ignored"}}++event: execution+data: {"execution": {"id": "ex-one", "run_id": "run-one"}}++event: console+data: {"console": {"execution_id": "ex-one", "name": "stdout", "text": "hello\n"}}++event: console+data: {"console": {"execution_id": "ex-one", "name": "stderr", "text": "warning\n"}}++event: execution+data: {"execution": {"id": "ex-one", "run_id": "run-one", "outcome": {"kind": "value", "display": {"mimetype": "text/plain", "data": "42"}}}}++event: run+data: {"run": {"id": "run-other", "status": "completed", "outcome": "failed"}}++event: run+data: {"run": {"id": "run-one", "status": "completed", "outcome": "succeeded"}}diff --git a/tests/_cli/test_cli_pair.py b/tests/_cli/test_cli_pair.pyindex 243aadc7c0..3fa6fa5378 100644--- a/tests/_cli/test_cli_pair.py+++ b/tests/_cli/test_cli_pair.py@@ -1,7 +1,6 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations-import hashlibimport jsonimport reimport shlex@@ -9,6 +8,7 @@ import sysfrom pathlib import Pathfrom typing import Anyfrom unittest.mock import patch+from urllib.parse import urlsplitimport pytestfrom click.testing import CliRunner@@ -17,21 +17,14 @@ from inline_snapshot import snapshotfrom marimo._cli.cli import main as cli_mainfrom marimo._cli.pair import commandsfrom marimo._cli.pair.client import (- AmbiguousSessionError,+ AmbiguousNotebookError,ExecutionResult,- NoSessionError,+ HostEndpoint,+ NoNotebookError,+ NotebookUnsupportedError,PairError,PairInputError,- StableSessionUnsupportedError,- StaleSessionError,-)-from marimo._cli.pair.commands import (- AgentConfig,- _codex_repository_skill_dirs,- _codex_skill_dirs,- _opencode_skill_dirs,- _plugin_skill_dirs,- pair_agents,+ StaleNotebookError,)_runner = CliRunner()@@ -40,8 +33,17 @@ TEST_URL = "https://localhost:8000?auth=tok123"@pytest.fixture(autouse=True)-def _isolate_pair_preview(monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.delenv("MARIMO_PAIR_NEXT", raising=False)+def _isolate_pair_command(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ commands,+ "resolve_host",+ lambda url: HostEndpoint(+ urlsplit(url)+ ._replace(path=urlsplit(url).path.rstrip("/") + "/api/marimo/v1")+ .geturl(),+ "host-secret",+ ),+ )monkeypatch.setattr("marimo._cli.pair.prompts.is_editable", lambda _: False)@@ -59,14 +61,22 @@ Usage: main pair [OPTIONS] COMMAND [ARGS]...Pair with a live marimo notebook.Authentication:- If a token-file path is supplied, add --token-file <PATH> to every- execute and notebook list command. Pass the path, not the file contents.+ Notebook discovery uses the editor token. Pass --token-file <PATH> to+ notebook list or execute without --notebook when a token is required.+ Host commands read their token from the private local host record.+ With host support off, execution uses the editor token and stable Session.Workflow:If no server is running, start one in the background:marimo edit <notebook.py> --no-token- If you do not have the server URL or session:+ If you do not have the server URL or notebook ID:marimo pair notebook list+ Connect to the notebook before waiting for work.+ Run marimo pair connect --help to check supported harnesses.+ If your harness is supported, start the server with MARIMO_ENABLE_HOST=1,+ then run (restart an existing server to enable host support):+ marimo pair connect --url <URL> --notebook <NOTEBOOK>+ Otherwise, work with the notebook using pair execute:marimo pair execute --url <URL> --session <SESSION> --code-file - <<'PY'import marimo._code_mode as cmasync with cm.get_context() as ctx:@@ -74,7 +84,7 @@ Usage: main pair [OPTIONS] COMMAND [ARGS]...cid = ctx.create_cell("import pandas as pd")ctx.run_cell(cid)PY- marimo pair execute --url <URL> --session <SESSION> --code-file - <<'PY'+ marimo pair execute --url <URL> --notebook <NOTEBOOK> --code-file - <<'PY'import marimo._code_mode as cmasync with cm.get_context() as ctx:cell = ctx.cells["<CELL_ID>"]@@ -82,14 +92,27 @@ Usage: main pair [OPTIONS] COMMAND [ARGS]...PYTarget selection:- --session takes the session_id from marimo pair notebook list. It does not- change when the page reloads or the notebook is renamed. If a command reports- an unknown session, the notebook was closed or restarted: run- marimo pair notebook list again and pick the new session_id.- If one notebook has several sessions, ask the user which one.- Do not switch sessions after authentication or connection errors,+ --session takes a stable session_id for editor execution.+ --notebook takes notebook_id for host execution. It survives+ kernel restarts and page reloads. Only saved notebooks inside the project+ root have a host notebook ID. Host commands need a local edit server.+ If several notebooks are open, ask the user which one.+ Do not switch notebooks after authentication or connection errors,or when execution is unconfirmed.+ Agent messages (preview):+ Start the server with MARIMO_ENABLE_HOST=1. The CLI needs no flag.+ Inside Codex, Claude Code, or OpenCode, run:+ marimo pair connect --url <URL> --notebook <NOTEBOOK>.+ Codex must use its shared daemon and support codex queue.+ Claude Code requires its native inbox on macOS or Linux.+ OpenCode 2.x requires its registered local service.+ Inbound message settings still apply; messages can be held or refused.+ Notebook agent messages arrive here as messages from marimo.+ Oversized agent messages include a complete JSON file on this machine.+ Files remain after detach. Cleanup removes owned files older than 24 hours.+ Use pair detach --notebook <NOTEBOOK> to stop the inbox.+Rules:Cells are the unit of work. The scratchpad is temporary; only code mode edits persist.Cells do not run on creation. Call run_cell after create_cell or edit_cell.@@ -109,15 +132,17 @@ Usage: main pair [OPTIONS] COMMAND [ARGS]...ctx.delete_cell(cid)ctx.packages.add("pandas>=2") # queued, installs on exitIf a cm call fails, run help(cm):- marimo pair execute --url <URL> --session <SESSION> -c 'import marimo._code_mode as cm; help(cm)'+ marimo pair execute --url <URL> --notebook <NOTEBOOK> -c 'import marimo._code_mode as cm; help(cm)'Options:-h, --help Show this message and exit.Commands:+ connect Connect this harness inbox to a live...+ detach Stop the forwarder and detach its notebook...docs Read notebook guidance on demand.- execute Run Python in a live notebook session.- notebook Find active notebooks and their sessions.+ execute Run Python in a live notebook.+ notebook Find active notebooks and their IDs.prompt Generate a prompt for pair programming on...""")@@ -125,11 +150,10 @@ Commands:result = _runner.invoke(cli_main, ["pair", "prompt", "--help"])assert result.exit_code == 0assert "--url" in result.output- assert "--claude" in result.output- assert "--codex" in result.output- assert "--opencode" in result.output- assert "--file" not in result.outputassert "--session" in result.output+ assert "--claude" not in result.output+ assert "--file" not in result.output+ assert "--notebook" in result.outputclass TestPairExecute:@@ -155,7 +179,9 @@ Usage: main pair execute [OPTIONS]Options:--url URL Server URL. [required]- --session ID Stable session_id from marimo pair notebook list.+ --notebook ID Host notebook_id from marimo pair notebook list.+ --session TEXT Stable Session ID from notebook list. Host execution is+ preferred when available.--token-file PATH Read the server token from a local file.-c TEXT Inline Python.--code-file PATH Read Python from a UTF-8 file, or from stdin when PATH is@@ -198,7 +224,7 @@ Options:"execute","--url",TEST_URL,- "--session",+ "--notebook","s_ab12cd",*resolved_arguments,],@@ -217,7 +243,7 @@ Options:"execute","--url",TEST_URL,- "--session",+ "--notebook","s_ab12cd","-c","",@@ -248,7 +274,7 @@ Options:"execute","--url",TEST_URL,- "--session",+ "--notebook","s_ab12cd","--code-file",str(code_file),@@ -277,7 +303,7 @@ Options:"execute","--url",TEST_URL,- "--session",+ "--notebook","s_ab12cd","--code-file","-",@@ -301,7 +327,7 @@ Options:"execute","--url",TEST_URL,- "--session",+ "--notebook","s_ab12cd","--code-file",str(code_file),@@ -329,7 +355,7 @@ Options:"execute","--url",TEST_URL,- "--session",+ "--notebook","s_ab12cd","--code-file",str(code_file),@@ -361,7 +387,7 @@ Options:"execute","--url",TEST_URL,- "--session",+ "--notebook","s_ab12cd","-c","print(1)",@@ -369,17 +395,21 @@ Options:)assert result.exit_code == 0- assert calls[0]["url"] == TEST_URL- assert calls[0]["session_id"] == "s_ab12cd"+ assert (+ calls[0]["url"]+ == "https://localhost:8000/api/marimo/v1?auth=tok123"+ )+ assert calls[0]["notebook_id"] == "s_ab12cd"assert calls[0]["code"] == "print(1)"- assert calls[0]["token"] is None+ assert calls[0]["token"] == "host-secret"assert calls[0]["stream"] is Falseassert json.loads(result.output) == {"success": True,+ "outcome": "succeeded","output": {"mimetype": "text/plain", "data": "done"},"stdout": "","stderr": "",- "session": {"id": "s_ab12cd"},+ "notebook": {"id": "s_ab12cd"},}def test_execute_failure_exits_one(@@ -389,6 +419,7 @@ Options:del kwargsreturn ExecutionResult(success=False,+ outcome="failed",output=None,stdout="",stderr="failed",@@ -403,7 +434,7 @@ Options:"execute","--url",TEST_URL,- "--session",+ "--notebook","s_ab12cd","-c","raise ValueError",@@ -413,10 +444,11 @@ Options:assert result.exit_code == 1assert json.loads(result.output) == {"success": False,+ "outcome": "failed","output": None,"stdout": "","stderr": "failed",- "session": {"id": "s_ab12cd"},+ "notebook": {"id": "s_ab12cd"},}@pytest.mark.parametrize(@@ -456,7 +488,7 @@ Options:"execute","--url",TEST_URL,- "--session",+ "--notebook","s_ab12cd","-c","x",@@ -469,7 +501,7 @@ Options:assert payload["stderr"] == stderrassert expected in payload["next"]assert (- "--session s_ab12cd" in payload["next"]+ "--notebook s_ab12cd" in payload["next"]or "top level" in (payload["next"]))@@ -480,6 +512,7 @@ Options:del kwargsreturn ExecutionResult(success=False,+ outcome="failed",output=None,stdout="",stderr='KeyError: "Cell \'a"b\' not found"',@@ -493,7 +526,7 @@ Options:"execute","--url","http://one/a b",- "--session",+ "--notebook","s'1","-c","x",@@ -503,7 +536,7 @@ Options:assert result.exit_code == 1payload = json.loads(result.output)assert "--url 'http://one/a b'" in payload["next"]- assert "--session 's'\"'\"'1'" in payload["next"]+ assert "--notebook 's'\"'\"'1'" in payload["next"]assert "ctx.cells['a\"b']" in payload["next"]def test_execute_stream_failure_prints_next_lines(@@ -511,7 +544,7 @@ Options:) -> None:def fail_execute(**kwargs: Any) -> ExecutionResult:del kwargs- raise StaleSessionError("Invalid session id: s_old")+ raise StaleNotebookError("Invalid session id: s_old")monkeypatch.setattr(commands, "execute_code", fail_execute)result = _runner.invoke(@@ -521,7 +554,7 @@ Options:"execute","--url","http://one",- "--session",+ "--notebook","s_old","--stream","-c",@@ -532,8 +565,8 @@ Options:assert result.exit_code == 2assert result.stdout == ""assert result.stderr == (- "error: No session s_old on http://one. "- "The notebook was closed or restarted.\n"+ "error: No notebook s_old on http://one. "+ "Run notebook list to find the current host notebook.\n"" next: marimo pair notebook list --url http://one\n")@@ -552,7 +585,7 @@ Options:"execute","--url","http://one",- "--session",+ "--notebook","s","-c","1",@@ -562,8 +595,7 @@ Options:assert result.exit_code == 2payload = json.loads(result.output)assert payload["error"] == "Authentication failed."- assert "MARIMO_TOKEN" in payload["next"]- assert "Never print the token" in payload["next"]+ assert "host discovery" in payload["next"]def test_execute_invalid_url_has_list_next(self) -> None:result = _runner.invoke(@@ -573,7 +605,7 @@ Options:"execute","--url","ftp://x",- "--session",+ "--notebook","s","-c","1",@@ -600,7 +632,7 @@ Options:"execute","--url",TEST_URL,- "--session",+ "--notebook","s_ab12cd","-c","print(1)",@@ -614,7 +646,7 @@ Options:"output": None,"stdout": None,"stderr": None,- "session": {"id": "s_ab12cd"},+ "notebook": {"id": "s_ab12cd"},}def test_execute_reports_server_without_stable_sessions(@@ -622,7 +654,7 @@ Options:) -> None:def fail_execute(**kwargs: Any) -> ExecutionResult:del kwargs- raise StableSessionUnsupportedError+ raise NotebookUnsupportedErrormonkeypatch.setattr(commands, "execute_code", fail_execute)result = _runner.invoke(@@ -632,7 +664,7 @@ Options:"execute","--url",TEST_URL,- "--session",+ "--notebook","s_ab12cd","-c","print(1)",@@ -645,12 +677,12 @@ Options:"success": False,"error": ("Server https://localhost:8000 runs a marimo version "- "without session_id. Upgrade marimo on the server."+ "without notebook_id. Upgrade marimo on the server."),"output": None,"stdout": None,"stderr": None,- "session": {"id": "s_ab12cd"},+ "notebook": {"id": "s_ab12cd"},}assert "next" not in payload@@ -669,7 +701,7 @@ Options:"execute","--url",TEST_URL,- "--session",+ "--notebook","s_ab12cd","-c","print(1)",@@ -707,7 +739,7 @@ Options:"execute","--url",TEST_URL,- "--session",+ "--notebook","s_ab12cd","--token-file",str(token_file),@@ -718,8 +750,8 @@ Options:)assert result.exit_code == 0- assert token_calls == [token_file]- assert execute_calls[0]["token"] == "secret"+ assert token_calls == []+ assert execute_calls[0]["token"] == "host-secret"assert execute_calls[0]["stream"] is Trueassert result.output == ""@@ -729,9 +761,9 @@ Options:resolve_calls: list[dict[str, Any]] = []execute_calls: list[dict[str, Any]] = []- def fake_resolve(**kwargs: Any) -> str:+ def fake_resolve(**kwargs: Any) -> tuple[str | None, str]:resolve_calls.append(kwargs)- return "s_one"+ return "s_one", "sess-one"def fake_execute(**kwargs: Any) -> ExecutionResult:execute_calls.append(kwargs)@@ -739,7 +771,7 @@ Options:success=True, output=None, stdout="", stderr="")- monkeypatch.setattr(commands, "resolve_session", fake_resolve)+ monkeypatch.setattr(commands, "resolve_execution_target", fake_resolve)monkeypatch.setattr(commands, "execute_code", fake_execute)result = _runner.invoke(cli_main,@@ -754,8 +786,10 @@ Options:)assert result.exit_code == 0- assert resolve_calls == [{"url": "http://one", "token": None}]- assert execute_calls[0]["session_id"] == "s_one"+ assert resolve_calls == [+ {"url": "http://one", "token": None, "session_id": None}+ ]+ assert execute_calls[0]["notebook_id"] == "s_one"def test_execute_rejects_file_selector(self, monkeypatch: pytest.MonkeyPatch@@ -788,12 +822,12 @@ Options:) -> None:def fake_resolve(**kwargs: Any) -> str:del kwargs- raise NoSessionError(+ raise NoNotebookError("No running session on http://one.",url="http://user:password@one?access_token=secret",)- monkeypatch.setattr(commands, "resolve_session", fake_resolve)+ monkeypatch.setattr(commands, "resolve_execution_target", fake_resolve)monkeypatch.setattr(commands,"execute_code",@@ -818,7 +852,7 @@ Options:assert payload["next"].endswith("marimo pair notebook list --url http://one")- assert payload["session"] == {"id": None}+ assert payload["notebook"] == {"id": None}assert "password" not in result.outputassert "secret" not in result.output@@ -827,13 +861,13 @@ Options:) -> None:def fake_resolve(**kwargs: Any) -> str:del kwargs- raise AmbiguousSessionError(+ raise AmbiguousNotebookError("Server http://one has 2 running sessions.",url="http://user:password@one?access_token=secret",candidates=("sess-a", "sess-b"),)- monkeypatch.setattr(commands, "resolve_session", fake_resolve)+ monkeypatch.setattr(commands, "resolve_execution_target", fake_resolve)monkeypatch.setattr(commands,"execute_code",@@ -878,7 +912,7 @@ Options:monkeypatch.setattr(commands,- "resolve_session",+ "resolve_execution_target",lambda **_kwargs: pytest.fail("resolve must not run"),)monkeypatch.setattr(commands, "execute_code", fake_execute)@@ -889,7 +923,7 @@ Options:"execute","--url","http://user:password@one?access_token=secret",- "--session",+ "--notebook","s_given","-c","print(1)",@@ -897,14 +931,14 @@ Options:)assert result.exit_code == 0- assert execute_calls[0]["session_id"] == "s_given"+ assert execute_calls[0]["notebook_id"] == "s_given"def test_execute_stale_session_maps_to_targeted_message(self, monkeypatch: pytest.MonkeyPatch) -> None:def fail_execute(**kwargs: Any) -> ExecutionResult:del kwargs- raise StaleSessionError("Invalid stable session id: sess-old")+ raise StaleNotebookError("Invalid stable session id: sess-old")monkeypatch.setattr(commands, "execute_code", fail_execute)result = _runner.invoke(@@ -914,7 +948,7 @@ Options:"execute","--url","http://user:password@one?access_token=secret",- "--session",+ "--notebook","sess-old","-c","print(1)",@@ -924,8 +958,8 @@ Options:assert result.exit_code == 2payload = json.loads(result.output)assert payload["error"] == (- "No session sess-old on http://one. "- "The notebook was closed or restarted."+ "No notebook sess-old on http://one. "+ "Run notebook list to find the current host notebook.")assert payload["next"].endswith("marimo pair notebook list --url http://one"@@ -1008,13 +1042,13 @@ class TestPairNotebooks:assert result.output == snapshot("""\Usage: main pair notebook [OPTIONS] COMMAND [ARGS]...- Find active notebooks and their sessions.+ Find active notebooks and their IDs.Options:-h, --help Show this message and exit.Commands:- list List active notebooks and their session IDs.+ list List active notebooks and their host IDs.""")def test_notebook_list_help(self) -> None:@@ -1026,7 +1060,7 @@ Commands:assert result.output == snapshot("""\Usage: main pair notebook list [OPTIONS]- List active notebooks and their session IDs.+ List active notebooks and their host IDs.Options:--url URL Server URL. Repeat to list more than one server.@@ -1045,11 +1079,13 @@ Options:"session_id": "sess-stable-2","filename": "analysis.py","path": "/work/analysis.py",+ "notebook_id": "nb-analysis",},"session-1": {"session_id": "sess-stable-1","filename": "analysis.py","path": "/work/analysis.py",+ "notebook_id": "nb-analysis",},},)@@ -1066,6 +1102,7 @@ Options:"server": {"url": "http://one"},"name": "analysis.py","path": "/work/analysis.py",+ "notebook_id": "nb-analysis","sessions": [{"id": "session-1",@@ -1218,6 +1255,7 @@ Options:"session_id": "sess-stable-1","filename": "analysis.py","path": "/work/analysis.py",+ "notebook_id": "nb-analysis",}}@@ -1242,6 +1280,7 @@ Options:"server": {"url": "http://good"},"name": "analysis.py","path": "/work/analysis.py",+ "notebook_id": "nb-analysis","sessions": [{"id": "session-1",@@ -1271,6 +1310,7 @@ Options:"session_id": "sess-stable-1","filename": "analysis.py","path": "/work/analysis.py",+ "notebook_id": "nb-analysis",}}@@ -1315,7 +1355,7 @@ Options:self, monkeypatch: pytest.MonkeyPatch) -> None:def fail_list_sessions(**_kwargs: Any) -> None:- raise StableSessionUnsupportedError+ raise NotebookUnsupportedErrormonkeypatch.setattr(commands, "list_sessions", fail_list_sessions)@@ -1329,7 +1369,7 @@ Options:assert payload["notebooks"] == []assert payload["warnings"] == [(- "Server http://one runs a marimo version without session_id. "+ "Server http://one runs a marimo version without notebook_id. ""Upgrade marimo on the server.")]@@ -1410,29 +1450,21 @@ Options:class TestPairPrompt:- def test_prompt_requires_url(self) -> None:- result = _runner.invoke(cli_main, ["pair", "prompt"])- assert result.exit_code != 0-- @pytest.mark.parametrize("flag", [None, "0", "false", ""])- def test_prompt_outputs_url(self, flag: str | None) -> None:+ @pytest.mark.parametrize(+ "selector", [[], ["--session", "sess-one"], ["--notebook", "nb-one"]]+ )+ def test_prompt_is_cli_without_flags(self, selector: list[str]) -> None:result = _runner.invoke(- cli_main,- ["pair", "prompt", "--url", TEST_URL],- env={"MARIMO_PAIR_NEXT": flag},+ cli_main, ["pair", "prompt", "--url", TEST_URL, *selector])assert result.exit_code == 0- assert result.output == snapshot("""\-Use the /marimo-pair skill to pair-program on a running marimo notebook.--Connect to the notebook at: https://localhost:8000?auth=tok123--Use `execute-code.sh --url 'https://localhost:8000?auth=tok123'` from the marimo-pair skill to execute code in the notebook.--Once you are connected, send a fun toast (mo.status.toast(...)) to the user inside marimo letting them know you're ready to pair.-""")+ assert TEST_URL in result.output+ assert "pair --help" in result.output+ assert "skill" not in result.output+ if selector:+ assert selector[1] in result.output- def test_prompt_rejects_file_selector(self) -> None:+ def test_prompt_rejects_ambiguous_target(self) -> None:result = _runner.invoke(cli_main,[@@ -1440,588 +1472,72 @@ Once you are connected, send a fun toast (mo.status.toast(...)) to the user insi"prompt","--url",TEST_URL,- "--file",- "notebooks/example.py",+ "--session",+ "s",+ "--notebook",+ "n",],)assert result.exit_code == 2- assert "unexpected argument '--file'" in result.output-- def test_prompt_without_session_omits_selector(self) -> None:- result = _runner.invoke(- cli_main, ["pair", "prompt", "--url", TEST_URL]- )- assert result.exit_code == 0- assert "--file" not in result.output- assert "--session" not in result.output-- def test_prompt_with_session(self) -> None:- result = _runner.invoke(- cli_main,- ["pair", "prompt", "--url", TEST_URL, "--session", "s_ab12cd"],- )- assert result.exit_code == 0- assert result.output == snapshot("""\-Use the /marimo-pair skill to pair-program on a running marimo notebook.--Connect to the notebook at: https://localhost:8000?auth=tok123-Use `execute-code.sh --url 'https://localhost:8000?auth=tok123' --session s_ab12cd` from the marimo-pair skill to execute code in the notebook.--Once you are connected, send a fun toast (mo.status.toast(...)) to the user inside marimo letting them know you're ready to pair.-""")+ def test_prompt_requires_url(self) -> None:+ assert _runner.invoke(cli_main, ["pair", "prompt"]).exit_code == 2- def test_prompt_shell_quotes_session_ids(self) -> None:- cases = [- ("sess-stable", "--session sess-stable"),- ("sess stable", "--session 'sess stable'"),- ("sess'quote", """--session 'sess'"'"'quote'"""),- ]- for session_id, expected in cases:- result = _runner.invoke(- cli_main,- [- "pair",- "prompt",- "--url",- TEST_URL,- "--session",- session_id,- ],- )- assert result.exit_code == 0- assert expected in result.output-- def test_prompt_shell_quotes_url_with_metacharacters(self) -> None:- # The execute-code.sh command is meant to be copy-pasted into a shell,- # so a url with metacharacters (`&`) must be quoted so it isn't split.- url = "http://localhost:8000?file=a&b"- result = _runner.invoke(cli_main, ["pair", "prompt", "--url", url])- assert result.exit_code == 0- assert f"execute-code.sh --url '{url}'" in result.output-- def test_prompt_skill_missing(self) -> None:- with patch.object(AgentConfig, "has_skill", return_value=False):- for flag in ("--claude", "--codex", "--opencode"):- result = _runner.invoke(- cli_main,- ["pair", "prompt", "--url", TEST_URL, flag],- )- assert result.exit_code == 0, flag- assert "could not be found" in result.output, flag-- def test_prompt_skill_installed(self) -> None:- with patch.object(AgentConfig, "has_skill", return_value=True):- for flag in ("--claude", "--codex", "--opencode"):- result = _runner.invoke(- cli_main,- ["pair", "prompt", "--url", TEST_URL, flag],- )- assert result.exit_code == 0, flag- assert TEST_URL in result.output, flag-- def test_prompt_handles_skill_permission_error(self) -> None:- with patch.object(Path, "exists", side_effect=PermissionError):+ def test_token_is_private_and_shell_quoted(self, tmp_path: Path) -> None:+ with patch.object(commands, "_token_dir", return_value=tmp_path):result = _runner.invoke(cli_main,- ["pair", "prompt", "--url", TEST_URL, "--codex"],+ ["pair", "prompt", "--url", TEST_URL, "--with-token"],+ input="private-token\n",)-assert result.exit_code == 0- assert "could not be found" in result.output- assert TEST_URL in result.output+ assert "private-token" not in result.output+ token_file = next(tmp_path.iterdir())+ assert token_file.read_text() == "private-token"+ if sys.platform != "win32":+ assert token_file.stat().st_mode & 0o777 == 0o600+ token_option = re.search(r"`(--token-file .+)`", result.stdout)+ assert token_option is not None+ assert shlex.split(token_option.group(1)) == [+ "--token-file",+ str(token_file),+ ]- def test_prompt_finds_codex_user_skill(self, tmp_path: Path) -> None:- home = tmp_path / "home"- cwd = tmp_path / "project"- skill = home / ".agents" / "skills" / "marimo-pair" / "SKILL.md"- skill.parent.mkdir(parents=True)- skill.write_text("test")- cwd.mkdir()-- with (- patch.object(Path, "home", return_value=home),- patch.object(Path, "cwd", return_value=cwd),- ):+ def test_empty_token_preserves_existing_file(self, tmp_path: Path) -> None:+ token_file = tmp_path / "existing"+ token_file.write_text("previous")+ with patch.object(commands, "_token_dir", return_value=tmp_path):result = _runner.invoke(cli_main,- ["pair", "prompt", "--url", TEST_URL, "--codex"],+ ["pair", "prompt", "--url", TEST_URL, "--with-token"],+ input="\n",)-assert result.exit_code == 0- assert "could not be found" not in result.output-+ assert token_file.read_text() == "previous"+ assert "--token-file" not in result.stdout-class TestPairPromptPreview:@pytest.mark.parametrize(("editable", "command"),[(True, "uv run marimo"), (False, "uvx marimo@latest")],)- def test_prompt_uses_installation_command(+ def test_installation_command(self, monkeypatch: pytest.MonkeyPatch, editable: bool, command: str) -> None:monkeypatch.setattr("marimo._cli.pair.prompts.is_editable", lambda _: editable)- result = _runner.invoke(- cli_main,- ["pair", "prompt", "--url", "http://localhost:2718"],- env={"MARIMO_PAIR_NEXT": "1"},- )-- assert result.exit_code == 0- assert result.output == (- "Pair with me on this running marimo notebook.\n\n"- "URL: http://localhost:2718\n\n"- f"Run `{command} pair --help` first.\n"- f"Use `{command}` for all marimo commands.\n\n"- "Once connected, send a fun toast using `mo.status.toast(...)` "- "(`import marimo as mo`).\n"- )-- def test_with_token_uses_private_file(self, tmp_path: Path) -> None:- token_dir = tmp_path / "tokens ' {command}"- with patch.object(commands, "_token_dir", return_value=token_dir):- result = _runner.invoke(- cli_main,- [- "pair",- "prompt",- "--url",- "http://localhost:2718",- "--session",- "s_ab12cd",- "--with-token",- ],- env={"MARIMO_PAIR_NEXT": "1"},- input="my-secret-token\n",- )-- assert result.exit_code == 0- assert (- "Auth token (leave empty if MARIMO_TOKEN is set):" in result.stderr- )- assert "my-secret-token" not in result.output- token_file = next(token_dir.iterdir())- assert token_file.read_text() == "my-secret-token"- if sys.platform != "win32":- assert token_file.stat().st_mode & 0o777 == 0o600-- token_command = re.search(r"`(--token-file .+)`", result.stdout)- assert token_command is not None- assert shlex.split(token_command.group(1)) == [- "--token-file",- str(token_file),- ]- assert result.stdout.replace(- shlex.quote(str(token_file)), "<TOKEN_FILE>"- ) == snapshot("""\-Pair with me on this running marimo notebook.--URL: http://localhost:2718-Session: s_ab12cd--Run `uvx marimo@latest pair --help` first.-Use `uvx marimo@latest` for all marimo commands.--Once connected, send a fun toast using `mo.status.toast(...)` (`import marimo as mo`).--For authenticated Pair commands, pass `--token-file <TOKEN_FILE>`.-""")-- @pytest.mark.parametrize("agent", ["--claude", "--codex", "--opencode"])- def test_prompt_needs_no_skill(- self,- agent: str,- tmp_path: Path,- monkeypatch: pytest.MonkeyPatch,- ) -> None:- monkeypatch.chdir(tmp_path)- monkeypatch.setenv("HOME", str(tmp_path))- monkeypatch.setenv("USERPROFILE", str(tmp_path))- result = _runner.invoke(- cli_main,- ["pair", "prompt", "--url", "http://localhost:2718", agent],- env={"MARIMO_PAIR_NEXT": "1"},- )-- assert result.exit_code == 0- assert result.output == snapshot("""\-Pair with me on this running marimo notebook.--URL: http://localhost:2718--Run `uvx marimo@latest pair --help` first.-Use `uvx marimo@latest` for all marimo commands.--Once connected, send a fun toast using `mo.status.toast(...)` (`import marimo as mo`).-""")-- def test_prompt_preserves_connection_details(self) -> None:- result = _runner.invoke(- cli_main,- [- "pair",- "prompt",- "--url",- "http://localhost:2718/{session}",- "--session",- "{command}/it's session",- ],- env={"MARIMO_PAIR_NEXT": "1"},- )-- assert result.exit_code == 0- assert result.output == snapshot("""\-Pair with me on this running marimo notebook.--URL: http://localhost:2718/{session}-Session: {command}/it's session--Run `uvx marimo@latest pair --help` first.-Use `uvx marimo@latest` for all marimo commands.--Once connected, send a fun toast using `mo.status.toast(...)` (`import marimo as mo`).-""")-- @pytest.mark.parametrize("flag", ["1", "true", " TRUE "])- def test_prompt_uses_cli(self, flag: str) -> None:- result = _runner.invoke(- cli_main,- [- "pair",- "prompt",- "--url",- "http://localhost:2718",- "--session",- "sess-stable",- ],- env={"MARIMO_PAIR_NEXT": flag},- )-- assert result.exit_code == 0- assert result.output == snapshot("""\-Pair with me on this running marimo notebook.--URL: http://localhost:2718-Session: sess-stable--Run `uvx marimo@latest pair --help` first.-Use `uvx marimo@latest` for all marimo commands.--Once connected, send a fun toast using `mo.status.toast(...)` (`import marimo as mo`).-""")---class TestPairPromptWithToken:- @pytest.mark.parametrize("preview", ["0", "1"])- @pytest.mark.parametrize("existing_file", [False, True])- def test_empty_token_skips_file(- self, tmp_path: Path, preview: str, existing_file: bool- ) -> None:- token_dir = tmp_path / "tokens"- url_hash = hashlib.sha256(TEST_URL.encode()).hexdigest()[:6]- token_file = token_dir / f"{url_hash}-token.txt"- if existing_file:- token_dir.mkdir()- token_file.write_text("previous-token", encoding="utf-8")- env = {"MARIMO_PAIR_NEXT": preview, "MARIMO_TOKEN": "env-secret"}- args = ["pair", "prompt", "--url", TEST_URL]- with patch.object(commands, "_token_dir", return_value=token_dir):- result = _runner.invoke(- cli_main, [*args, "--with-token"], input="\n", env=env- )- without_token = _runner.invoke(cli_main, args, env=env)-- assert result.exit_code == 0- assert result.stdout == without_token.stdout- assert "env-secret" not in result.output- if existing_file:- assert token_file.read_text(encoding="utf-8") == "previous-token"- else:- assert not token_dir.exists()-- def test_with_token_writes_file_and_outputs_prompt(- self, tmp_path: Path- ) -> None:- with patch(- "marimo._cli.pair.commands._token_dir", return_value=tmp_path- ):- result = _runner.invoke(- cli_main,- ["pair", "prompt", "--url", TEST_URL, "--with-token"],- input="my-secret-token\n",- )- assert result.exit_code == 0- assert TEST_URL in result.output- assert "execute-code.sh" in result.output- assert "token" in result.output.lower()- assert "cat" in result.output-- url_hash = hashlib.sha256(TEST_URL.encode()).hexdigest()[:6]- token_file = tmp_path / f"{url_hash}-token.txt"- assert token_file.exists()- assert token_file.read_text() == "my-secret-token"- if sys.platform != "win32":- assert oct(token_file.stat().st_mode & 0o777) == "0o600"-- def test_with_token_and_session(self, tmp_path: Path) -> None:- with patch(- "marimo._cli.pair.commands._token_dir", return_value=tmp_path- ):- result = _runner.invoke(- cli_main,- [- "pair",- "prompt",- "--url",- TEST_URL,- "--session",- "sess stable",- "--with-token",- ],- input="my-secret-token\n",- )- assert result.exit_code == 0- assert "--session 'sess stable'" in result.output- # The token hint should target the same session.- assert "--session 'sess stable' --token" in result.output-- def test_with_token_still_requires_url(self) -> None:- result = _runner.invoke(- cli_main,- ["pair", "prompt", "--with-token"],- input="tok\n",- )- assert result.exit_code != 0-- def test_with_token_and_agent_flag(self, tmp_path: Path) -> None:- with (- patch.object(AgentConfig, "has_skill", return_value=True),- patch(- "marimo._cli.pair.commands._token_dir",- return_value=tmp_path,- ),- ):- result = _runner.invoke(- cli_main,- [- "pair",- "prompt",- "--url",- TEST_URL,- "--claude",- "--with-token",- ],- input="secret\n",- )- assert result.exit_code == 0- assert TEST_URL in result.output- assert "token" in result.output.lower()-- def test_with_token_and_skill_missing_fails(self) -> None:- with patch.object(AgentConfig, "has_skill", return_value=False):- result = _runner.invoke(- cli_main,- [- "pair",- "prompt",- "--url",- TEST_URL,- "--claude",- "--with-token",- ],- input="secret\n",- )- assert result.exit_code == 0- assert "could not be found" in result.output-- def test_without_token_no_token_hint(self) -> None:result = _runner.invoke(cli_main, ["pair", "prompt", "--url", TEST_URL])assert result.exit_code == 0- assert "cat" not in result.output---class TestOpencodeSkillDirs:- def test_opencode_skill_dirs(self) -> None:- cwd = Path.cwd()- home = Path.home()- assert _opencode_skill_dirs() == [- cwd / ".opencode" / "skills",- home / ".config" / "opencode" / "skills",- cwd / ".claude" / "skills",- home / ".claude" / "skills",- cwd / ".agents" / "skills",- home / ".agents" / "skills",- ]---class TestCodexSkillDirs:- def test_codex_skill_dirs_include_supported_global_locations(- self, tmp_path: Path- ) -> None:- home = tmp_path / "home"- cwd = tmp_path / "project"- cwd.mkdir()-- with (- patch.object(Path, "home", return_value=home),- patch.object(Path, "cwd", return_value=cwd),- ):- skill_dirs = _codex_skill_dirs()+ assert f"{command} pair --help" in result.output- assert home / ".agents" / "skills" in skill_dirs- assert Path("/etc/codex/skills") in skill_dirs-- def test_codex_repository_skill_dirs_stop_at_repository_root(- self, tmp_path: Path- ) -> None:- repository = tmp_path / "repository"- cwd = repository / "packages" / "notebooks"- cwd.mkdir(parents=True)- (repository / ".git").mkdir()-- assert _codex_repository_skill_dirs(cwd) == [- cwd / ".agents" / "skills",- cwd.parent / ".agents" / "skills",- repository / ".agents" / "skills",- ]-- def test_codex_repository_skill_dirs_only_check_cwd_without_repository(- self, tmp_path: Path- ) -> None:- cwd = tmp_path / "notebooks"- cwd.mkdir()- assert _codex_repository_skill_dirs(cwd) == [- cwd / ".agents" / "skills"- ]-- def test_codex_repository_skill_dirs_stop_on_permission_error(- self, tmp_path: Path- ) -> None:- cwd = tmp_path / "repository" / "notebooks"- cwd.mkdir(parents=True)-- with patch.object(Path, "exists", side_effect=PermissionError):- assert _codex_repository_skill_dirs(cwd) == [- cwd / ".agents" / "skills"- ]---class TestAgentConfig:- def test_has_skill_true(self, tmp_path: Path) -> None:- skill_dir = tmp_path / "skills"- (skill_dir / "marimo-pair").mkdir(parents=True)- (skill_dir / "marimo-pair" / "SKILL.md").write_text("test")-- agent = AgentConfig(name="test", skill_dirs=[skill_dir])- assert agent.has_skill() is True-- def test_has_skill_false(self, tmp_path: Path) -> None:- agent = AgentConfig(name="test", skill_dirs=[tmp_path / "nonexistent"])- assert agent.has_skill() is False-- def test_has_skill_empty_dirs(self) -> None:- agent = AgentConfig(name="test", skill_dirs=[])- assert agent.has_skill() is False-- def test_has_skill_multiple_dirs_first_match(self, tmp_path: Path) -> None:- dir1 = tmp_path / "a" / "skills"- dir2 = tmp_path / "b" / "skills"- (dir1 / "marimo-pair").mkdir(parents=True)- (dir1 / "marimo-pair" / "SKILL.md").write_text("test")-- agent = AgentConfig(name="test", skill_dirs=[dir1, dir2])- assert agent.has_skill() is True-- def test_has_skill_multiple_dirs_second_match(- self, tmp_path: Path- ) -> None:- dir1 = tmp_path / "a" / "skills"- dir2 = tmp_path / "b" / "skills"- (dir2 / "marimo-pair").mkdir(parents=True)- (dir2 / "marimo-pair" / "SKILL.md").write_text("test")-- agent = AgentConfig(name="test", skill_dirs=[dir1, dir2])- assert agent.has_skill() is True-- def test_has_skill_skips_permission_error(self, tmp_path: Path) -> None:- agent = AgentConfig(- name="test",- skill_dirs=[tmp_path / "inaccessible", tmp_path / "installed"],- )-- with patch.object(Path, "exists", side_effect=[PermissionError, True]):- assert agent.has_skill() is True---class TestPluginSkillDirs:- def test_pair_agents_discovers_plugin_skills(self, tmp_path: Path) -> None:- claude_skill_dir = (- tmp_path- / ".claude"- / "plugins"- / "marketplaces"- / "marimo-pair"- / "skills"- / "marimo-pair"- )- codex_skill_dir = (- tmp_path- / ".codex"- / "plugins"- / "cache"- / "marimo-pair"- / "marimo-pair"- / "0.0.18"- / "skills"- / "marimo-pair"- )- claude_skill_dir.mkdir(parents=True)- codex_skill_dir.mkdir(parents=True)- (claude_skill_dir / "SKILL.md").write_text("test")- (codex_skill_dir / "SKILL.md").write_text("test")-- with (- patch.object(Path, "home", return_value=tmp_path),- patch.object(Path, "cwd", return_value=tmp_path),- ):- agents = pair_agents()-- assert agents["claude"].has_skill() is True- assert agents["codex"].has_skill() is True-- def test_claude_marketplace_layout(self, tmp_path: Path) -> None:- skill_dir = (- tmp_path / "plugins" / "marketplaces" / "marimo-pair" / "skills"- )- (skill_dir / "marimo-pair").mkdir(parents=True)- (skill_dir / "marimo-pair" / "SKILL.md").write_text("test")-- agent = AgentConfig(- name="Claude Code",- skill_dirs=_plugin_skill_dirs(tmp_path),- )- assert agent.has_skill() is True-- def test_plugin_cache_layout(self, tmp_path: Path) -> None:- skill_dir = (- tmp_path- / "plugins"- / "cache"- / "marimo-pair"- / "marimo-pair"- / "0.0.18"- / "skills"- )- (skill_dir / "marimo-pair").mkdir(parents=True)- (skill_dir / "marimo-pair" / "SKILL.md").write_text("test")-- agent = AgentConfig(- name="Codex",- skill_dirs=_plugin_skill_dirs(tmp_path),- )- assert agent.has_skill() is True[email protected]("agent", ["--claude", "--codex", "--opencode"])+def test_legacy_launcher_flag_still_generates_cli_prompt(agent: str) -> None:+ result = _runner.invoke(+ cli_main, ["pair", "prompt", "--url", TEST_URL, agent]+ )+ assert result.exit_code == 0+ assert "pair --help" in result.output+ assert "skill" not in result.outputdiff --git a/tests/_cli/test_pair_claude.py b/tests/_cli/test_pair_claude.pynew file mode 100644index 0000000000..301eea80af--- /dev/null+++ b/tests/_cli/test_pair_claude.py@@ -0,0 +1,275 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import json+import os+import queue+import socket+import sys+import threading+import urllib.request+from pathlib import Path+from typing import TYPE_CHECKING+from unittest.mock import Mock++import msgspec+import pytest++from marimo._cli.pair.client import PairError, PairInputError+from marimo._cli.pair.connection import ConnectionStore, connection_identity+from marimo._cli.pair.delivery import DeliveryTarget, ProcessHandle+from marimo._cli.pair.forwarder import ForwarderConfig, start_forwarder+from marimo._cli.pair.harnesses import detect_target, harness_for+from marimo._cli.pair.harnesses.claude import ClaudeHarness+from tests._cli._pair_server import pair_test_server++if TYPE_CHECKING:+ from collections.abc import Iterator++pytestmark = pytest.mark.skipif(+ sys.platform == "win32", reason="Claude adapter uses Unix sockets"+)+++def inbox() -> Iterator[tuple[str, socket.socket]]:+ # macOS limits Unix socket paths to 104 bytes.+ import tempfile++ with tempfile.TemporaryDirectory(prefix="pair-", dir="/tmp") as directory:+ address = str(Path(directory) / "inbox.sock")+ with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as listener:+ listener.bind(address)+ listener.listen()+ yield address, listener+++def test_detect_native_inbox(+ inbox: tuple[str, socket.socket],+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ import psutil++ address, _ = inbox+ owner = ProcessHandle.capture(os.getpid())+ process = Mock(pid=owner.pid)+ process.name.side_effect = AssertionError("Use CLAUDE_PID, not names")+ process.cmdline.side_effect = AssertionError("Use CLAUDE_PID, not argv")+ monkeypatch.setattr(psutil.Process, "parents", lambda _: [process])+ harness, target = detect_target(+ {+ "CLAUDE_CODE_MESSAGING_SOCKET": address,+ "CLAUDE_CODE_MESSAGING_TOKEN": "private-token",+ "CLAUDE_PID": str(owner.pid),+ },+ "claude",+ )+ assert isinstance(harness, ClaudeHarness)+ assert target == DeliveryTarget(+ "claude", address, "Claude Code", owner, "private-token"+ )+ assert harness.open_inbox(target).alive()+ assert "private-token" not in repr(target)+ config = ForwarderConfig(+ "http://localhost", "nb-one", "identity", None, target+ )+ assert (+ msgspec.json.decode(msgspec.json.encode(config), type=ForwarderConfig)+ == config+ )+++def test_missing_inbox_is_not_detected() -> None:+ assert ClaudeHarness().detect({}) is None+ assert isinstance(harness_for("claude"), ClaudeHarness)+++def test_explicit_pid_does_not_require_claude_pid(+ inbox: tuple[str, socket.socket], monkeypatch: pytest.MonkeyPatch+) -> None:+ import psutil++ address, _ = inbox+ owner = ProcessHandle.capture(os.getpid())+ monkeypatch.setattr(+ psutil.Process,+ "parents",+ Mock(side_effect=AssertionError("Explicit PID must bypass discovery")),+ )+ _, target = detect_target(+ {+ "CLAUDE_CODE_MESSAGING_SOCKET": address,+ "CLAUDE_CODE_MESSAGING_TOKEN": "private-token",+ },+ "claude",+ pid=owner.pid,+ )+ assert target == DeliveryTarget(+ "claude", address, "Claude Code", owner, "private-token"+ )+++def test_reject_stale_or_symlink_inbox(+ inbox: tuple[str, socket.socket], tmp_path: Path+) -> None:+ address, _ = inbox+ link = tmp_path / "link"+ link.symlink_to(address)+ for path in (str(tmp_path / "missing"), str(link)):+ with pytest.raises(PairInputError, match="socket is unavailable"):+ ClaudeHarness().detect({"CLAUDE_CODE_MESSAGING_SOCKET": path})+++def test_require_own_child_token(inbox: tuple[str, socket.socket]) -> None:+ address, _ = inbox+ with pytest.raises(PairInputError, match="inbox token"):+ ClaudeHarness().detect({"CLAUDE_CODE_MESSAGING_SOCKET": address})+++def test_require_claude_parent(+ inbox: tuple[str, socket.socket], monkeypatch: pytest.MonkeyPatch+) -> None:+ import psutil++ address, _ = inbox+ monkeypatch.setattr(psutil.Process, "parents", lambda _: [])+ with pytest.raises(PairInputError, match="native Claude Code session"):+ ClaudeHarness().detect(+ {+ "CLAUDE_CODE_MESSAGING_SOCKET": address,+ "CLAUDE_CODE_MESSAGING_TOKEN": "private-token",+ "CLAUDE_PID": str(os.getpid()),+ }+ )++[email protected]("pid", ["", "invalid", "0", "-1"])+def test_require_documented_pid(+ inbox: tuple[str, socket.socket], pid: str+) -> None:+ address, _ = inbox+ with pytest.raises(PairInputError, match="valid CLAUDE_PID"):+ ClaudeHarness().detect(+ {+ "CLAUDE_CODE_MESSAGING_SOCKET": address,+ "CLAUDE_CODE_MESSAGING_TOKEN": "private-token",+ "CLAUDE_PID": pid,+ }+ )+++def test_send_preserves_text_and_authenticates(+ inbox: tuple[str, socket.socket],+) -> None:+ address, listener = inbox+ target = DeliveryTarget(+ "claude", address, "Claude Code", auth_token="private-token"+ )+ text = 'Unicode 🐍\n"quotes"; $(must not execute)'+ ClaudeHarness().open_inbox(target).send(text)+ listener.settimeout(2)+ with listener.accept()[0] as connection:+ with connection.makefile("rb") as reader:+ assert [json.loads(line) for line in reader] == [+ {"type": "auth", "token": "private-token"},+ {"type": "user", "message": {"role": "user", "content": text}},+ ]+++def test_send_failure_does_not_leak(tmp_path: Path) -> None:+ target = DeliveryTarget(+ "claude",+ str(tmp_path / "missing"),+ "Claude Code",+ auth_token="private-token",+ )+ with pytest.raises(PairError, match="Could not deliver") as error:+ ClaudeHarness().open_inbox(target).send("private-message")+ assert "private-token" not in str(error.value)+ assert "private-message" not in str(error.value)+++def test_liveness_tracks_socket_and_process(+ inbox: tuple[str, socket.socket],+) -> None:+ address, _ = inbox+ harness = ClaudeHarness()+ owner = ProcessHandle.capture(os.getpid())+ assert not harness.open_inbox(+ DeliveryTarget("claude", address, "Claude Code")+ ).alive()+ assert not harness.open_inbox(+ DeliveryTarget(+ "claude", address, "Claude Code", ProcessHandle(owner.pid, 0)+ )+ ).alive()+ Path(address).unlink()+ assert not harness.open_inbox(+ DeliveryTarget("claude", address, "Claude Code", owner)+ ).alive()+++def test_detached_forwarder_delivers_to_claude_socket(+ inbox: tuple[str, socket.socket],+ tmp_path: Path,+) -> None:+ from marimo._cli.pair.client import resolve_host++ address, listener = inbox+ received: queue.Queue[list[dict[str, object]]] = queue.Queue()++ def read() -> None:+ listener.settimeout(10)+ with listener.accept()[0] as connection:+ connection.settimeout(10)+ with connection.makefile("rb") as reader:+ received.put([json.loads(line) for line in reader])++ with pair_test_server(tmp_path) as server:+ host = resolve_host(server.url)+ target = DeliveryTarget(+ "claude",+ address,+ "Claude Code",+ ProcessHandle.capture(os.getpid()),+ "private-inbox-token",+ )+ config = ForwarderConfig(+ host.url,+ server.notebook_id,+ connection_identity(server.notebook_id, "claude", address),+ host.token,+ target,+ )+ store = ConnectionStore(tmp_path / "connections")+ record = start_forwarder(config, store)+ thread = threading.Thread(target=read, daemon=True)+ thread.start()+ try:+ message = {"error": "Claude socket delivery 🐍"}+ request = urllib.request.Request(+ f"{server.url}/api/pair/notebooks/{server.stable_session_id}/messages",+ method="POST",+ data=json.dumps(message).encode(),+ headers={"Content-Type": "application/json"},+ )+ with urllib.request.urlopen(request, timeout=5) as response:+ assert response.status == 202+ frames = received.get(timeout=10)+ assert frames[0] == {+ "type": "auth",+ "token": "private-inbox-token",+ }+ assert frames[1]["type"] == "user"+ body = frames[1]["message"]+ assert isinstance(body, dict)+ assert body["role"] == "user"+ assert "Claude socket delivery" in body["content"]+ assert all(+ "private-inbox-token" not in path.read_text()+ for path in tmp_path.rglob("*.json")+ )+ finally:+ record.forwarder.stop()+ store.remove(record)+ thread.join(timeout=1)diff --git a/tests/_cli/test_pair_client.py b/tests/_cli/test_pair_client.pyindex bf18e3f4a5..f663297c1e 100644--- a/tests/_cli/test_pair_client.py+++ b/tests/_cli/test_pair_client.py@@ -5,20 +5,23 @@ import http.clientimport ioimport jsonimport os+import queue+import threadingfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any+from unittest.mock import Mockimport pytestfrom marimo._cli.pair import clientfrom marimo._cli.pair.client import (- AmbiguousSessionError,- NoSessionError,+ AmbiguousNotebookError,+ NoNotebookError,+ NotebookUnsupportedError,PairError,PairInputError,SSEEvent,- StableSessionUnsupportedError,- StaleSessionError,+ StaleNotebookError,)if TYPE_CHECKING:@@ -68,7 +71,7 @@ def _patch_response(def fake_open_response(**kwargs: Any) -> Any:calls.append(kwargs)- return response+ return client.EventStream(response, Mock())monkeypatch.setattr(client, "open_response", fake_open_response)return calls@@ -117,334 +120,319 @@ def test_display_url_removes_credentials_query_and_fragment() -> None:assert client.display_url("http://[::1") == "<invalid URL>"- ("fixture", "expected"),- [- (- "execute-success.sse",- [- SSEEvent("stdout", '{"data":"hello\\n"}'),- SSEEvent(- "done",- '{"success":true,"output":{"mimetype":"text/plain","data":"2"}}',- ),- ],- ),- (- "execute-failure.sse",+def test_iter_sse_reads_cursor_multiline_and_ignores_invalid_ids() -> None:+ assert list(+ client.iter_sse([- SSEEvent("stderr", '{"data":"ValueError: boom\\n"}'),- SSEEvent(- "done",- '{"success":false,"output":{"mimetype":"text/plain","data":""}}',- ),- ],- ),- ],-)-def test_iter_sse_fixtures(fixture: str, expected: list[SSEEvent]) -> None:- assert list(client.iter_sse(io.BytesIO(_fixture(fixture)))) == expected+ b": comment\r\n",+ b"id: cursor-1\r\n",+ b"event: custom\r\n",+ b"data: one\r\n",+ b"data: two\r\n",+ b"\r\n",+ b"id: bad\0cursor\n",+ b"data: three\n",+ b"\n",+ b"id:\n",+ b"data: four\n",+ ]+ )+ ) == [+ SSEEvent("custom", "one\ntwo", "cursor-1"),+ SSEEvent("message", "three", "cursor-1"),+ SSEEvent("message", "four", ""),+ ]-def test_iter_sse_handles_crlf_comments_and_multiline_data() -> None:- lines = [- b": keep-alive\r\n",- b"event: custom\r\n",- b"data: first\r\n",- b"data: second\r\n",- b"\r\n",- ]+def test_event_pump_reports_clean_eof_after_events() -> None:+ event = SSEEvent("custom", "payload", "cursor-one")+ incoming: queue.Queue[SSEEvent | Exception | None] = queue.Queue()+ client.pump_events([event], incoming, threading.Event())+ assert [incoming.get_nowait(), incoming.get_nowait()] == [event, None]+ assert incoming.empty()+- assert list(client.iter_sse(lines)) == [- SSEEvent("custom", "first\nsecond")+ "failure",+ [+ OSError("disconnected"),+ http.client.IncompleteRead(b""),+ ValueError("invalid frame"),+ ],+)+def test_event_pump_reports_failure_then_eof(failure: Exception) -> None:+ event = SSEEvent("custom", "before failure")++ def events() -> Iterator[SSEEvent]:+ yield event+ raise failure++ incoming: queue.Queue[SSEEvent | Exception | None] = queue.Queue()+ client.pump_events(events(), incoming, threading.Event())+ assert [+ incoming.get_nowait(),+ incoming.get_nowait(),+ incoming.get_nowait(),+ ] == [+ event,+ failure,+ None,]+ assert incoming.empty()-def test_iter_sse_dispatches_unterminated_final_record() -> None:- assert list(client.iter_sse([b"data: final"])) == [- SSEEvent("message", "final")- ]+def test_event_pump_cancels_without_draining_a_full_queue() -> None:+ incoming: queue.Queue[SSEEvent | Exception | None] = queue.Queue(maxsize=1)+ queued = SSEEvent("custom", "already queued")+ incoming.put_nowait(queued)+ started = threading.Event()+ stopped = threading.Event()+ def events() -> Iterator[SSEEvent]:+ started.set()+ yield SSEEvent("custom", "blocked by backpressure")-def test_execute_sends_request_and_streams_in_event_order(+ worker = threading.Thread(+ target=client.pump_events,+ args=(events(), incoming, stopped),+ daemon=True,+ )+ worker.start()+ try:+ assert started.wait(timeout=1)+ finally:+ stopped.set()+ worker.join(timeout=1)+ assert not worker.is_alive()+ assert incoming.get_nowait() == queued+ assert incoming.empty()+++def test_open_events_uses_host_headers_and_cursor(monkeypatch: pytest.MonkeyPatch,) -> None:- response = io.BytesIO(- b"event: stdout\n"- b'data: {"data":"out"}\n\n'- b"event: stderr\n"- b'data: {"data":"err"}\n\n'- b"event: done\n"- b'data: {"success":true,"output":{"data":"result"}}\n\n'- )- calls = _patch_response(monkeypatch, response)- records: list[tuple[str, str]] = []- stdout = RecordingStream("stdout", records)- stderr = RecordingStream("stderr", records)-- result = client.execute(- url="https://example.com/base/?access_token=query-token#part",- session_id="session-1",- token="secret-token",- code="print(1)",- stdout=stdout,- stderr=stderr,- stream=True,+ calls = _patch_response(monkeypatch, io.BytesIO())+ client.open_events(+ url="http://localhost:2718/base/api/marimo/v1",+ notebook="nb-one",+ token="private",+ identity="p1_one",+ name="Codex",+ cursor="cursor-1",)-- assert result == client.ExecutionResult(- success=True,- output={"mimetype": "text/plain", "data": "result"},- stdout="",- stderr="",- )- assert records == [- ("stdout", "out"),- ("stdout", "flush"),- ("stderr", "err"),- ("stderr", "flush"),- ("stdout", "result\n"),- ]assert calls == [{- "method": "POST",- "url": "https://example.com/base/api/kernel/execute?access_token=query-token",+ "method": "GET",+ "url": "http://localhost:2718/base/api/marimo/v1/notebooks/nb-one/events?types=custom,attachment","headers": {- "Content-Type": "application/json",- "Marimo-Stable-Session-Id": "session-1",- "Authorization": "Bearer secret-token",+ "Marimo-Attachment-Identity": "p1_one",+ "Marimo-Attachment-Kind": "agent",+ "Marimo-Attachment-Name": "Codex",+ "Authorization": "Bearer private",+ "Last-Event-ID": "cursor-1",},- "body": json.dumps({"code": "print(1)"}).encode(),+ "body": None,+ "read_timeout": 45,}]- assert "secret-token" not in calls[0]["url"]- assert b"secret-token" not in calls[0]["body"]- assert response.closed-def test_execute_omits_authorization_without_token(- monkeypatch: pytest.MonkeyPatch,[email protected]("outcome", ["succeeded", "failed", "interrupted"])[email protected]("stream", [True, False])+def test_execute_host_run_filters_other_runs(+ monkeypatch: pytest.MonkeyPatch, outcome: str, stream: bool) -> None:- response = io.BytesIO(_fixture("execute-success.sse"))- calls = _patch_response(monkeypatch, response)-- client.execute(- url="http://localhost:2718",- session_id="session-1",- token=None,- code="1 + 1",- stdout=io.StringIO(),- stderr=io.StringIO(),- stream=True,- )-- assert len(calls) == 1- assert "Authorization" not in calls[0]["headers"]--- "url",- [- "ftp://localhost/not-http",- "http:///missing-host",- "http://localhost:0",- "http://localhost:not-a-port?access_token=secret",- "http://[::1",- ],-)-def test_open_response_rejects_invalid_url_without_exposing_it(- url: str,-) -> None:- with pytest.raises(PairInputError) as exc_info:- client.open_response(- method="GET",- url=url,- headers={},- body=None,- )-- assert str(exc_info.value) in (- "The server URL is invalid.",- "The server URL must use http or https.",- )- assert "secret" not in str(exc_info.value)---def test_execute_buffers_output_until_done(- monkeypatch: pytest.MonkeyPatch,-) -> None:- stdout = io.StringIO()- stderr = io.StringIO()-- class InspectingResponse(io.BytesIO):- def readline(self, size: int = -1) -> bytes:- line = super().readline(size)- if line == b"event: done\n":- assert stdout.getvalue() == ""- assert stderr.getvalue() == ""- return line-- response = InspectingResponse(_fixture("execute-success.sse"))- calls = _patch_response(monkeypatch, response)+ response = io.BytesIO(_fixture(f"host-run-{outcome}.sse"))+ calls: list[dict[str, Any]] = []+ def open_response(**kwargs: Any) -> client.EventStream:+ calls.append(kwargs)+ if kwargs["method"] == "GET":+ return client.EventStream(response, Mock())+ # The ready frame must be consumed before submission.+ assert response.tell() > 0+ return client.EventStream(io.BytesIO(b'{"id":"run-one"}'), Mock())++ monkeypatch.setattr(client, "open_response", open_response)+ stdout, stderr = io.StringIO(), io.StringIO()result = client.execute(- url="http://localhost:2718",- session_id="session-1",- token=None,- code="1 + 1",+ url="http://localhost:2718/api/marimo/v1",+ notebook_id="nb-one",+ token="private",+ code="print(42)",stdout=stdout,stderr=stderr,- stream=False,+ stream=stream,)-- assert result.success- assert result.stdout == "hello\n"- assert result.stderr == ""- assert result.output == {"mimetype": "text/plain", "data": "2"}- assert stdout.getvalue() == ""- assert stderr.getvalue() == ""- assert len(calls) == 1---def test_execute_returns_unsuccessful_result(- monkeypatch: pytest.MonkeyPatch,-) -> None:- response = io.BytesIO(_fixture("execute-failure.sse"))- calls = _patch_response(monkeypatch, response)- stderr = io.StringIO()-- result = client.execute(- url="http://localhost:2718",- session_id="session-1",- token=None,- code="raise ValueError",- stdout=io.StringIO(),- stderr=stderr,- stream=False,- )-assert result == client.ExecutionResult(- success=False,- output=None,- stdout="",- stderr="ValueError: boom\n",+ outcome == "succeeded",+ {"mimetype": "text/plain", "data": "42"},+ "" if stream else "hello\n",+ "" if stream else "warning\n",+ outcome,)- assert stderr.getvalue() == ""- assert len(calls) == 1---def test_execute_rejects_missing_done(- monkeypatch: pytest.MonkeyPatch,-) -> None:- response = io.BytesIO(b'event: stdout\ndata: {"data":"partial"}\n\n')- calls = _patch_response(monkeypatch, response)-- with pytest.raises(PairError, match="ended before completion"):- client.execute(- url="http://localhost:2718",- session_id="session-1",- token=None,- code="print(1)",- stdout=io.StringIO(),- stderr=io.StringIO(),- stream=True,- )+ assert stdout.getvalue() == ("hello\n42\n" if stream else "")+ assert stderr.getvalue() == ("warning\n" if stream else "")+ assert [call["method"] for call in calls] == ["GET", "POST"]+ assert json.loads(calls[1]["body"]) == {"code": "print(42)"}+ from uuid import UUID- assert len(calls) == 1+ UUID(calls[1]["headers"]["Idempotency-Key"])+ assert response.closed@pytest.mark.parametrize("body",[- b"event: stdout\ndata: not json\n\n",- b'event: done\ndata: {"output":null}\n\n',- b"event: stdout\ndata: []\n\n",+ b"",+ b"event: ready\ndata: {}\n\n",+ b"event: ready\ndata: {}\n\nevent: execution\ndata: invalid\n\n",],- ids=["non_json", "done_without_success", "wrong_shape"],)-def test_execute_treats_malformed_events_as_unconfirmed(+def test_execute_missing_completion_is_unconfirmed(monkeypatch: pytest.MonkeyPatch, body: bytes) -> None:- response = io.BytesIO(body)- _patch_response(monkeypatch, response)+ def open_response(**kwargs: Any) -> client.EventStream:+ return client.EventStream(+ io.BytesIO(+ body if kwargs["method"] == "GET" else b'{"id":"run-one"}'+ ),+ Mock(),+ )- with pytest.raises(PairError, match="ended before completion"):+ monkeypatch.setattr(client, "open_response", open_response)+ with pytest.raises(PairError):client.execute(- url="http://localhost:2718",- session_id="session-1",- token=None,- code="print(1)",+ url="http://localhost:2718/api/marimo/v1",+ notebook_id="nb-one",+ token="private",+ code="1",stdout=io.StringIO(),stderr=io.StringIO(),stream=False,)-def test_execute_keeps_buffered_output_after_read_error([email protected]("stream", [False, True])[email protected]("with_traceback", [False, True])+def test_execution_error_snapshots_are_emitted_once(monkeypatch: pytest.MonkeyPatch,+ stream: bool,+ with_traceback: bool,) -> None:- response = RaisingResponse(- [b"event: stdout\n", b'data: {"data":"partial"}\n', b"\n"],- OSError("connection lost"),+ error: dict[str, object] = {+ "name": "ValueError",+ "message": "<invalid value>",+ }+ expected = "ValueError: <invalid value>\n"+ if with_traceback:+ expected = "Traceback: original cell\n" + expected+ error["traceback"] = {"mimetype": "text/plain", "data": expected}+ frames = [b"event: ready\ndata: {}\n\n"]+ for status in ("concluded", "completed"):+ snapshot = {+ "execution": {+ "id": "execution-one",+ "run_id": "run-one",+ "status": status,+ "outcome": {"kind": "error", "error": error},+ }+ }+ frames.append(+ b"event: execution\ndata: "+ + json.dumps(snapshot).encode()+ + b"\n\n"+ )+ frames.append(+ b'event: run\ndata: {"run":{"id":"run-one","status":"completed","outcome":"failed"}}\n\n')- calls = _patch_response(monkeypatch, response)- stdout = io.StringIO()-- with pytest.raises(PairError, match="ended before completion"):- client.execute(- url="http://localhost:2718",- session_id="session-1",- token=None,- code="print(1)",- stdout=stdout,- stderr=io.StringIO(),- stream=True,+ response = io.BytesIO(b"".join(frames))++ def open_response(**kwargs: Any) -> client.EventStream:+ return client.EventStream(+ response+ if kwargs["method"] == "GET"+ else io.BytesIO(b'{"id":"run-one"}'),+ Mock(),)- assert stdout.getvalue() == "partial"+ monkeypatch.setattr(client, "open_response", open_response)+ stderr = io.StringIO()+ result = client.execute(+ url="http://localhost:2718/api/marimo/v1",+ notebook_id="nb-one",+ token="private",+ code="raise ValueError('<invalid value>')",+ stdout=io.StringIO(),+ stderr=stderr,+ stream=stream,+ )+ assert result == client.ExecutionResult(+ False, None, "", "" if stream else expected, "failed"+ )+ assert stderr.getvalue() == (expected if stream else "")assert response.closed- assert len(calls) == 1-def test_execute_rejects_truncated_http_response(+def test_lost_run_submission_response_is_unknown_and_never_retried(monkeypatch: pytest.MonkeyPatch,) -> None:- response = RaisingResponse([], http.client.IncompleteRead(b"partial"))- _patch_response(monkeypatch, response)+ response = io.BytesIO(b"event: ready\ndata: {}\n\n")+ calls: list[dict[str, Any]] = []++ def open_response(**kwargs: Any) -> client.EventStream:+ calls.append(kwargs)+ if kwargs["method"] == "GET":+ return client.EventStream(response, Mock())+ raise client.PairConnectionError("private transport details")- with pytest.raises(PairError, match="ended before completion"):+ monkeypatch.setattr(client, "open_response", open_response)+ fallback = Mock(+ side_effect=AssertionError("Execution must not be retried")+ )+ monkeypatch.setattr(client, "execute_editor", fallback)+ with pytest.raises(+ PairError, match="before completion was confirmed"+ ) as caught:client.execute(- url="http://localhost:2718",- session_id="session-1",- token=None,- code="print(1)",+ url="http://localhost:2718/api/marimo/v1",+ notebook_id="nb-one",+ token="private",+ code="side_effect()",stdout=io.StringIO(),stderr=io.StringIO(),- stream=True,+ stream=False,)-+ assert type(caught.value) is PairError+ assert "private transport details" not in str(caught.value)+ assert [call["method"] for call in calls] == ["GET", "POST"]+ assert calls[1]["url"].endswith("/notebooks/nb-one/runtime/runs")+ fallback.assert_not_called()assert response.closed-def test_execute_closes_response_after_keyboard_interrupt(- monkeypatch: pytest.MonkeyPatch,+ "url",+ [+ "ftp://user:private-password@localhost?access_token=private-token#private-fragment",+ "http://user:private-password@[?access_token=private-token#private-fragment",+ "http://user:private-password@localhost:99999?access_token=private-token#private-fragment",+ ],+)+def test_open_response_rejects_invalid_url_without_exposing_it(+ url: str,) -> None:- response = RaisingResponse([], KeyboardInterrupt())- calls = _patch_response(monkeypatch, response)-- with pytest.raises(KeyboardInterrupt):- client.execute(- url="http://localhost:2718",- session_id="session-1",- token=None,- code="while True: pass",- stdout=io.StringIO(),- stderr=io.StringIO(),- stream=True,+ with pytest.raises(PairInputError) as caught:+ client.open_response(method="GET", url=url, headers={}, body=None)+ assert all(+ secret not in str(caught.value)+ for secret in (+ "private-password",+ "private-token",+ "private-fragment",+ "user:",)-- assert response.closed- assert len(calls) == 1+ )def test_list_sessions_sends_request_and_parses_response(@@ -457,12 +445,14 @@ def test_list_sessions_sends_request_and_parses_response("session_id": "sess-stable-1","filename": "analysis.py","path": "/work/analysis.py",+ "notebook_id": "nb-analysis","state": "idle",},"session-2": {"session_id": "sess-stable-2","filename": None,"path": None,+ "notebook_id": None,},}).encode()@@ -482,11 +472,13 @@ def test_list_sessions_sends_request_and_parses_response("session_id": "sess-stable-1","filename": "analysis.py","path": "/work/analysis.py",+ "notebook_id": "nb-analysis",},"session-2": {"session_id": "sess-stable-2","filename": None,"path": None,+ "notebook_id": None,},}assert calls == [@@ -531,6 +523,7 @@ def test_list_sessions_omits_authorization_without_token("session-1": {"session_id": "sess-stable","path": "/work/analysis.py",+ "notebook_id": "nb-analysis",}},{@@ -538,6 +531,7 @@ def test_list_sessions_omits_authorization_without_token("session_id": "sess-stable","filename": [],"path": None,+ "notebook_id": None,}},{@@ -552,6 +546,7 @@ def test_list_sessions_omits_authorization_without_token("session_id": None,"filename": None,"path": None,+ "notebook_id": None,}},],@@ -605,13 +600,14 @@ def test_list_sessions_rejects_server_without_stable_ids("session-1": {"filename": "analysis.py","path": "/work/analysis.py",+ "notebook_id": "nb-analysis",}}).encode())_patch_response(monkeypatch, response)- with pytest.raises(StableSessionUnsupportedError):+ with pytest.raises(NotebookUnsupportedError):client.list_sessions(url="http://localhost:2718", token=None)assert response.closed@@ -707,7 +703,7 @@ def test_raise_for_status_maps_invalid_session_id() -> None:500, json.dumps({"detail": "Invalid session id: s_old"}).encode())- with pytest.raises(StaleSessionError, match="Invalid session id"):+ with pytest.raises(StaleNotebookError, match="Invalid session id"):client._raise_for_status(response)assert response.closed@@ -719,7 +715,7 @@ def test_raise_for_status_maps_invalid_stable_session_id() -> None:json.dumps({"detail": "Invalid stable session id: sess-old"}).encode(),)- with pytest.raises(StaleSessionError, match="Invalid stable session id"):+ with pytest.raises(StaleNotebookError, match="Invalid stable session id"):client._raise_for_status(response)assert response.closed@@ -731,7 +727,7 @@ def test_raise_for_status_maps_missing_legacy_header_to_upgrade() -> None:json.dumps({"detail": "Missing Marimo-Session-Id header"}).encode(),)- with pytest.raises(StableSessionUnsupportedError):+ with pytest.raises(NotebookUnsupportedError):client._raise_for_status(response)assert response.closed@@ -769,12 +765,13 @@ def test_resolve_session_returns_only_stable_session_id("session_id": "sess-stable","filename": "analysis.py","path": "/work/analysis.py",+ "notebook_id": "nb-analysis",}},)- assert client.resolve_session(url="http://one", token=None) == (- "sess-stable"+ assert (+ client.resolve_notebook(url="http://one", token=None) == "nb-analysis")@@ -783,8 +780,8 @@ def test_resolve_session_zero_matches() -> None:monkeypatch.setattr(client, "list_sessions", lambda **_kwargs: {})- with pytest.raises(NoSessionError, match="No running session") as exc_info:- client.resolve_session(+ with pytest.raises(NoNotebookError, match="No host notebook") as exc_info:+ client.resolve_notebook(url="http://user:password@one?access_token=secret",token=None,)@@ -802,19 +799,136 @@ def test_resolve_session_many_matches("list_sessions",lambda **_kwargs: {"routing-b": {- "session_id": "sess-b",+ "notebook_id": "sess-b","filename": "nb.py","path": "/b/nb.py",},"routing-a": {- "session_id": "sess-a",+ "notebook_id": "sess-a","filename": "nb.py","path": "/a/nb.py",},},)- with pytest.raises(AmbiguousSessionError) as exc_info:- client.resolve_session(url="http://one", token=None)+ with pytest.raises(AmbiguousNotebookError) as exc_info:+ client.resolve_notebook(url="http://one", token=None)assert exc_info.value.candidates == ("sess-a", "sess-b")+++def _host_record(+ path: Path, *, url: str, started: float | None = None+) -> None:+ from datetime import datetime, timezone++ import msgspec+ import psutil++ from marimo._core import protocol++ path.write_bytes(+ msgspec.json.encode(+ protocol.HostRecord(+ version=1,+ process=protocol.Process(+ pid=os.getpid(),+ started_at=datetime.fromtimestamp(+ psutil.Process().create_time()+ if started is None+ else started,+ tz=timezone.utc,+ ),+ ),+ name="marimo",+ url=url,+ token="private-host-token",+ )+ )+ )+ path.chmod(0o600)+++def test_resolve_host_skips_stale_and_malformed_records(+ tmp_path: Path,+) -> None:+ _host_record(+ tmp_path / "a-stale.json",+ url="http://127.0.0.1:2718/base/api/marimo/v1",+ started=1,+ )+ (tmp_path / "b-malformed.json").write_text("{}")+ _host_record(+ tmp_path / "c-live.json",+ url="http://127.0.0.1:2718/base/api/marimo/v1",+ )+ result = client.resolve_host("http://localhost:2718/base/", root=tmp_path)+ assert result == client.HostEndpoint(+ "http://127.0.0.1:2718/base/api/marimo/v1", "private-host-token"+ )+ assert "private-host-token" not in repr(result)++[email protected](os.name != "posix", reason="POSIX private file validation")+ "kind", ["public", "symlink", "wrong-port", "wrong-base"]+)+def test_resolve_host_rejects_unsafe_or_unmatched_records(+ tmp_path: Path, kind: str+) -> None:+ record = tmp_path / "record.json"+ _host_record(record, url="http://127.0.0.1:2718/api/marimo/v1")+ selected = "http://localhost:2718"+ if kind == "public":+ record.chmod(0o644)+ elif kind == "symlink":+ record.rename(tmp_path / "record.private")+ record.symlink_to(tmp_path / "record.private")+ elif kind == "wrong-port":+ selected = "http://localhost:2719"+ else:+ selected += "/base"+ with pytest.raises(PairError, match="local edit server"):+ client.resolve_host(selected, root=tmp_path)+++def test_resolve_notebook_filters_unsaved_and_deduplicates(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(+ client,+ "list_sessions",+ lambda **_: {+ "one": {"notebook_id": "nb-one"},+ "two": {"notebook_id": None},+ "three": {"notebook_id": "nb-one"},+ },+ )+ assert (+ client.resolve_notebook(url="http://localhost:2718", token=None)+ == "nb-one"+ )+++ ("problem", "error"),+ [+ ("no-runtime", client.NoRuntimeError),+ ("conflict", client.RunConflictError),+ ],+)+def test_host_problem_types_map_to_cli_errors(+ problem: str, error: type[PairError]+) -> None:+ response = FakeStatusResponse(+ 409,+ json.dumps(+ {+ "type": f"tag:marimo.io,2026:host/{problem}",+ "detail": "host detail",+ }+ ).encode(),+ )+ with pytest.raises(error, match="host detail"):+ client._raise_for_status(response)+ assert response.closeddiff --git a/tests/_cli/test_pair_delivery.py b/tests/_cli/test_pair_delivery.pynew file mode 100644index 0000000000..8d48c54200--- /dev/null+++ b/tests/_cli/test_pair_delivery.py@@ -0,0 +1,717 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import json+import os+import subprocess+import sys+import tempfile+from pathlib import Path+from unittest.mock import Mock, patch++import pytest++from marimo._cli.pair.artifacts import AgentMessageFiles, inbox_message+from marimo._cli.pair.client import PairError, PairInputError+from marimo._cli.pair.connection import (+ Connection,+ ConnectionStore,+ connection_identity,+)+from marimo._cli.pair.delivery import DeliveryTarget, ProcessHandle+from marimo._cli.pair.harnesses import detect_target+from marimo._cli.pair.harnesses.claude import ClaudeHarness+from marimo._cli.pair.harnesses.codex import CodexHarness+++def codex_ready(monkeypatch: pytest.MonkeyPatch) -> Mock:+ check = Mock()+ monkeypatch.setattr(CodexHarness, "check", check)+ return check+++def owner() -> ProcessHandle:+ return ProcessHandle.capture(os.getpid())+++ ("env", "address"),+ [+ ({}, None),+ ({"CODEX_SESSION_ID": "root", "CODEX_THREAD_ID": "child"}, "root"),+ ({"CODEX_THREAD_ID": "child"}, "child"),+ ({"CODEX_SESSION_ID": "", "CODEX_THREAD_ID": "child"}, "child"),+ ],+)+def test_codex_detect(+ env: dict[str, str],+ address: str | None,+ monkeypatch: pytest.MonkeyPatch,+ owner: ProcessHandle,+ codex_ready: Mock,+) -> None:+ import psutil++ parent = Mock(pid=owner.pid)+ parent.name.return_value = "codex"+ parent.cmdline.return_value = ["codex"]+ monkeypatch.setattr(psutil.Process, "parents", lambda _: [parent])+ assert CodexHarness().detect(env) == (+ None+ if address is None+ else DeliveryTarget("codex", address, "Codex", process=owner)+ )+ assert codex_ready.call_count == (1 if address is not None else 0)+++ "args",+ [+ ["codex", "app-server", "--listen", "stdio://"],+ ["codex", "--no-daemon"],+ ],+)+def test_codex_refuses_embedded_process(+ args: list[str], monkeypatch: pytest.MonkeyPatch+) -> None:+ import psutil++ parent = Mock()+ parent.name.return_value = "codex"+ parent.cmdline.return_value = args+ monkeypatch.setattr(psutil.Process, "parents", lambda _: [parent])+ with pytest.raises(PairInputError, match="shared daemon"):+ CodexHarness().detect({"CODEX_SESSION_ID": "root"})+++def test_no_inbox_and_no_owner(monkeypatch: pytest.MonkeyPatch) -> None:+ import psutil++ with pytest.raises(PairInputError, match="No supported inbox"):+ detect_target({}, None)+ monkeypatch.setattr(psutil.Process, "parents", lambda _: [])+ with pytest.raises(PairInputError, match="native Codex session"):+ detect_target({"CODEX_THREAD_ID": "thread"}, None)+++def test_explicit_pid_keeps_recipient_and_skips_ancestor_detection(+ monkeypatch: pytest.MonkeyPatch, owner: ProcessHandle, codex_ready: Mock+) -> None:+ import psutil++ monkeypatch.setattr(+ psutil.Process,+ "parents",+ Mock(side_effect=AssertionError("Explicit PID must bypass discovery")),+ )+ _, target = detect_target(+ {"CODEX_THREAD_ID": "thread"}, "codex", pid=owner.pid+ )+ assert target == DeliveryTarget("codex", "thread", "Codex", owner)+ codex_ready.assert_called_once()++[email protected]("pid", [0, -1])+def test_explicit_pid_must_be_positive(pid: int) -> None:+ with pytest.raises(PairInputError, match="positive process ID"):+ detect_target({"CODEX_THREAD_ID": "thread"}, "codex", pid=pid)+++def test_explicit_pid_must_be_running(+ monkeypatch: pytest.MonkeyPatch, owner: ProcessHandle+) -> None:+ monkeypatch.setattr(ProcessHandle, "alive", lambda _: False)+ with pytest.raises(PairInputError, match="not running"):+ detect_target({"CODEX_THREAD_ID": "thread"}, "codex", pid=owner.pid)+++def test_explicit_pid_inspection_failure(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ import psutil++ monkeypatch.setattr(+ ProcessHandle, "capture", Mock(side_effect=psutil.NoSuchProcess(123))+ )+ with pytest.raises(PairInputError, match="Could not inspect"):+ detect_target({"CODEX_THREAD_ID": "thread"}, "codex", pid=123)+++ ("status", "code", "ok"),+ [("running", 0, True), ("stopped", 0, False), ("running", 1, False)],+)+def test_daemon_probe(+ status: str, code: int, ok: bool, monkeypatch: pytest.MonkeyPatch+) -> None:+ run = Mock(+ return_value=subprocess.CompletedProcess(+ [], code, json.dumps({"status": status}).encode()+ )+ )+ monkeypatch.setattr(subprocess, "run", run)+ if ok:+ CodexHarness().check()+ else:+ with pytest.raises(PairInputError, match="daemon is not running"):+ CodexHarness().check()+ assert run.call_args_list[0].args[0] == [+ "codex",+ "app-server",+ "daemon",+ "version",+ ]+ if ok:+ assert run.call_args_list[1].args[0] == ["codex", "queue", "--help"]++[email protected]("stdout", [b"bad", b"[]", b"null"])+def test_malformed_daemon_probe(+ stdout: bytes, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(+ subprocess,+ "run",+ Mock(return_value=subprocess.CompletedProcess([], 0, stdout)),+ )+ with pytest.raises(PairInputError):+ CodexHarness().check()+++def test_codex_send_preserves_message(monkeypatch: pytest.MonkeyPatch) -> None:+ run = Mock(return_value=subprocess.CompletedProcess([], 0, b"queued"))+ monkeypatch.setattr(subprocess, "run", run)+ message = 'line 1\n"quotes"; $(must not execute)'+ CodexHarness().open_inbox(DeliveryTarget("codex", "thread", "Codex")).send(+ message+ )+ assert run.call_args.args[0] == [+ "codex",+ "queue",+ "--thread",+ "thread",+ "--message",+ message,+ ]+ assert "shell" not in run.call_args.kwargs+++ "failure", [OSError("secret"), subprocess.TimeoutExpired("secret", 15)]+)+def test_codex_send_failure_does_not_leak(+ failure: Exception, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(subprocess, "run", Mock(side_effect=failure))+ with pytest.raises(PairError, match="Could not deliver") as error:+ CodexHarness().open_inbox(+ DeliveryTarget("codex", "thread", "Codex")+ ).send("message")+ assert "secret" not in str(error.value)+++def test_process_identity_guards_pid_reuse(owner: ProcessHandle) -> None:+ assert owner.alive()+ reused = ProcessHandle(owner.pid, owner.started - 1)+ assert not reused.alive()+ reused.stop()+ assert owner.alive()+ assert (+ not CodexHarness()+ .open_inbox(DeliveryTarget("codex", "thread", "Codex"))+ .alive()+ )+++def test_process_stop() -> None:+ process = subprocess.Popen(+ [sys.executable, "-c", "import time; time.sleep(60)"]+ )+ try:+ handle = ProcessHandle.capture(process.pid)+ assert handle.alive()+ handle.stop()+ assert not handle.alive()+ finally:+ if process.poll() is None:+ process.kill()+ process.wait()+++def record(owner: ProcessHandle, conversation: str = "thread") -> Connection:+ return Connection(+ 1,+ connection_identity("s_one", "codex", conversation),+ "s_one",+ "codex",+ owner.pid,+ owner.started,+ owner.pid,+ owner.started,+ 1.0,+ )+++def test_connection_roundtrip_and_replacement(+ tmp_path: Path, owner: ProcessHandle+) -> None:+ store = ConnectionStore(tmp_path)+ old = record(owner)+ with store.locked(old.identity):+ store.save(old)+ assert store.load(old.identity) == old+ assert store.select("s_one", kind="codex", conversation="thread") == old+ replacement = record(ProcessHandle(owner.pid, owner.started + 1))+ store.save(replacement)+ store.remove(old)+ assert store.load(old.identity) == replacement+ assert set(json.loads(store.path(old.identity).read_bytes())) == {+ "version",+ "identity",+ "notebook",+ "harness_kind",+ "harness_pid",+ "harness_start",+ "forwarder_pid",+ "forwarder_start",+ "created_at",+ }+ if os.name == "posix":+ assert store.path(old.identity).stat().st_mode & 0o777 == 0o600+ store.remove(replacement)+ assert store.load(old.identity) is None+++def test_connection_rejects_ambiguous_and_corrupt(+ tmp_path: Path, owner: ProcessHandle+) -> None:+ store = ConnectionStore(tmp_path)+ first = record(owner)+ store.save(first)+ store.save(record(owner, "other"))+ with pytest.raises(PairInputError, match="Several"):+ store.select("s_one", kind="unknown", conversation=None)+ store.path(first.identity).write_text("{}")+ with pytest.raises(PairInputError, match="Invalid Pair connection"):+ store.load(first.identity)+ with pytest.raises(PairInputError, match="Invalid Pair attachment"):+ store.path("../escape")+++def test_corrupt_connection_recovery_never_signals(+ tmp_path: Path, owner: ProcessHandle, monkeypatch: pytest.MonkeyPatch+) -> None:+ store = ConnectionStore(tmp_path)+ current = record(owner)+ store.path(current.identity).write_text('{"forwarder_pid": 123}')+ stop = Mock(side_effect=AssertionError("No valid process ownership"))+ monkeypatch.setattr(ProcessHandle, "stop", stop)+ with store.locked(current.identity):+ store.stop(current.identity)+ store.save(current)+ assert store.load(current.identity) == current+ stop.assert_not_called()+++def test_selection_skips_unrelated_corruption(+ tmp_path: Path, owner: ProcessHandle+) -> None:+ store = ConnectionStore(tmp_path)+ current = record(owner)+ store.save(current)+ store.path(connection_identity("other", "codex", "bad")).write_text("{}")+ assert store.select("s_one", kind="unknown", conversation=None) == current+++def test_connection_io_error_does_not_remove_record(+ tmp_path: Path, owner: ProcessHandle, monkeypatch: pytest.MonkeyPatch+) -> None:+ store = ConnectionStore(tmp_path)+ current = record(owner)+ store.save(current)+ monkeypatch.setattr(Path, "read_bytes", Mock(side_effect=PermissionError))+ with (+ pytest.raises(PairInputError, match="Could not read"),+ store.locked(current.identity),+ ):+ store.stop(current.identity)+ assert store.path(current.identity).exists()+++def test_stop_validated_zombie_does_not_wait(+ owner: ProcessHandle, monkeypatch: pytest.MonkeyPatch+) -> None:+ import psutil++ zombie = Mock()+ zombie.create_time.return_value = owner.started+ zombie.is_running.return_value = True+ zombie.status.return_value = psutil.STATUS_ZOMBIE+ monkeypatch.setattr(psutil, "Process", Mock(return_value=zombie))+ owner.stop()+ zombie.terminate.assert_not_called()+ zombie.wait.assert_not_called()+++def test_stop_process_that_becomes_a_zombie(+ owner: ProcessHandle, monkeypatch: pytest.MonkeyPatch+) -> None:+ import psutil++ process = Mock()+ process.create_time.return_value = owner.started+ process.is_running.return_value = True+ process.status.side_effect = [psutil.STATUS_RUNNING, psutil.STATUS_ZOMBIE]+ process.wait.side_effect = psutil.TimeoutExpired(5)+ monkeypatch.setattr(psutil, "Process", Mock(return_value=process))+ owner.stop()+ process.terminate.assert_called_once()+ process.kill.assert_not_called()+++PAYLOADS: list[object] = [+ {+ "type": "cell-output",+ "code": "1/0",+ "output": {"traceback": "full\ntraceback"},+ },+ {"lens": [1, 2]},+ "plain text",+ [1, "two"],+ 42,+ 1.5,+ True,+ None,+]++[email protected]("payload", PAYLOADS)+def test_small_payloads(payload: object) -> None:+ files = AgentMessageFiles()+ message = inbox_message(+ payload, notebook="s_one", budget=8192, files=files+ )+ body = message.split("\n", 1)[1]+ assert (body if isinstance(payload, str) else json.loads(body)) == payload+ assert files.directory is None++[email protected]("payload", PAYLOADS)+def test_full_json_dump_roundtrip(payload: object, tmp_path: Path) -> None:+ files = AgentMessageFiles()+ files.directory = tmp_path+ path = files.write(payload)+ assert json.loads(path.read_text(encoding="utf-8")) == payload+ assert path.is_absolute()+ assert files.write(payload) != path+ assert json.loads(path.read_text(encoding="utf-8")) == payload+++ "payload",+ [+ "😀é" * 10000,+ {"traceback": "line\n" * 10000},+ ["long" * 10000],+ {"lens": "x" * 10000},+ ],+)+def test_oversized_dump_retained(payload: object, tmp_path: Path) -> None:+ files = AgentMessageFiles()+ files.directory = tmp_path+ message = inbox_message(payload, notebook="s_one", budget=512, files=files)+ assert len(message.encode("utf-8")) <= 512+ reference = Path(+ message.rsplit("Complete JSON agent message: ", 1)[1][:-1]+ )+ del files+ assert json.loads(reference.read_text(encoding="utf-8")) == payload+++def test_dump_failure_does_not_send_broken_reference(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(+ tempfile, "mkdtemp", Mock(side_effect=OSError("disk full"))+ )+ with pytest.raises(PairError, match="No shortened message was sent"):+ inbox_message(+ "x" * 20000,+ notebook="s_one",+ budget=512,+ files=AgentMessageFiles(),+ )+++def test_cleanup_only_owned_aged_files(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(tempfile, "gettempdir", lambda: str(tmp_path))+ files = AgentMessageFiles()+ path = files.write({"full": "content"})+ assert files.directory is not None+ unowned = files.directory / "keep.txt"+ unowned.write_text("keep")+ old = files.write("old")+ os.utime(old, (1, 1))+ AgentMessageFiles.cleanup(now=100000)+ assert not old.exists()+ assert path.exists()+ assert unowned.exists()+++def test_cleanup_removed_directory_is_replaced(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(tempfile, "gettempdir", lambda: str(tmp_path))+ files = AgentMessageFiles()+ old = files.write("old")+ directory = old.parent+ os.utime(old, (1, 1))+ os.utime(directory, (1, 1))+ AgentMessageFiles.cleanup(now=100000)+ assert not directory.exists()+ new = files.write("new")+ assert new.parent != directory+ assert json.loads(new.read_text()) == "new"+ assert new.stat().st_mode & 0o777 == 0o600+++def test_replaced_payload_directory_is_not_followed(tmp_path: Path) -> None:+ files = AgentMessageFiles()+ original = files.write("old")+ directory = original.parent+ original.unlink()+ directory.rmdir()+ try:+ directory.symlink_to(tmp_path, target_is_directory=True)+ except OSError:+ pytest.skip("Symlinks unavailable")+ try:+ with pytest.raises(PairError, match="No shortened message"):+ files.write("must not reach the replacement")+ assert list(tmp_path.iterdir()) == []+ finally:+ directory.unlink()+++def test_nul_and_surrogate_text() -> None:+ message = inbox_message(+ "null\0\ud800", notebook="s", budget=512, files=AgentMessageFiles()+ )+ assert "\0" not in message+ assert "\\u0000" in message+ message.encode("utf-8")+++def test_windows_uses_native_executable(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ run = Mock(return_value=subprocess.CompletedProcess([], 0, b"queued"))+ monkeypatch.setattr(subprocess, "run", run)+ monkeypatch.setattr(sys, "platform", "win32")+ text = 'unicode 😀 & | "quotes" %PATH%'+ CodexHarness().open_inbox(DeliveryTarget("codex", "thread", "Codex")).send(+ text+ )+ assert run.call_args.args[0] == [+ "codex.exe",+ "queue",+ "--thread",+ "thread",+ "--message",+ text,+ ]+++def test_missing_queue_support(monkeypatch: pytest.MonkeyPatch) -> None:+ run = Mock(+ side_effect=[+ subprocess.CompletedProcess([], 0, b'{"status":"running"}'),+ subprocess.CompletedProcess([], 1, b"unsupported"),+ ]+ )+ monkeypatch.setattr(subprocess, "run", run)+ with pytest.raises(PairInputError, match="queue support"):+ CodexHarness().check()+++def test_windows_reference_budget(monkeypatch: pytest.MonkeyPatch) -> None:+ from pathlib import PureWindowsPath++ files = AgentMessageFiles()+ path = PureWindowsPath("C:/Users/Name With Spaces/Temp/😀/handoff.json")+ monkeypatch.setattr(files, "write", Mock(return_value=path))+ message = inbox_message("😀" * 1000, notebook="s", budget=512, files=files)+ assert str(path) in message+ assert len(message.encode("utf-8")) <= 512+++def test_windows_lock_releases_on_error(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ from types import SimpleNamespace++ locking = Mock()+ monkeypatch.setitem(+ sys.modules,+ "msvcrt",+ SimpleNamespace(locking=locking, LK_NBLCK=1, LK_UNLCK=2),+ )+ monkeypatch.setattr(sys, "platform", "win32")+ store = ConnectionStore(tmp_path)+ with (+ pytest.raises(RuntimeError),+ store.locked(connection_identity("s", "codex", "thread")),+ ):+ raise RuntimeError("release the lock")+ assert [call.args[1:] for call in locking.call_args_list] == [+ (1, 1),+ (2, 1),+ ]+++def test_registry_nested_refusal_and_explicit_selection(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from marimo._cli.pair import harnesses++ codex = Mock(kind="codex")+ codex.detect.return_value = DeliveryTarget("codex", "thread", "Codex")+ other = Mock(kind="other")+ other.detect.return_value = DeliveryTarget("other", "inbox", "Other")+ monkeypatch.setattr(+ harnesses, "registered_harnesses", lambda: [codex, other]+ )+ with pytest.raises(PairInputError, match="Nested harnesses"):+ detect_target({}, None)+ assert detect_target({}, "codex") == (codex, codex.detect.return_value)+++def test_identity_uses_registered_adapters_and_refuses_ambiguity(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from marimo._cli.pair import harnesses++ codex = Mock(kind="codex")+ other = Mock(kind="other")+ codex.identity.return_value = None+ other.identity.return_value = "other-thread"+ monkeypatch.setattr(+ harnesses, "registered_harnesses", lambda: [codex, other]+ )+ assert harnesses.environment_identity({}) == ("other", "other-thread")+ codex.identity.return_value = "codex-thread"+ with pytest.raises(PairInputError, match="Nested harnesses"):+ harnesses.environment_identity({})+ assert harnesses.environment_identity({}, "codex") == (+ "codex",+ "codex-thread",+ )+ other.identity.side_effect = PairInputError("Unresolved conversation")+ with pytest.raises(PairInputError, match="Unresolved conversation"):+ harnesses.environment_identity({})+ codex.identity.return_value = None+ with pytest.raises(PairInputError, match="No codex conversation"):+ harnesses.environment_identity({}, "codex")+++ ("env", "message"),+ [+ ({"CLAUDE_PID": "123"}, "inbox socket"),+ ({"CLAUDE_CODE_MESSAGING_SOCKET": ""}, "inbox socket"),+ ({"CLAUDE_CODE_MESSAGING_TOKEN": "private-token"}, "inbox socket"),+ ({"CODEX_SESSION_ID": ""}, "conversation ID"),+ ({"CODEX_THREAD_ID": ""}, "conversation ID"),+ ],+)+def test_unresolved_native_context_cannot_detach_another_conversation(+ env: dict[str, str],+ message: str,+ tmp_path: Path,+ owner: ProcessHandle,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from click.testing import CliRunner++ from marimo._cli.pair import commands++ store = ConnectionStore(tmp_path)+ other = record(owner, "another-conversation")+ store.save(other)+ monkeypatch.setattr(commands, "ConnectionStore", lambda: store)+ stop = Mock(+ side_effect=AssertionError("Unresolved identity cannot stop a process")+ )+ monkeypatch.setattr(ProcessHandle, "stop", stop)+ with patch.dict(os.environ, env, clear=True):+ result = CliRunner().invoke(commands.detach, ["--notebook", "s_one"])+ assert result.exit_code == 1+ assert message in result.output+ assert "private-token" not in result.output+ assert store.load(other.identity) == other+ stop.assert_not_called()+++def test_explicit_harness_ignores_unresolved_inherited_harness() -> None:+ from marimo._cli.pair.harnesses import environment_identity++ assert environment_identity(+ {"CLAUDE_PID": "123", "CODEX_SESSION_ID": "thread-one"}, "codex"+ ) == ("codex", "thread-one")+ assert environment_identity(+ {+ "CODEX_THREAD_ID": "",+ "CLAUDE_CODE_MESSAGING_SOCKET": "/native/inbox",+ },+ "claude",+ ) == ("claude", "/native/inbox")+ assert ClaudeHarness().identity({}) is None+ assert CodexHarness().detect({}) is None+++def test_pair_lock_rejects_symlink_without_modifying_target(+ tmp_path: Path,+) -> None:+ store = ConnectionStore(tmp_path / "connections")+ store.root.mkdir()+ target = tmp_path / "target"+ target.write_text("unchanged")+ identity = connection_identity("notebook", "codex", "thread")+ try:+ store.path(identity).with_suffix(".lock").symlink_to(target)+ except OSError:+ pytest.skip("Symlinks unavailable")+ with pytest.raises(OSError, match="symlink"), store.locked(identity):+ pytest.fail("The lock must reject symlinks")+ assert target.read_text() == "unchanged"+++ "message", ["division by zero", "division by zero" * 1000]+)+def test_delivery_does_not_add_error_instructions(+ message: str, tmp_path: Path+) -> None:+ payload = {+ "type": "cell-output",+ "cell_id": "vblA",+ "code": "average([])",+ "output": {"type": "error", "message": message},+ }+ files = AgentMessageFiles()+ files.directory = tmp_path+ text = inbox_message(payload, notebook="s_one", budget=512, files=files)+ assert (+ text.split("\n", 1)[0] == "Agent message from marimo (notebook s_one)."+ )+ assert "Fix reported notebook errors" not in text+ assert len(text.encode("utf-8")) <= 512+ if "Complete JSON agent message: " in text:+ path = Path(text.rsplit("Complete JSON agent message: ", 1)[1][:-1])+ assert json.loads(path.read_text(encoding="utf-8")) == payload+ else:+ assert json.loads(text.split("\n", 1)[1]) == payloaddiff --git a/tests/_cli/test_pair_delivery_integration.py b/tests/_cli/test_pair_delivery_integration.pynew file mode 100644index 0000000000..295b405cec--- /dev/null+++ b/tests/_cli/test_pair_delivery_integration.py@@ -0,0 +1,332 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import json+import os+import queue+import subprocess+import sys+import threading+import time+import urllib.request+from pathlib import Path++import msgspec+import pytest+from click.testing import CliRunner++from marimo._cli.cli import main as cli_main+from marimo._cli.pair import commands+from marimo._cli.pair.client import iter_sse, open_events, resolve_host+from marimo._cli.pair.connection import ConnectionStore, connection_identity+from marimo._cli.pair.delivery import DeliveryTarget, ProcessHandle+from marimo._cli.pair.forwarder import ForwarderConfig+from tests._cli._pair_server import pair_test_server+++def wait_messages(path: Path, count: int) -> list[dict[str, str]]:+ deadline = time.monotonic() + 10+ while time.monotonic() < deadline:+ try:+ messages = [+ json.loads(line) for line in path.read_text().splitlines()+ ]+ if len(messages) >= count:+ return messages+ except (FileNotFoundError, ValueError):+ pass+ time.sleep(0.05)+ raise AssertionError(+ "The detached forwarder did not deliver the expected messages."+ )+++ os.name != "posix", reason="The stub executable uses a POSIX shebang."+)+def test_detached_delivery_replacement_and_files(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ inbox = tmp_path / "inbox.jsonl"+ binary = tmp_path / "bin" / "codex"+ binary.parent.mkdir()+ binary.write_text(+ f"#!{sys.executable}\n"+ "import json, sys\n"+ "if sys.argv[1:4] == ['app-server', 'daemon', 'version']:\n"+ " print(json.dumps({'status': 'running'}))\n"+ "elif sys.argv[1:] == ['queue', '--help']:\n"+ " print('Queue help')\n"+ "else:\n"+ f" with open({str(inbox)!r}, 'a', encoding='utf-8') as output:\n"+ " output.write(json.dumps({'thread': sys.argv[3], 'message': sys.argv[5]}) + '\\n')\n"+ )+ binary.chmod(0o700)+ monkeypatch.setenv(+ "PATH", f"{binary.parent}{os.pathsep}{os.environ['PATH']}"+ )+ store = ConnectionStore(tmp_path / "state" / "connections-v1")+ monkeypatch.setattr(commands, "ConnectionStore", lambda: store)+ owner = ProcessHandle.capture(os.getpid())+ runner = CliRunner()+ records = []+ with pair_test_server(tmp_path) as server:+ arguments = [+ "--url",+ server.url,+ "--notebook",+ server.notebook_id,+ ]+ connection_arguments = [+ *arguments,+ "--harness",+ "codex",+ "--pid",+ str(owner.pid),+ ]+ try:+ for thread in ("first", "second"):+ monkeypatch.setenv("CODEX_SESSION_ID", thread)+ result = runner.invoke(+ cli_main, ["pair", "connect", *connection_arguments]+ )+ assert result.exit_code == 0, result.output+ record = store.load(+ connection_identity(server.notebook_id, "codex", thread)+ )+ assert record is not None+ assert (record.harness_pid, record.harness_start) == (+ owner.pid,+ owner.started,+ )+ assert record.forwarder.alive()+ records.append(record)++ def send(payload: object) -> None:+ request = urllib.request.Request(+ f"{server.url}/api/pair/notebooks/{server.stable_session_id}/messages",+ data=json.dumps(payload).encode("utf-8"),+ headers={"Content-Type": "application/json"},+ method="POST",+ )+ with urllib.request.urlopen(request, timeout=5) as response:+ assert response.status == 202++ send(+ {+ "type": "cell-output",+ "code": "1/0",+ "output": {+ "message": "division by zero",+ "traceback": "full\ntraceback",+ },+ }+ )+ first = wait_messages(inbox, 2)+ assert {message["thread"] for message in first} == {+ "first",+ "second",+ }+ assert first[0]["message"] == first[1]["message"]++ large = {"lens": "😀" * 10000}+ send(large)+ messages = wait_messages(inbox, 4)+ references = []+ for message in messages[2:]:+ assert len(message["message"].encode("utf-8")) <= 8192+ path = Path(+ message["message"].rsplit(+ "Complete JSON agent message: ", 1+ )[1][:-1]+ )+ assert json.loads(path.read_text(encoding="utf-8")) == large+ references.append(path)+ assert references[0] != references[1]++ previous = records[-1]+ result = runner.invoke(+ cli_main, ["pair", "connect", *connection_arguments]+ )+ assert result.exit_code == 0, result.output+ replacement = store.load(previous.identity)+ assert replacement is not None+ assert replacement.forwarder.alive()+ records.append(replacement)+ assert not previous.forwarder.alive()++ result = runner.invoke(+ cli_main,+ ["pair", "execute", *arguments, "-c", "print('connected')"],+ )+ assert result.exit_code == 0, result.output+ assert json.loads(result.stdout)["stdout"] == "connected\n"++ replacement.forwarder.stop()+ result = runner.invoke(+ cli_main,+ [+ "pair",+ "execute",+ *arguments,+ "-c",+ "print('still executes')",+ ],+ )+ assert result.exit_code == 0, result.output+ result = runner.invoke(+ cli_main,+ ["pair", "detach", "--notebook", server.notebook_id],+ )+ assert result.exit_code == 0, result.output+ assert store.load(replacement.identity) is None+ for path in references:+ assert json.loads(path.read_text(encoding="utf-8")) == large+ finally:+ for record in records:+ record.forwarder.stop()+ with store.locked(record.identity):+ store.remove(record)+++def test_failed_start_removes_record(tmp_path: Path) -> None:+ from marimo._cli.pair.client import PairError+ from marimo._cli.pair.forwarder import ForwarderConfig, start_forwarder++ identity = connection_identity("s_one", "codex", "thread")+ config = ForwarderConfig(+ "http://127.0.0.1:1",+ "s_one",+ identity,+ "private-token",+ DeliveryTarget(+ "codex",+ "thread",+ "Codex",+ process=ProcessHandle.capture(os.getpid()),+ ),+ )+ store = ConnectionStore(tmp_path)+ with store.locked(identity):+ with pytest.raises(PairError, match="could not attach"):+ start_forwarder(config, store)+ assert store.load(identity) is None+ assert "private-token" not in "".join(+ path.read_text() for path in tmp_path.glob("*.json")+ )+++def test_subprocess_reconnect_replays_messages_and_server_detach(+ tmp_path: Path,+) -> None:+ with pair_test_server(tmp_path) as server:+ host = resolve_host(server.url)+ observer = open_events(+ url=host.url,+ notebook=server.notebook_id,+ token=host.token,+ identity="observer",+ name="Replay observer",+ read_timeout=10,+ )+ events = iter_sse(observer)+ for event in events:+ if event.name == "ready":+ break+ config = ForwarderConfig(+ host.url,+ server.notebook_id,+ "replay-test",+ host.token,+ DeliveryTarget(+ "test",+ "replay-conversation",+ "Replay test",+ process=ProcessHandle.capture(os.getpid()),+ ),+ )+ process = subprocess.Popen(+ [sys.executable, "-m", "tests._cli._pair_replay", str(tmp_path)],+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ )+ assert process.stdin is not None+ process.stdin.write(msgspec.json.encode(config))+ process.stdin.close()+ process.stdin = None++ def attachment() -> str:+ for event in events:+ if event.name == "attachment":+ value = json.loads(event.data)["attachment"]+ if value.get("identity") == config.identity:+ identity = value["id"]+ assert isinstance(identity, str)+ return identity+ raise AssertionError("No forwarder attachment")++ def send(message: str) -> None:+ request = urllib.request.Request(+ f"{server.url}/api/pair/notebooks/{server.stable_session_id}/messages",+ method="POST",+ data=json.dumps(message).encode(),+ headers={"Content-Type": "application/json"},+ )+ with urllib.request.urlopen(request, timeout=5) as response:+ assert response.status == 202++ try:+ assert process.stdout is not None+ output = process.stdout+ startup: queue.Queue[bytes] = queue.Queue(maxsize=1)+ threading.Thread(+ target=lambda: startup.put(output.readline()), daemon=True+ ).start()+ assert startup.get(timeout=10) == b"attached\n"+ first_id = attachment()+ send("before drop")+ wait_messages(tmp_path / "inbox.jsonl", 1)+ (tmp_path / "drop").touch()+ deadline = time.monotonic() + 10+ while not (tmp_path / "reconnecting.json").exists():+ if process.poll() is not None:+ _, stderr = process.communicate(timeout=5)+ raise AssertionError(stderr.decode())+ if time.monotonic() >= deadline:+ raise AssertionError("Forwarder did not reconnect")+ time.sleep(0.01)+ cursor = json.loads((tmp_path / "reconnecting.json").read_text())[+ "cursor"+ ]+ assert isinstance(cursor, str)+ assert cursor.isdigit()+ # The observer keeps the producer guard satisfied during the gap.+ send("during gap")+ (tmp_path / "resume").touch()+ second_id = attachment()+ assert second_id != first_id+ wait_messages(tmp_path / "inbox.jsonl", 2)+ send("after reconnect")+ messages = wait_messages(tmp_path / "inbox.jsonl", 3)+ assert [+ message["message"].rsplit("\n", 1)[1] for message in messages+ ] == ["before drop", "during gap", "after reconnect"]+ request = urllib.request.Request(+ f"{server.url}/api/pair/notebooks/{server.stable_session_id}/attachments/detach",+ method="POST",+ data=json.dumps({"attachment_id": second_id}).encode(),+ headers={"Content-Type": "application/json"},+ )+ with urllib.request.urlopen(request, timeout=5) as response:+ assert response.status == 204+ stdout, stderr = process.communicate(timeout=10)+ assert process.returncode == 0, stderr.decode()+ assert stdout == b""+ finally:+ observer.close()+ if process.poll() is None:+ process.kill()+ _, errors = process.communicate(timeout=5)+ if process.returncode not in (0, -9):+ raise AssertionError(errors.decode())diff --git a/tests/_cli/test_pair_forwarder.py b/tests/_cli/test_pair_forwarder.pynew file mode 100644index 0000000000..03c6a96033--- /dev/null+++ b/tests/_cli/test_pair_forwarder.py@@ -0,0 +1,514 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import http.client+import json+import os+import subprocess+import sys+import threading+import time+from pathlib import Path+from typing import TYPE_CHECKING+from unittest.mock import Mock++import pytest+from click.testing import CliRunner++from marimo._cli.cli import main as cli_main+from marimo._cli.pair import commands, forwarder+from marimo._cli.pair.artifacts import AgentMessageFiles+from marimo._cli.pair.client import (+ HostEndpoint,+ PairConnectionError,+ PairError,+ SSEEvent,+ StaleNotebookError,+)+from marimo._cli.pair.connection import ConnectionStore+from marimo._cli.pair.delivery import DeliveryTarget, ProcessHandle+from marimo._cli.pair.forwarder import ForwarderConfig, run_forwarder+from tests._cli.test_pair_delivery import record++if TYPE_CHECKING:+ import queue+++class RecordingInbox:+ inbox_bytes = 512++ def __init__(self) -> None:+ self.messages: list[str] = []+ self.living = True++ def alive(self) -> bool:+ return self.living++ def send(self, text: str) -> None:+ self.messages.append(text)+++def config() -> ForwarderConfig:+ return ForwarderConfig(+ "http://server",+ "s_one",+ "identity",+ "private-token",+ DeliveryTarget(+ "codex",+ "thread",+ "Codex",+ process=ProcessHandle.capture(os.getpid()),+ ),+ )+++def install_stream(+ monkeypatch: pytest.MonkeyPatch,+ scripts: list[list[SSEEvent | Exception | None]],+) -> Mock:+ calls = Mock()++ def read(+ config: ForwarderConfig,+ incoming: queue.Queue[SSEEvent | Exception | None],+ stopped: threading.Event,+ _responses: object,+ _cursor: str | None = None,+ ) -> None:+ calls(config)+ for event in scripts.pop(0):+ if event is None:+ event = SSEEvent(+ "attachment.removed",+ json.dumps({"id": "att-one"}),+ )+ if stopped.is_set():+ return+ incoming.put(event)+ if isinstance(event, SSEEvent) and event.name == "attachment":+ incoming.put(SSEEvent("ready", "{}"))++ monkeypatch.setattr(forwarder, "_read_stream", read)+ return calls+++def attached(identity: str = "identity") -> SSEEvent:+ return SSEEvent(+ "attachment",+ json.dumps({"attachment": {"identity": identity, "id": "att-one"}}),+ )+++def agent_message(value: object) -> SSEEvent:+ return SSEEvent(+ "custom",+ json.dumps(+ {"custom": {"type": "marimo.pair.agent-message", "data": value}}+ ),+ )+++def test_coalescing_bounds_final_messages(+ config: ForwarderConfig, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(AgentMessageFiles, "cleanup", lambda _: None)+ install_stream(+ monkeypatch,+ [+ [+ attached(),+ agent_message("one"),+ agent_message("two"),+ agent_message("😀" * 1000),+ agent_message({"lens": "custom"}),+ None,+ ]+ ],+ )+ inbox = RecordingInbox()+ ready = Mock()+ run_forwarder(config, inbox, ready=ready)+ ready.assert_called_once()+ assert len(inbox.messages) == 3+ assert "one" in inbox.messages[0]+ assert "two" in inbox.messages[0]+ for message in inbox.messages:+ assert len(message.encode("utf-8")) <= inbox.inbox_bytes+ path = Path(+ inbox.messages[1].rsplit("Complete JSON agent message: ", 1)[1][:-1]+ )+ assert json.loads(path.read_text(encoding="utf-8")) == "😀" * 1000+++def test_reconnect_preserves_identity(+ config: ForwarderConfig, monkeypatch: pytest.MonkeyPatch+) -> None:+ calls = install_stream(+ monkeypatch,+ [+ [+ attached(),+ agent_message("first"),+ http.client.IncompleteRead(b""),+ ],+ [attached(), SSEEvent("heartbeat", ""), agent_message(None), None],+ ],+ )+ inbox = RecordingInbox()+ ready = Mock()+ run_forwarder(config, inbox, ready=ready)+ assert calls.call_args_list == [((config,),), ((config,),)]+ ready.assert_called_once()+ assert len(inbox.messages) == 2+ assert inbox.messages[0].endswith("first")+ assert inbox.messages[1].endswith("null")+++def test_reconnect_backoff_caps_and_resets_after_attachment(+ config: ForwarderConfig, monkeypatch: pytest.MonkeyPatch+) -> None:+ dropped = PairConnectionError("wording can change")+ scripts: list[list[SSEEvent | Exception | None]] = [[attached(), dropped]]+ scripts.extend([[dropped] for _ in range(8)])+ scripts.extend([[attached(), dropped], [attached(), None]])+ install_stream(monkeypatch, scripts)+ wait = Mock(return_value=True)+ monkeypatch.setattr(forwarder, "_wait_reconnect", wait)+ ready = Mock()+ run_forwarder(config, RecordingInbox(), ready=ready)+ assert [call.args[1] for call in wait.call_args_list] == [+ 0.1,+ 0.2,+ 0.4,+ 0.8,+ 1.6,+ 3.2,+ 5.0,+ 5.0,+ 5.0,+ 0.1,+ ]+ ready.assert_called_once()+++def test_authentication_failure_after_attachment_does_not_reconnect(+ config: ForwarderConfig, monkeypatch: pytest.MonkeyPatch+) -> None:+ calls = install_stream(+ monkeypatch, [[attached(), PairError("Authentication failed.")]]+ )+ with pytest.raises(PairError, match="could not continue"):+ run_forwarder(config, RecordingInbox(), ready=Mock())+ calls.assert_called_once()+++def test_reconnect_wait_stops_when_harness_exits(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ inbox = RecordingInbox()+ monkeypatch.setattr(+ time, "sleep", lambda _: setattr(inbox, "living", False)+ )+ assert not forwarder._wait_reconnect(inbox, 5)+++ "first",+ [+ agent_message("too early"),+ attached("wrong"),+ PairError("Authentication failed."),+ ],+)+def test_startup_failure(+ config: ForwarderConfig,+ monkeypatch: pytest.MonkeyPatch,+ first: SSEEvent | Exception,+) -> None:+ install_stream(monkeypatch, [[first]])+ ready = Mock()+ with pytest.raises(PairError):+ run_forwarder(config, RecordingInbox(), ready=ready)+ ready.assert_not_called()+++def test_stale_notebook_exit(+ config: ForwarderConfig, monkeypatch: pytest.MonkeyPatch+) -> None:+ install_stream(+ monkeypatch,+ [+ [attached(), OSError("drop")],+ [StaleNotebookError("Invalid stable session id")],+ ],+ )+ run_forwarder(config, RecordingInbox(), ready=Mock())+++def test_send_failure_does_not_retry_delivery(+ config: ForwarderConfig, monkeypatch: pytest.MonkeyPatch+) -> None:+ install_stream(monkeypatch, [[attached(), agent_message("once"), None]])+ inbox = RecordingInbox()+ send = Mock(side_effect=PairError("rejected"))+ monkeypatch.setattr(inbox, "send", send)+ with pytest.raises(PairError, match="rejected"):+ run_forwarder(config, inbox, ready=Mock())+ send.assert_called_once()+++def test_dead_harness_closes_reader(+ config: ForwarderConfig, monkeypatch: pytest.MonkeyPatch+) -> None:+ inbox = RecordingInbox()+ closed = threading.Event()++ def read(+ _config: object,+ incoming: queue.Queue[SSEEvent | Exception | None],+ stopped: threading.Event,+ _responses: object,+ _cursor: str | None = None,+ ) -> None:+ incoming.put(attached())+ stopped.wait(timeout=2)+ closed.set()++ monkeypatch.setattr(forwarder, "_read_stream", read)+ monkeypatch.setattr(forwarder, "_LIVENESS_SECONDS", 0.01)+ run_forwarder(config, inbox, ready=lambda: setattr(inbox, "living", False))+ assert closed.is_set()+++def test_dead_harness_never_connects(+ config: ForwarderConfig, monkeypatch: pytest.MonkeyPatch+) -> None:+ calls = install_stream(monkeypatch, [])+ inbox = RecordingInbox()+ inbox.living = False+ run_forwarder(config, inbox, ready=Mock())+ calls.assert_not_called()+++def test_detached_platform_options(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.setattr(subprocess, "DETACHED_PROCESS", 8, raising=False)+ monkeypatch.setattr(+ subprocess, "CREATE_NEW_PROCESS_GROUP", 512, raising=False+ )+ assert forwarder.detached_options() == {"creationflags": 520}+ monkeypatch.setattr(sys, "platform", "darwin")+ assert forwarder.detached_options() == {"start_new_session": True}+++def isolated_cli(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> ConnectionStore:+ monkeypatch.setenv("CODEX_SESSION_ID", "thread")+ monkeypatch.setattr(+ commands,+ "resolve_host",+ lambda _: HostEndpoint("http://server/api/marimo/v1", "host-token"),+ )+ store = ConnectionStore(tmp_path)+ monkeypatch.setattr(commands, "ConnectionStore", lambda: store)+ return store+++def test_connect_and_detach_lifecycle(+ isolated_cli: ConnectionStore, monkeypatch: pytest.MonkeyPatch+) -> None:+ owner = ProcessHandle.capture(os.getpid())+ target = DeliveryTarget("codex", "thread", "Codex", process=owner)+ harness = Mock()+ check = Mock()+ monkeypatch.setattr(harness, "check", check)+ monkeypatch.setattr(+ commands, "detect_target", lambda *_: (harness, target)+ )+ start = Mock(return_value=record(owner))+ stop = Mock()+ monkeypatch.setattr(commands, "start_forwarder", start)+ monkeypatch.setattr(ProcessHandle, "stop", stop)+ previous = record(owner)+ isolated_cli.save(previous)+ runner = CliRunner()+ result = runner.invoke(+ cli_main,+ [+ "pair",+ *["connect", "--url", "http://server", "--notebook", "s_one"],+ ],+ )+ assert result.exit_code == 0, result.output+ check.assert_not_called()+ stop.assert_called_once()+ assert start.call_args.args[0].identity == previous.identity+ assert isolated_cli.load(previous.identity) is None+ isolated_cli.save(previous)+ result = runner.invoke(+ cli_main,+ ["pair", *["detach", "--notebook", "s_one"]],+ )+ assert result.exit_code == 0, result.output+ assert isolated_cli.load(previous.identity) is None+ assert stop.call_count == 2+++def test_stream_close_interrupts_blocked_read() -> None:+ import socket++ from marimo._cli.pair.client import EventStream++ left, right = socket.socketpair()+ finished = threading.Event()++ def read() -> None:+ try:+ assert left.recv(1) == b""+ finally:+ finished.set()++ thread = threading.Thread(target=read)+ try:+ thread.start()+ response = Mock()+ EventStream(response, left).close()+ assert finished.wait(timeout=1)+ response.close.assert_called_once()+ assert left.fileno() == -1+ finally:+ left.close()+ right.close()+ thread.join(timeout=1)+++def test_heartbeat_parser_is_opt_in() -> None:+ from marimo._cli.pair.client import iter_sse++ lines = [+ b": keep-alive\n",+ b"\n",+ b"event: custom\n",+ b"data: null\n",+ b"\n",+ ]+ assert list(iter_sse(lines)) == [SSEEvent("custom", "null")]+ assert list(iter_sse(lines, heartbeats=True)) == [+ SSEEvent("heartbeat", ""),+ SSEEvent("custom", "null"),+ ]+++def test_reconnect_uses_processed_cursor_and_ignores_old_removal(+ config: ForwarderConfig, monkeypatch: pytest.MonkeyPatch+) -> None:+ cursors: list[str | None] = []+ scripts: list[list[SSEEvent | Exception | None]] = [+ [+ attached(),+ SSEEvent("ready", "{}", "10"),+ SSEEvent(+ "custom",+ json.dumps(+ {+ "custom": {+ "type": "marimo.pair.agent-message",+ "data": "first",+ }+ }+ ),+ "11",+ ),+ OSError("drop"),+ ],+ [+ SSEEvent(+ "attachment.removed",+ json.dumps({"id": "att-one"}),+ "12",+ ),+ SSEEvent(+ "custom",+ json.dumps({"custom": {"type": "other", "data": "ignore"}}),+ "13",+ ),+ SSEEvent(+ "custom",+ json.dumps(+ {+ "custom": {+ "type": "marimo.pair.agent-message",+ "data": "replayed",+ }+ }+ ),+ "14",+ ),+ SSEEvent(+ "attachment",+ json.dumps(+ {+ "attachment": {+ "identity": config.identity,+ "id": "att-two",+ }+ }+ ),+ "15",+ ),+ SSEEvent("ready", "{}", "15"),+ SSEEvent(+ "attachment.removed",+ json.dumps({"id": "att-two"}),+ "16",+ ),+ ],+ ]++ def read(+ _config: ForwarderConfig,+ incoming: queue.Queue[SSEEvent | Exception | None],+ _stopped: threading.Event,+ _responses: object,+ cursor: str | None = None,+ ) -> None:+ cursors.append(cursor)+ for event in scripts.pop(0):+ incoming.put(event)++ monkeypatch.setattr(forwarder, "_read_stream", read)+ inbox = RecordingInbox()+ ready = Mock()+ run_forwarder(config, inbox, ready=ready)+ assert cursors == [None, "11"]+ assert [message.rsplit("\n", 1)[1] for message in inbox.messages] == [+ "first",+ "replayed",+ ]+ ready.assert_called_once()+++def test_reset_replaces_attachment_without_second_ready(+ config: ForwarderConfig, monkeypatch: pytest.MonkeyPatch+) -> None:+ install_stream(+ monkeypatch,+ [+ [+ attached(),+ SSEEvent("reset", "{}"),+ attached(),+ agent_message({"opaque": [1, None]}),+ None,+ ]+ ],+ )+ inbox = RecordingInbox()+ ready = Mock()+ run_forwarder(config, inbox, ready=ready)+ ready.assert_called_once()+ assert inbox.messages[0].endswith('{"opaque": [1, null]}')diff --git a/tests/_cli/test_pair_integration.py b/tests/_cli/test_pair_integration.pyindex 7eaf217023..6f7849b67f 100644--- a/tests/_cli/test_pair_integration.py+++ b/tests/_cli/test_pair_integration.py@@ -7,7 +7,7 @@ import signalimport subprocessimport sysfrom concurrent.futures import ThreadPoolExecutor-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Literalimport pytest@@ -15,6 +15,7 @@ from tests._cli._pair_server import PairTestServer, pair_test_serverif TYPE_CHECKING:from collections.abc import Generator+ from pathlib import Path@pytest.fixture(scope="module")@@ -25,7 +26,17 @@ def server(yield running-def _command(server: PairTestServer, *arguments: str) -> list[str]:+def _command(+ server: PairTestServer,+ *arguments: str,+ selector: Literal["notebook", "session", "auto"] = "notebook",+) -> list[str]:+ target = []+ if selector == "notebook":+ assert server.notebook_id is not None+ target = ["--notebook", server.notebook_id]+ elif selector == "session":+ target = ["--session", server.stable_session_id]return [sys.executable,"-m",@@ -34,8 +45,7 @@ def _command(server: PairTestServer, *arguments: str) -> list[str]:"execute","--url",server.url,- "--session",- server.stable_session_id,+ *target,*arguments,]@@ -45,9 +55,10 @@ def _run(*arguments: str,code_input: str | None = None,timeout: float = 20,+ selector: Literal["notebook", "session", "auto"] = "notebook",) -> subprocess.CompletedProcess[str]:return subprocess.run(- _command(server, *arguments),+ _command(server, *arguments, selector=selector),input=code_input,text=True,capture_output=True,@@ -88,15 +99,107 @@ def test_streams_output_before_execution_finishes(assert stdout == "b\n"-def test_executes_by_stable_session_id(server: PairTestServer) -> None:- assert server.stable_session_id != server.session_id[email protected]("selector", ["notebook", "session", "auto"])+def test_host_execution_target_selection(+ server: PairTestServer,+ selector: Literal["notebook", "session", "auto"],+) -> None:+ assert server.notebook_id != server.session_id- result = _run(server, "-c", "print('stable')")+ result = _run(server, "-c", "print('stable')", selector=selector)assert result.returncode == 0, result.stderrpayload = json.loads(result.stdout)assert payload["stdout"] == "stable\n"- assert payload["session"]["id"] == server.stable_session_id+ assert payload["notebook"]["id"] == server.notebook_id+ if selector == "notebook":+ assert "session" not in payload+ else:+ assert payload["session"]["id"] == server.stable_session_id++[email protected](scope="module")+def editor_server(+ tmp_path_factory: pytest.TempPathFactory,+) -> Generator[PairTestServer, None, None]:+ with pair_test_server(+ tmp_path_factory.mktemp("pair-editor"),+ host_enabled=False,+ token="pair-editor-private-token",+ ) as running:+ yield running++[email protected]("selector", ["session", "auto"])+def test_editor_execution_without_host_preserves_session_contract(+ editor_server: PairTestServer,+ tmp_path: Path,+ selector: Literal["session", "auto"],+) -> None:+ token_file = tmp_path / "token"+ token_file.write_text("pair-editor-private-token")+ assert editor_server.notebook_id is None+ result = _run(+ editor_server,+ "--token-file",+ str(token_file),+ "-c",+ "print('editor'); 42",+ selector=selector,+ )+ assert result.returncode == 0, result.stderr+ payload = json.loads(result.stdout)+ assert payload["success"] is True+ assert payload["stdout"] == "editor\n"+ assert payload["output"] == {+ "mimetype": "text/html",+ "data": "<pre class='text-xs'>42</pre>",+ }+ assert payload["session"] == {"id": editor_server.stable_session_id}+ assert "notebook" not in payload+++def test_editor_execution_requires_editor_token(+ editor_server: PairTestServer,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.delenv("MARIMO_TOKEN", raising=False)+ result = _run(+ editor_server, "-c", "print('must not execute')", selector="session"+ )+ assert result.returncode == 2+ assert "must not execute" not in result.stdout+ assert "pair-editor-private-token" not in result.stdout + result.stderr+ editor_server.wait_for_kernel("idle")++[email protected]("stream", [False, True])+def test_editor_execution_failure_preserves_output(+ editor_server: PairTestServer,+ tmp_path: Path,+ stream: bool,+) -> None:+ token_file = tmp_path / "token"+ token_file.write_text("pair-editor-private-token")+ result = _run(+ editor_server,+ "--token-file",+ str(token_file),+ *(["--stream"] if stream else []),+ "-c",+ "print('before error'); 1 / 0",+ selector="session",+ )+ assert result.returncode == 1, result.stderr+ if stream:+ assert result.stdout == "before error\n"+ assert "ZeroDivisionError" in result.stderr+ else:+ payload = json.loads(result.stdout)+ assert payload["success"] is False+ assert payload["stdout"] == "before error\n"+ assert "ZeroDivisionError" in payload["stderr"]+ assert payload["session"] == {"id": editor_server.stable_session_id}@pytest.mark.skipif(os.name != "posix", reason="SIGINT requires POSIX")@@ -119,7 +222,8 @@ def test_interrupt_disconnects_and_kernel_recovers(process.wait()assert process.returncode == 1, (stdout, stderr)- assert stderr == "Interrupted.\n"+ assert json.loads(stdout)["outcome"] == "interrupted"+ assert stderr == ""server.wait_for_kernel("idle")recovered = _run(server, "-c", "print('alive')")@@ -128,7 +232,7 @@ def test_interrupt_disconnects_and_kernel_recovers(assert payload["success"] is Trueassert payload["stdout"] == "alive\n"assert payload["output"] is None- assert payload["session"]["id"] == server.stable_session_id+ assert payload["notebook"]["id"] == server.notebook_iddef test_missing_input_does_not_read_stdin_or_execute(@@ -140,3 +244,66 @@ def test_missing_input_does_not_read_stdin_or_execute(assert "error: specify -c or --code-file" in result.stderrassert "must not run" not in result.stdoutserver.wait_for_kernel("idle", timeout=1)+++ ("code", "error"),+ [("1 / 0", "ZeroDivisionError"), ("input()", "EOFError")],+)+def test_host_run_error_returns_failed_result(+ server: PairTestServer, code: str, error: str+) -> None:+ result = _run(server, "-c", code)+ assert result.returncode == 1, result.stderr+ payload = json.loads(result.stdout)+ assert payload["outcome"] == "failed"+ assert payload["success"] is False+ assert error in payload["stderr"]++[email protected](os.name != "posix", reason="SIGINT requires POSIX")+def test_concurrent_host_run_reports_conflict(server: PairTestServer) -> None:+ process = subprocess.Popen(+ _command(server, "-c", "import time; time.sleep(30)"),+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ text=True,+ )+ try:+ server.wait_for_kernel("running")+ second = _run(server, "-c", "print('must not run')")+ assert second.returncode == 2+ payload = json.loads(second.stdout)+ assert (+ "active" in payload["error"].lower()+ or "progress" in payload["error"].lower()+ )+ assert payload["stdout"] is None+ finally:+ process.send_signal(signal.SIGINT)+ process.communicate(timeout=10)+ server.wait_for_kernel("idle")+++def test_host_run_without_runtime_reports_error(tmp_path: Path) -> None:+ import urllib.request++ from marimo._cli.pair.client import resolve_host++ with pair_test_server(tmp_path) as server:+ host = resolve_host(server.url)+ request = urllib.request.Request(+ f"{host.url}/notebooks/{server.notebook_id}/runtime",+ method="DELETE",+ headers={+ "Authorization": f"Bearer {host.token}",+ "Idempotency-Key": "stop-test-runtime",+ },+ )+ with urllib.request.urlopen(request, timeout=5):+ pass+ result = _run(server, "-c", "1")+ assert result.returncode == 2+ payload = json.loads(result.stdout)+ assert "runtime" in payload["error"].lower()+ assert "kernel" in payload["next"]diff --git a/tests/_cli/test_pair_opencode.py b/tests/_cli/test_pair_opencode.pynew file mode 100644index 0000000000..67bf142ef3--- /dev/null+++ b/tests/_cli/test_pair_opencode.py@@ -0,0 +1,382 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import base64+import json+import os+import queue+import sys+import threading+import urllib.request+from contextlib import contextmanager+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from typing import TYPE_CHECKING+from urllib.parse import parse_qs, urlsplit++import msgspec+import pytest++from marimo._cli.pair.client import PairError, PairInputError+from marimo._cli.pair.connection import ConnectionStore, connection_identity+from marimo._cli.pair.delivery import ProcessHandle+from marimo._cli.pair.forwarder import ForwarderConfig, start_forwarder+from marimo._cli.pair.harnesses import detect_target, harness_for+from marimo._cli.pair.harnesses.opencode import OpenCodeHarness+from tests._cli._pair_server import pair_test_server++if TYPE_CHECKING:+ from collections.abc import Iterator+ from pathlib import Path++pytestmark = pytest.mark.skipif(+ sys.platform == "win32",+ reason="Native OpenCode discovery uses POSIX ownership",+)+++class OpenCodeServer:+ """An authenticated transport double for the OpenCode 2.x API."""++ def __init__(self) -> None:+ self.authorization = (+ "Basic " + base64.b64encode(b"opencode:private-password").decode()+ )+ self.version = "2.0.32"+ self.pid = os.getpid()+ self.shells: list[dict[str, object]] = [+ {"pid": os.getpid(), "metadata": {"sessionID": "ses_one"}}+ ]+ self.session = "ses_one"+ self.messages: queue.Queue[dict[str, str]] = queue.Queue()+ self.status = 200+++@contextmanager+def opencode_server() -> Iterator[tuple[OpenCodeServer, str]]:+ state = OpenCodeServer()++ class Handler(BaseHTTPRequestHandler):+ def log_message(self, *_args: object) -> None:+ pass++ def do_GET(self) -> None:+ self.respond()++ def do_POST(self) -> None:+ self.respond()++ def respond(self) -> None:+ body: dict[str, object]+ if self.headers.get("Authorization") != state.authorization:+ status, body = 401, {"error": "credential-must-not-appear"}+ elif state.status != 200:+ status, body = (+ state.status,+ {"error": "credential-must-not-appear"},+ )+ else:+ status = 200+ endpoint = urlsplit(self.path)+ location = parse_qs(endpoint.query).get("location[directory]")+ if (+ self.command == "POST"+ and endpoint.path == "/api/session/ses_one/prompt"+ and location == [os.getcwd()]+ ):+ state.messages.put(+ json.loads(+ self.rfile.read(+ int(self.headers["Content-Length"])+ )+ )+ )+ body = {}+ elif self.command == "GET" and self.path == "/api/info":+ body = {"pid": state.pid, "version": state.version}+ elif self.command != "GET" or location != [os.getcwd()]:+ status, body = 404, {"error": "Wrong OpenCode location"}+ elif endpoint.path == "/api/shell":+ body = {"data": state.shells}+ elif endpoint.path == "/api/session/ses_one":+ body = {"data": {"id": state.session}}+ else:+ status, body = 404, {"error": "Unknown OpenCode endpoint"}+ data = json.dumps(body).encode()+ self.send_response(status)+ self.send_header("Content-Length", str(len(data)))+ self.end_headers()+ self.wfile.write(data)++ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ yield state, f"http://127.0.0.1:{server.server_port}"+ finally:+ server.shutdown()+ server.server_close()+ thread.join(timeout=2)+++def native_env(+ tmp_path: Path, state: OpenCodeServer, url: str+) -> dict[str, str]:+ record = tmp_path / "opencode" / "service.json"+ record.parent.mkdir()+ record.write_text(+ json.dumps(+ {+ "url": url,+ "pid": os.getpid(),+ "version": state.version,+ "password": "private-password",+ }+ )+ )+ record.chmod(0o600)+ state.authorization = (+ "Basic " + base64.b64encode(b"opencode:private-password").decode()+ )+ return {"OPENCODE_TERMINAL": "1", "XDG_STATE_HOME": str(tmp_path)}+++def test_verified_session_delivery(tmp_path: Path) -> None:+ with opencode_server() as (state, url):+ env = native_env(tmp_path, state, url)+ harness, target = detect_target(env, "opencode")+ assert isinstance(harness, OpenCodeHarness)+ assert target.process == ProcessHandle.capture(os.getpid())+ assert target.label == "OpenCode"+ assert target.auth_token is not None+ assert target.auth_token not in repr(target)+ assert harness.identity(env) == target.address+ inbox = harness.open_inbox(target)+ assert inbox.alive()+ inbox.send("Opaque notebook payload 🐍")+ assert state.messages.get(timeout=2) == {+ "text": "Opaque notebook payload 🐍",+ "delivery": "queue",+ }+ config = ForwarderConfig(+ "http://localhost", "nb-one", "identity", None, target+ )+ assert (+ msgspec.json.decode(+ msgspec.json.encode(config), type=ForwarderConfig+ )+ == config+ )+++def test_unconfigured_and_unsupported_version() -> None:+ assert OpenCodeHarness().detect({}) is None+ assert OpenCodeHarness().identity({}) is None+ assert isinstance(harness_for("opencode"), OpenCodeHarness)+ with pytest.raises(PairInputError, match=r"require OpenCode 2\.x"):+ OpenCodeHarness().detect({"OPENCODE": "1"})+ with pytest.raises(PairInputError, match=r"require OpenCode 2\.x"):+ OpenCodeHarness().identity({"OPENCODE": "1"})+++def test_native_session_id_does_not_require_shell_lookup(+ tmp_path: Path,+) -> None:+ with opencode_server() as (state, url):+ env = native_env(tmp_path, state, url)+ env["OPENCODE_SESSION_ID"] = state.session+ state.shells = []+ target = OpenCodeHarness().detect(env)+ assert target is not None+ assert urlsplit(target.address).path == "/api/session/ses_one/prompt"+++def test_empty_xdg_state_uses_home(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from pathlib import Path++ with opencode_server() as (state, url):+ state_home = tmp_path / ".local" / "state"+ state_home.mkdir(parents=True)+ env = native_env(state_home, state, url)+ env["XDG_STATE_HOME"] = ""+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ assert OpenCodeHarness().detect(env) is not None+++def test_identity_resolution_failure_is_not_absence(tmp_path: Path) -> None:+ from marimo._cli.pair.harnesses import environment_identity++ with pytest.raises(PairInputError, match="service record"):+ environment_identity(+ {"OPENCODE_TERMINAL": "1", "XDG_STATE_HOME": str(tmp_path)}+ )+++def test_native_discovery_checks_platform_once(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from unittest.mock import Mock++ check = Mock()+ monkeypatch.setattr(OpenCodeHarness, "check", check)+ with opencode_server() as (state, url):+ env = native_env(tmp_path, state, url)+ assert OpenCodeHarness().detect(env) is not None+ check.assert_called_once()+++ "url",+ [+ "https://127.0.0.1",+ "http://example.com",+ "http://token@localhost",+ "http://localhost/#fragment",+ ],+)+def test_remote_endpoint_rejected(tmp_path: Path, url: str) -> None:+ state = OpenCodeServer()+ env = native_env(tmp_path, state, url)+ with pytest.raises(PairInputError, match="local HTTP endpoint"):+ OpenCodeHarness().detect(env)+++ "mutation", ["pid", "version", "session", "auth", "no-shell", "ambiguous"]+)+def test_reject_unverified_native_target(+ tmp_path: Path, mutation: str+) -> None:+ with opencode_server() as (state, url):+ env = native_env(tmp_path, state, url)+ if mutation == "pid":+ state.pid += 1+ elif mutation == "version":+ state.version = "2.0.99"+ elif mutation == "session":+ state.session = "ses_wrong"+ elif mutation == "auth":+ state.authorization = "Bearer wrong"+ elif mutation == "no-shell":+ state.shells = [+ {"pid": 99999999, "metadata": {"sessionID": "ses_other"}}+ ]+ else:+ state.shells.append(+ {"pid": os.getpid(), "metadata": {"sessionID": "ses_other"}}+ )+ with pytest.raises(PairError) as caught:+ OpenCodeHarness().detect(env)+ assert "private-password" not in str(caught.value)+ assert "credential-must-not-appear" not in str(caught.value)+++ "mutation", ["missing", "public", "symlink", "malformed", "v1", "dead"]+)+def test_reject_invalid_service_record(tmp_path: Path, mutation: str) -> None:+ with opencode_server() as (state, url):+ env = native_env(tmp_path, state, url)+ record = tmp_path / "opencode" / "service.json"+ if mutation == "missing":+ record.unlink()+ elif mutation == "public":+ record.chmod(0o644)+ elif mutation == "symlink":+ record.rename(record.with_suffix(".real"))+ record.symlink_to(record.with_suffix(".real"))+ elif mutation == "malformed":+ record.write_text("{}")+ else:+ data = json.loads(record.read_text())+ data["version" if mutation == "v1" else "pid"] = (+ "1.18.23" if mutation == "v1" else 99999999+ )+ record.write_text(json.dumps(data))+ with pytest.raises(PairInputError, match="service record"):+ OpenCodeHarness().detect(env)+++def test_explicit_owner_does_not_skip_session_verification(+ tmp_path: Path,+) -> None:+ with opencode_server() as (state, url):+ owner = ProcessHandle(os.getpid(), 0)+ harness = OpenCodeHarness()+ env = native_env(tmp_path, state, url)+ target = harness.detect(env, process=owner)+ assert target is not None+ assert target.process == owner+ assert not harness.open_inbox(target).alive()+ state.session = "ses_wrong"+ with pytest.raises(PairInputError, match="different conversation"):+ harness.detect(env, process=owner)+++def test_delivery_errors_are_sanitized(tmp_path: Path) -> None:+ with opencode_server() as (state, url):+ env = native_env(tmp_path, state, url)+ harness = OpenCodeHarness()+ target = harness.detect(env)+ assert target is not None+ state.status = 503+ with pytest.raises(PairError, match="rejected") as caught:+ harness.open_inbox(target).send("private notebook content")+ assert "private notebook content" not in str(caught.value)+ assert "credential-must-not-appear" not in str(caught.value)+++def test_detached_forwarder_to_opencode(+ tmp_path: Path,+) -> None:+ with (+ opencode_server() as (state, url),+ pair_test_server(tmp_path) as notebook,+ ):+ from marimo._cli.pair.client import resolve_host++ env = native_env(tmp_path, state, url)+ target = OpenCodeHarness().detect(env)+ assert target is not None+ identity = connection_identity(+ notebook.notebook_id, target.kind, target.address+ )+ host = resolve_host(notebook.url)+ store = ConnectionStore(tmp_path / "connections")+ try:+ start_forwarder(+ ForwarderConfig(+ host.url,+ notebook.notebook_id,+ identity,+ host.token,+ target,+ ),+ store,+ )+ for sequence in (1, 2):+ message = {+ "text": f"Notebook error {sequence}",+ "opaque": [sequence],+ }+ request = urllib.request.Request(+ f"{notebook.url}/api/pair/notebooks/{notebook.stable_session_id}/messages",+ data=json.dumps(message).encode(),+ headers={"Content-Type": "application/json"},+ method="POST",+ )+ with urllib.request.urlopen(request, timeout=5) as response:+ assert response.status == 202+ received = state.messages.get(timeout=5)+ assert received["delivery"] == "queue"+ assert (+ json.loads(received["text"].split("\n", 1)[1]) == message+ )+ record = store.load(identity)+ assert record is not None+ assert record.harness_kind == "opencode"+ assert "private-token" not in store.path(identity).read_text()+ assert "private-password" not in store.path(identity).read_text()+ finally:+ store.stop(identity)diff --git a/tests/_server/api/endpoints/test_pair_endpoints.py b/tests/_server/api/endpoints/test_pair_endpoints.pyindex 2281cceec8..ce006fc29a 100644--- a/tests/_server/api/endpoints/test_pair_endpoints.py+++ b/tests/_server/api/endpoints/test_pair_endpoints.py@@ -9,6 +9,7 @@ import pytestfrom marimo._ast.app import App, InternalAppfrom marimo._config.manager import get_default_config_manager+from marimo._config.settings import GLOBAL_SETTINGSfrom marimo._core import protocolfrom marimo._messaging.messages import AGENT_MESSAGE_TYPEfrom marimo._server.host.bridge import SessionBridge@@ -22,7 +23,6 @@ from marimo._session.notebook import AppFileManagerfrom marimo._session.session import SessionImplfrom marimo._session.state.session_view import SessionViewfrom marimo._types.ids import ConsumerId, SessionId-from marimo._utils.env import PAIR_PREVIEW_ENVfrom marimo._utils.marimo_path import MarimoPathfrom tests._server.mocks import get_session_manager, token_header@@ -36,8 +36,8 @@ if TYPE_CHECKING:@pytest.fixture(autouse=True)-def preview(monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setenv(PAIR_PREVIEW_ENV, "1")+def enable_host(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(GLOBAL_SETTINGS, "ENABLE_HOST", True)@pytest.fixture@@ -202,14 +202,14 @@ def test_invalid_message_json(@pytest.mark.parametrize("operation", ["messages", "attachments/detach"])-def test_preview_gate(+def test_host_gate(client: TestClient,target: tuple[SessionImpl, Notebook],monkeypatch: pytest.MonkeyPatch,operation: str,) -> None:session, _ = target- monkeypatch.delenv(PAIR_PREVIEW_ENV)+ monkeypatch.setattr(GLOBAL_SETTINGS, "ENABLE_HOST", False)assert (client.post(path(session, operation),diff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.pyindex eb08c09491..6730af736b 100644--- a/tests/_server/api/endpoints/test_ws.py+++ b/tests/_server/api/endpoints/test_ws.py@@ -236,6 +236,12 @@ async def test_reconnect_restores_current_attachments()last_op = "startup-progress" if url == WS_URL else "cell-op"+ expected_attachments = []+ if attachment_state == "attached":+ assert attachment is not None+ expected_attachments = [+ msgspec.json.decode(msgspec.json.encode(attachment))+ ]with client.websocket_connect(url) as websocket:messages = [websocket.receive_json()]while messages[-1]["op"] != last_op:@@ -246,11 +252,7 @@ async def test_reconnect_restores_current_attachments("op": "attachments","data": {"op": "attachments",- "attachments": (- [msgspec.json.decode(msgspec.json.encode(attachment))]- if attachment_state == "attached"- else []- ),+ "attachments": expected_attachments,},}]diff --git a/tests/_server/templates/test_templates_api.py b/tests/_server/templates/test_templates_api.pyindex 2c2d5c92b7..059f2bd07f 100644--- a/tests/_server/templates/test_templates_api.py+++ b/tests/_server/templates/test_templates_api.py@@ -2,10 +2,12 @@from __future__ import annotationsimport unittest+from dataclasses import asdictimport pytest-from inline_snapshot import snapshot+from marimo._cli.pair.prompts import load_prompt_templates+from marimo._config.settings import GLOBAL_SETTINGSfrom marimo._schemas.session import (VERSION,Cell,@@ -20,46 +22,39 @@ from marimo._server.templates.api import (from tests._server.templates.utils import parse_mount_config[email protected]("flag", ["1", "true", " TRUE "])[email protected]("enabled", [True, False])@pytest.mark.parametrize(("editable", "command"),[(True, "uv run marimo"), (False, "uvx marimo@latest")],)-def test_render_notebook_pair_preview(- monkeypatch: pytest.MonkeyPatch, flag: str, editable: bool, command: str+def test_pair_cli_config_is_unconditional(+ monkeypatch: pytest.MonkeyPatch,+ enabled: bool,+ editable: bool,+ command: str,) -> None:- monkeypatch.setenv("MARIMO_PAIR_NEXT", flag)+ monkeypatch.setattr(GLOBAL_SETTINGS, "ENABLE_HOST", enabled)monkeypatch.setattr("marimo._cli.pair.prompts.is_editable", lambda _: editable)html = render_notebook(code="import marimo\napp = marimo.App()", mode="edit")- assert parse_mount_config(html)["pairPreview"] == {+ assert parse_mount_config(html)["pairConfig"] == {"command": command,- "templates": snapshot(- {- "prompt": "Pair with me on this running marimo notebook.\n\nURL: {url}\n{session}\nRun `{command} pair --help` first.\nUse `{command}` for all marimo commands.\n\nOnce connected, send a fun toast using `mo.status.toast(...)` (`import marimo as mo`).{authentication}",- "session": "Session: {session}\n",- "token_file": "\n\nFor authenticated Pair commands, pass `--token-file {token_file}`.",- "token": "\n\nFor authenticated Pair commands, set `export MARIMO_TOKEN={token}` in the shell that runs marimo.",- }- ),+ "templates": asdict(load_prompt_templates()),+ "hostEnabled": enabled,}[email protected]("flag", [None, "", "0", "false"])-def test_render_notebook_omits_pair_preview(- monkeypatch: pytest.MonkeyPatch, flag: str | None+def test_read_mode_disables_agent_aware_ui(+ monkeypatch: pytest.MonkeyPatch,) -> None:- if flag is None:- monkeypatch.delenv("MARIMO_PAIR_NEXT", raising=False)- else:- monkeypatch.setenv("MARIMO_PAIR_NEXT", flag)+ monkeypatch.setattr(GLOBAL_SETTINGS, "ENABLE_HOST", True)html = render_notebook(- code="import marimo\napp = marimo.App()", mode="edit"+ code="import marimo\napp = marimo.App()", mode="read")- assert "pairPreview" not in parse_mount_config(html)+ assert parse_mount_config(html)["pairConfig"]["hostEnabled"] is Falseclass TestRenderNotebook(unittest.TestCase):