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): target the current session so agents connect to the right notebook (#10169)
Myles Scolnick0808f6df303c
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.tsnew file mode 100644index 0000000000..256545d133--- /dev/null+++ b/frontend/src/components/editor/actions/__tests__/pair-with-agent-commands.test.ts@@ -0,0 +1,153 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { afterEach, describe, expect, it, vi } from "vitest";+import {+ type ConnectionInfo,+ getMarimoCommand,+ getRawPrompt,+ getTerminalCommand,+ maskToken,+ shellQuote,+} from "../pair-with-agent-commands";++const CONNECTION: ConnectionInfo = {+ url: "http://localhost:8000",+ sessionId: "s_ab12cd",+};++describe("shellQuote", () => {+ it("quotes an empty string", () => {+ expect(shellQuote("")).toBe("''");+ });++ it("leaves shell-safe values untouched", () => {+ expect(shellQuote("http://localhost:8000")).toBe("http://localhost:8000");+ expect(shellQuote("s_ab12cd")).toBe("s_ab12cd");+ });++ 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'`);+ });+});++describe("getMarimoCommand", () => {+ afterEach(() => {+ vi.unstubAllEnvs();+ });++ it("uses the local checkout in dev", () => {+ vi.stubEnv("DEV", true);+ expect(getMarimoCommand()).toBe("uv run marimo");+ });++ it("uses uvx outside of dev", () => {+ vi.stubEnv("DEV", false);+ expect(getMarimoCommand()).toBe("uvx marimo@latest");+ });+});++describe("getTerminalCommand", () => {+ it("includes the url and session for each agent", () => {+ expect(getTerminalCommand("claude", CONNECTION, false)).toBe(+ `claude "$(uv run marimo pair prompt --url http://localhost:8000 --session s_ab12cd --claude)"`,+ );+ expect(getTerminalCommand("codex", CONNECTION, false)).toBe(+ `codex "$(uv run marimo pair prompt --url http://localhost:8000 --session s_ab12cd --codex)"`,+ );+ expect(getTerminalCommand("opencode", CONNECTION, false)).toBe(+ `opencode --prompt "$(uv run marimo pair prompt --url http://localhost:8000 --session s_ab12cd --opencode)"`,+ );+ });++ it("always targets the given session, not a random one", () => {+ const command = getTerminalCommand("claude", CONNECTION, false);+ expect(command).toContain("--session s_ab12cd");+ });++ it("shell-escapes a url containing metacharacters", () => {+ const command = getTerminalCommand(+ "claude",+ { url: "http://host:8000?file=a&b", sessionId: "s_ab12cd" },+ false,+ );+ expect(command).toContain("--url 'http://host:8000?file=a&b'");+ });++ it("adds --with-token before the agent flag when requested", () => {+ const command = getTerminalCommand("claude", CONNECTION, true);+ expect(command).toContain("--with-token --claude");+ });++ it("omits --with-token when not requested", () => {+ expect(getTerminalCommand("claude", CONNECTION, false)).not.toContain(+ "--with-token",+ );+ });+});++describe("getRawPrompt", () => {+ it("references the session-scoped execute-code command", () => {+ const prompt = getRawPrompt(CONNECTION, null);+ expect(prompt).toContain(+ "execute-code.sh --url http://localhost:8000 --session s_ab12cd",+ );+ expect(prompt).toContain(+ "Connect to the notebook at: http://localhost:8000 (session s_ab12cd)",+ );+ });++ 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 session-scoped token hint when a token is present", () => {+ const prompt = getRawPrompt(CONNECTION, "secret-token");+ expect(prompt).toContain(+ "execute-code.sh --url http://localhost:8000 --session s_ab12cd --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 (session s_ab12cd)++ Use \`execute-code.sh --url http://localhost:8000 --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."+ `);+ });+});++describe("maskToken", () => {+ it("masks short tokens entirely", () => {+ 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");+ });+});diff --git a/frontend/src/components/editor/actions/pair-with-agent-commands.ts b/frontend/src/components/editor/actions/pair-with-agent-commands.tsnew file mode 100644index 0000000000..d4255a1039--- /dev/null+++ b/frontend/src/components/editor/actions/pair-with-agent-commands.ts@@ -0,0 +1,109 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { assertNever } from "@/utils/assertNever";++export type AgentTab = "claude" | "codex" | "opencode" | "prompt";++export const TERMINAL_TABS = ["claude", "codex", "opencode"] as const;++export const AGENT_TABS = ["claude", "codex", "opencode", "prompt"] as const;++export const AGENT_LABELS: Record<AgentTab, string> = {+ claude: "Claude",+ codex: "Codex",+ opencode: "OpenCode",+ 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";+}++/**+ * POSIX-quote a value for safe embedding in a shell command. These commands are+ * meant to be copied into a terminal, so a url/token containing shell+ * metacharacters (`'`, `&`, `$(...)`, ...) must not break out of its argument.+ *+ * Mirrors Python's `shlex.quote` (used on the CLI side in+ * `marimo/_cli/pair/commands.py`) so both sides produce identical commands:+ * values that are already shell-safe are left as-is for readability, and+ * anything else is single-quoted with embedded quotes escaped as `'"'"'`.+ */+export function shellQuote(value: string): string {+ if (value === "") {+ return "''";+ }+ // Same "safe" character set as CPython's shlex.quote (ASCII \w plus a few).+ if (/^[\w@%+=:,./-]+$/.test(value)) {+ return value;+ }+ return `'${value.replaceAll("'", `'"'"'`)}'`;+}++/** Identifies the specific running notebook to pair on. */+export interface ConnectionInfo {+ url: string;+ /**+ * The current session id, so agents connect to *this* notebook rather than+ * guessing when multiple sessions are open on the same server.+ */+ sessionId: string;+}++/**+ * The shell command that wraps an agent CLI, delegating prompt generation to+ * `marimo pair prompt` so the terminal and CLI stay in sync.+ */+export function getTerminalCommand(+ agent: Exclude<AgentTab, "prompt">,+ { url, sessionId }: ConnectionInfo,+ withToken: boolean,+): string {+ const tokenFlag = withToken ? " --with-token" : "";+ const base = `${getMarimoCommand()} pair prompt --url ${shellQuote(url)} --session ${shellQuote(sessionId)}${tokenFlag}`;+ switch (agent) {+ case "claude":+ return `claude "$(${base} --claude)"`;+ case "codex":+ return `codex "$(${base} --codex)"`;+ case "opencode":+ return `opencode --prompt "$(${base} --opencode)"`;+ default:+ assertNever(agent);+ }+}++/**+ * The raw prompt for the "Prompt" tab. Mirrors the output of+ * `marimo pair prompt` (see `marimo/_cli/pair/commands.py`) so pasting it into+ * an agent behaves the same as the terminal commands.+ */+export function getRawPrompt(+ { url, sessionId }: ConnectionInfo,+ token: string | null,+): string {+ const executeCmd = `execute-code.sh --url ${shellQuote(url)} --session ${shellQuote(sessionId)}`;+ 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} (session ${sessionId})`,+ "",+ `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");+}++/** Mask all but the last 4 chars of a token for display. */+export function maskToken(token: string): string {+ if (token.length <= 4) {+ return "****";+ }+ return `${"*".repeat(Math.min(token.length - 4, 8))}${token.slice(-4)}`;+}diff --git a/frontend/src/components/editor/actions/pair-with-agent-modal.tsx b/frontend/src/components/editor/actions/pair-with-agent-modal.tsxindex ed5ff579c8..07440d8d46 100644--- a/frontend/src/components/editor/actions/pair-with-agent-modal.tsx+++ b/frontend/src/components/editor/actions/pair-with-agent-modal.tsx@@ -14,67 +14,20 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";import { copyToClipboard } from "@/utils/copy";import { Events } from "@/utils/events";import { Tooltip } from "@/components/ui/tooltip";-import { assertNever } from "@/utils/assertNever";import { asRemoteURL, useRuntimeManager } from "@/core/runtime/config";import { API } from "@/core/network/api";--type AgentTab = "claude" | "codex" | "opencode" | "prompt";--const TERMINAL_TABS = ["claude", "codex", "opencode"] as const;--function getMarimoCommand(): string {- return import.meta.env.DEV ? "uv run marimo" : "uvx marimo@latest";-}--function getTerminalCommand(- agent: Exclude<AgentTab, "prompt">,- url: string,- withToken: boolean,-): string {- const tokenFlag = withToken ? " --with-token" : "";- const base = `${getMarimoCommand()} pair prompt --url '${url}'${tokenFlag}`;- switch (agent) {- case "claude":- return `claude "$(${base} --claude)"`;- case "codex":- return `codex "$(${base} --codex)"`;- case "opencode":- return `opencode --prompt "$(${base} --opencode)"`;- default:- assertNever(agent);- }-}--function getRawPrompt(url: string, token: string | null): string {- const tokenHint = token- ? `\n\nUse this auth token when calling \`execute-code.sh\`: \`execute-code.sh --url '${url}' --token '${token}'\`.`- : "";- return [- "Use the /marimo-pair skill to pair-program on a running marimo notebook.",- "",- `Connect to the notebook at: ${url}`,- "",- `Use \`execute-code.sh --url ${url}\` 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");-}--function maskToken(token: string): string {- if (token.length <= 4) {- return "****";- }- return `${"*".repeat(Math.min(token.length - 4, 8))}${token.slice(-4)}`;-}--const SKILL_INSTALL = "npx skills add marimo-team/marimo-pair";--const AGENT_LABELS: Record<AgentTab, string> = {- claude: "Claude",- codex: "Codex",- opencode: "OpenCode",- prompt: "Prompt",-};+import { getSessionId } from "@/core/kernel/session";+import {+ AGENT_LABELS,+ AGENT_TABS,+ type AgentTab,+ type ConnectionInfo,+ getRawPrompt,+ getTerminalCommand,+ maskToken,+ SKILL_INSTALL,+ TERMINAL_TABS,+} from "./pair-with-agent-commands";function useAuthToken(): string | null {const [token, setToken] = useState<string | null>(null);@@ -98,7 +51,10 @@ export const PairWithAgentModal: React.FC<{const runtimeManager = useRuntimeManager();const authToken = useAuthToken();const hasToken = Boolean(authToken);- const remoteUrl = runtimeManager.httpURL.toString();+ const connection: ConnectionInfo = {+ url: runtimeManager.httpURL.toString(),+ sessionId: getSessionId(),+ };return (<DialogContent className="sm:max-w-2xl">@@ -125,7 +81,7 @@ export const PairWithAgentModal: React.FC<{onValueChange={(v) => setActiveTab(v as AgentTab)}><TabsList className="w-full">- {(["claude", "codex", "opencode", "prompt"] as const).map((tab) => (+ {AGENT_TABS.map((tab) => (<TabsTrigger key={tab} value={tab} className="flex-1">{AGENT_LABELS[tab]}</TabsTrigger>@@ -147,7 +103,7 @@ export const PairWithAgentModal: React.FC<{</Step><Step index={2} title="Run in your terminal"><CommandBlock- command={getTerminalCommand(tab, remoteUrl, hasToken)}+ command={getTerminalCommand(tab, connection, hasToken)}/></Step>{hasToken && authToken && (@@ -179,9 +135,9 @@ export const PairWithAgentModal: React.FC<{}><CommandBlock- command={getRawPrompt(remoteUrl, authToken)}+ command={getRawPrompt(connection, authToken)}display={getRawPrompt(- remoteUrl,+ connection,authToken ? maskToken(authToken) : null,)}multiline={true}diff --git a/marimo/_cli/pair/commands.py b/marimo/_cli/pair/commands.pyindex 91bc38b3d4..01d5674884 100644--- a/marimo/_cli/pair/commands.py+++ b/marimo/_cli/pair/commands.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport hashlibimport os+import shlexfrom dataclasses import dataclass, fieldfrom pathlib import Path@@ -114,6 +115,13 @@ def pair() -> None:type=str,help="URL of the running marimo kernel.",)+ "--session",+ "session",+ default=None,+ type=str,+ help="ID of the specific notebook session to connect to.",+)@click.option("--claude",is_flag=True,@@ -140,6 +148,7 @@ def pair() -> None:)def prompt(url: str,+ session: str | None,claude: bool,codex: bool,opencode: bool,@@ -154,9 +163,18 @@ def prompt(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 session+ claude "$(uvx marimo@latest pair prompt --url 'https://localhost:8000' --session 's_ab12cd' --claude)"+# With an auth tokenclaude "$(uvx marimo@latest pair prompt --url 'https://localhost:8000' --claude --with-token)""""+ # The specific notebook the user wants to pair on, so agents don't have to+ # guess when multiple sessions are open on the same server. Shell-quote the+ # dynamic values since this command is meant to be copy-pasted into a shell+ # and the url/session may contain metacharacters (e.g. `&` in a query).+ session_flag = f" --session {shlex.quote(session)}" if session else ""+ execute_cmd = f"execute-code.sh --url {shlex.quote(url)}{session_flag}"# Validate that the selected agents have the required skillsselected_agents = {"claude": claude,@@ -197,16 +215,18 @@ def prompt(token_hint = (f"\n\nAn auth token is stored at {token_file}. "- f"Pass it via `execute-code.sh --url '{url}' "+ f"Pass it via `{execute_cmd} "f"--token \"$(cat '{token_file}')\"`.")+ session_hint = f" (session {session})" if session else ""+# 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-code.sh --url {url}` from the marimo-pair "+ f"Connect to the notebook at: {url}{session_hint}\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."diff --git a/tests/_cli/test_cli_pair.py b/tests/_cli/test_cli_pair.pyindex 2499d1199c..8a95a614ab 100644--- a/tests/_cli/test_cli_pair.py+++ b/tests/_cli/test_cli_pair.py@@ -46,6 +46,31 @@ class TestPairPrompt:assert "execute-code.sh" in result.outputassert "marimo-pair" 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 TEST_URL in result.output+ assert "s_ab12cd" in result.output+ assert "--session s_ab12cd" in result.output++ def test_prompt_without_session_omits_flag(self) -> None:+ result = _runner.invoke(+ cli_main, ["pair", "prompt", "--url", TEST_URL]+ )+ assert result.exit_code == 0+ assert "--session" not 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"):@@ -92,6 +117,28 @@ class TestPairPromptWithToken: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",+ "s_ab12cd",+ "--with-token",+ ],+ input="my-secret-token\n",+ )+ assert result.exit_code == 0+ assert "--session s_ab12cd" in result.output+ # The token hint should target the same session.+ assert "--session s_ab12cd --token" in result.output+def test_with_token_still_requires_url(self) -> None:result = _runner.invoke(cli_main,