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
fix(pair): use --file path instead of --session for pair prompt (#10367)
Myles Scolnick3e44bbcaa6b7
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 256545d133..403d426260 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@@ -3,6 +3,7 @@import { afterEach, describe, expect, it, vi } from "vitest";import {type ConnectionInfo,+ getFileFromURL,getMarimoCommand,getRawPrompt,getTerminalCommand,@@ -12,7 +13,11 @@ import {const CONNECTION: ConnectionInfo = {url: "http://localhost:8000",- sessionId: "s_ab12cd",+ file: "notebooks/example.py",+};++const CONNECTION_WITHOUT_FILE: ConnectionInfo = {+ url: "http://localhost:8000",};describe("shellQuote", () => {@@ -22,7 +27,7 @@ describe("shellQuote", () => {it("leaves shell-safe values untouched", () => {expect(shellQuote("http://localhost:8000")).toBe("http://localhost:8000");- expect(shellQuote("s_ab12cd")).toBe("s_ab12cd");+ expect(shellQuote("notebooks/example.py")).toBe("notebooks/example.py");});it("quotes values with shell metacharacters", () => {@@ -37,6 +42,49 @@ describe("shellQuote", () => {// 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'"],+ [+ String.raw`C:\Users\Jane Doe\notebook.py`,+ String.raw`'C:\Users\Jane Doe\notebook.py'`,+ ],+ [+ String.raw`\\server\share\my notebook.py`,+ String.raw`'\\server\share\my notebook.py'`,+ ],+ ])("quotes non-portable 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", () => {@@ -56,30 +104,56 @@ describe("getMarimoCommand", () => {});describe("getTerminalCommand", () => {- it("includes the url and session for each agent", () => {+ it("includes the url and file for each agent", () => {expect(getTerminalCommand("claude", CONNECTION, false)).toBe(- `claude "$(uv run marimo pair prompt --url http://localhost:8000 --session s_ab12cd --claude)"`,+ `claude "$(uv run marimo pair prompt --url http://localhost:8000 --file notebooks/example.py --claude)"`,);expect(getTerminalCommand("codex", CONNECTION, false)).toBe(- `codex "$(uv run marimo pair prompt --url http://localhost:8000 --session s_ab12cd --codex)"`,+ `codex "$(uv run marimo pair prompt --url http://localhost:8000 --file notebooks/example.py --codex)"`,);expect(getTerminalCommand("opencode", CONNECTION, false)).toBe(- `opencode --prompt "$(uv run marimo pair prompt --url http://localhost:8000 --session s_ab12cd --opencode)"`,+ `opencode --prompt "$(uv run marimo pair prompt --url http://localhost:8000 --file notebooks/example.py --opencode)"`,);});- it("always targets the given session, not a random one", () => {- const command = getTerminalCommand("claude", CONNECTION, false);- expect(command).toContain("--session s_ab12cd");+ it("omits the file flag when the page URL has no file", () => {+ const command = getTerminalCommand(+ "claude",+ CONNECTION_WITHOUT_FILE,+ false,+ );+ expect(command).not.toContain("--file");+ expect(command).not.toContain("--session");});it("shell-escapes a url containing metacharacters", () => {const command = getTerminalCommand("claude",- { url: "http://host:8000?file=a&b", sessionId: "s_ab12cd" },+ { url: "http://host:8000?auth=a&b", file: "notebook.py" },false,);- expect(command).toContain("--url 'http://host:8000?file=a&b'");+ expect(command).toContain("--url 'http://host:8000?auth=a&b'");+ });++ it.each([+ ["relative/my notebook.py", "--file 'relative/my notebook.py'"],+ ["/tmp/my notebook.py", "--file '/tmp/my notebook.py'"],+ [+ String.raw`C:\Users\Jane Doe\notebook.py`,+ String.raw`--file 'C:\Users\Jane Doe\notebook.py'`,+ ],+ [+ String.raw`\\server\share\my notebook.py`,+ String.raw`--file '\\server\share\my notebook.py'`,+ ],+ ["notebooks/it's.py", `--file 'notebooks/it'"'"'s.py'`],+ ])("shell-escapes file path %s", (file, expected) => {+ const command = getTerminalCommand(+ "claude",+ { url: CONNECTION.url, file },+ false,+ );+ expect(command).toContain(expected);});it("adds --with-token before the agent flag when requested", () => {@@ -95,26 +169,33 @@ describe("getTerminalCommand", () => {});describe("getRawPrompt", () => {- it("references the session-scoped execute-code command", () => {+ it("references the file-scoped execute-code command", () => {const prompt = getRawPrompt(CONNECTION, null);expect(prompt).toContain(- "execute-code.sh --url http://localhost:8000 --session s_ab12cd",+ "execute-code.sh --url http://localhost:8000 --file notebooks/example.py",);expect(prompt).toContain(- "Connect to the notebook at: http://localhost:8000 (session s_ab12cd)",+ "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 session-scoped token hint when a token is present", () => {+ 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 --session s_ab12cd --token secret-token",+ "execute-code.sh --url http://localhost:8000 --file notebooks/example.py --token secret-token",);});@@ -128,9 +209,9 @@ describe("getRawPrompt", () => {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)+ Connect to the notebook at: http://localhost:8000 (file notebooks/example.py)- Use \`execute-code.sh --url http://localhost:8000 --session s_ab12cd\` from the marimo-pair skill to execute code in the notebook.+ 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."`);diff --git a/frontend/src/components/editor/actions/pair-with-agent-commands.ts b/frontend/src/components/editor/actions/pair-with-agent-commands.tsindex d4255a1039..c6d6697c1d 100644--- a/frontend/src/components/editor/actions/pair-with-agent-commands.ts+++ b/frontend/src/components/editor/actions/pair-with-agent-commands.ts@@ -1,6 +1,7 @@/* Copyright 2026 Marimo. All rights reserved. */import { assertNever } from "@/utils/assertNever";+import { KnownQueryParams } from "@/core/constants";export type AgentTab = "claude" | "codex" | "opencode" | "prompt";@@ -43,14 +44,21 @@ export function shellQuote(value: string): string {return `'${value.replaceAll("'", `'"'"'`)}'`;}+/** 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 current session id, so agents connect to *this* notebook rather than- * guessing when multiple sessions are open on the same server.- */- sessionId: string;+ /** The server's file key, when the page URL identifies a notebook. */+ file?: string;}/**@@ -59,11 +67,12 @@ export interface ConnectionInfo {*/export function getTerminalCommand(agent: Exclude<AgentTab, "prompt">,- { url, sessionId }: ConnectionInfo,+ { url, file }: ConnectionInfo,withToken: boolean,): string {+ const fileFlag = getFileFlag(file);const tokenFlag = withToken ? " --with-token" : "";- const base = `${getMarimoCommand()} pair prompt --url ${shellQuote(url)} --session ${shellQuote(sessionId)}${tokenFlag}`;+ const base = `${getMarimoCommand()} pair prompt --url ${shellQuote(url)}${fileFlag}${tokenFlag}`;switch (agent) {case "claude":return `claude "$(${base} --claude)"`;@@ -82,17 +91,19 @@ export function getTerminalCommand(* an agent behaves the same as the terminal commands.*/export function getRawPrompt(- { url, sessionId }: ConnectionInfo,+ { url, file }: ConnectionInfo,token: string | null,): string {- const executeCmd = `execute-code.sh --url ${shellQuote(url)} --session ${shellQuote(sessionId)}`;+ 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} (session ${sessionId})`,+ `Connect to the notebook at: ${url}${fileHint}`,"",`Use \`${executeCmd}\` from the marimo-pair skill to execute code in the notebook.${tokenHint}`,"",diff --git a/frontend/src/components/editor/actions/pair-with-agent-modal.tsx b/frontend/src/components/editor/actions/pair-with-agent-modal.tsxindex 07440d8d46..602bccc90f 100644--- a/frontend/src/components/editor/actions/pair-with-agent-modal.tsx+++ b/frontend/src/components/editor/actions/pair-with-agent-modal.tsx@@ -16,12 +16,12 @@ 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 { getSessionId } from "@/core/kernel/session";import {AGENT_LABELS,AGENT_TABS,type AgentTab,type ConnectionInfo,+ getFileFromURL,getRawPrompt,getTerminalCommand,maskToken,@@ -53,7 +53,7 @@ export const PairWithAgentModal: React.FC<{const hasToken = Boolean(authToken);const connection: ConnectionInfo = {url: runtimeManager.httpURL.toString(),- sessionId: getSessionId(),+ file: getFileFromURL(window.location.href),};return (diff --git a/marimo/_cli/pair/commands.py b/marimo/_cli/pair/commands.pyindex 01d5674884..fe468b9972 100644--- a/marimo/_cli/pair/commands.py+++ b/marimo/_cli/pair/commands.py@@ -116,11 +116,11 @@ def pair() -> None:help="URL of the running marimo kernel.",)@click.option(- "--session",- "session",+ "--file",+ "file_path",default=None,type=str,- help="ID of the specific notebook session to connect to.",+ help="Notebook path or file key from the page URL.",)@click.option("--claude",@@ -148,7 +148,7 @@ def pair() -> None:)def prompt(url: str,- session: str | None,+ file_path: str | None,claude: bool,codex: bool,opencode: bool,@@ -163,18 +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)"+ # Connect to a specific notebook+ claude "$(uvx marimo@latest pair prompt --url 'https://localhost:8000' --file 'notebooks/example.py' --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}"+ # Preserve the file key exactly as supplied. Relative keys are resolved by+ # the server workspace and may refer to a remote or non-POSIX filesystem.+ # Shell-quote dynamic values because this command is copy-pasted into a+ # shell and paths may contain spaces or metacharacters.+ file_flag = f" --file {shlex.quote(file_path)}" if file_path else ""+ execute_cmd = f"execute-code.sh --url {shlex.quote(url)}{file_flag}"# Validate that the selected agents have the required skillsselected_agents = {"claude": claude,@@ -219,13 +219,13 @@ def prompt(f"--token \"$(cat '{token_file}')\"`.")- session_hint = f" (session {session})" if session else ""+ file_hint = f" (file {file_path})" if file_path 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}{session_hint}\n\n"+ f"Connect to the notebook at: {url}{file_hint}\n\n"f"Use `{execute_cmd}` from the marimo-pair ""skill to execute code in the notebook."f"{token_hint}\n\n"diff --git a/tests/_cli/test_cli_pair.py b/tests/_cli/test_cli_pair.pyindex 8a95a614ab..e0be29de42 100644--- a/tests/_cli/test_cli_pair.py+++ b/tests/_cli/test_cli_pair.py@@ -30,6 +30,8 @@ class TestPairGroup:assert "--claude" in result.outputassert "--codex" in result.outputassert "--opencode" in result.output+ assert "--file" in result.output+ assert "--session" not in result.outputclass TestPairPrompt:@@ -46,23 +48,71 @@ class TestPairPrompt:assert "execute-code.sh" in result.outputassert "marimo-pair" in result.output- def test_prompt_with_session(self) -> None:+ def test_prompt_with_file(self) -> None:result = _runner.invoke(cli_main,- ["pair", "prompt", "--url", TEST_URL, "--session", "s_ab12cd"],+ [+ "pair",+ "prompt",+ "--url",+ TEST_URL,+ "--file",+ "notebooks/example.py",+ ],)assert result.exit_code == 0assert TEST_URL in result.output- assert "s_ab12cd" in result.output- assert "--session s_ab12cd" in result.output+ assert "notebooks/example.py" in result.output+ assert "--file notebooks/example.py" in result.output- def test_prompt_without_session_omits_flag(self) -> None:+ def test_prompt_without_file_omits_flag(self) -> None:result = _runner.invoke(cli_main, ["pair", "prompt", "--url", TEST_URL])assert result.exit_code == 0+ assert "--file" not in result.outputassert "--session" not in result.output+ def test_prompt_rejects_removed_session_option(self) -> None:+ result = _runner.invoke(+ cli_main,+ ["pair", "prompt", "--url", TEST_URL, "--session", "s_ab12cd"],+ )+ assert result.exit_code != 0+ assert "--session" in result.output++ def test_prompt_shell_quotes_file_paths(self) -> None:+ cases = [+ ("relative/path.py", "--file relative/path.py"),+ ("/tmp/my notebook.py", "--file '/tmp/my notebook.py'"),+ (+ r"C:\Users\Jane Doe\notebook.py",+ r"--file 'C:\Users\Jane Doe\notebook.py'",+ ),+ (+ r"\\server\share\my notebook.py",+ r"--file '\\server\share\my notebook.py'",+ ),+ (+ "notebooks/it's.py",+ """--file 'notebooks/it'"'"'s.py'""",+ ),+ ]+ for file_path, expected in cases:+ result = _runner.invoke(+ cli_main,+ [+ "pair",+ "prompt",+ "--url",+ TEST_URL,+ "--file",+ file_path,+ ],+ )+ 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.@@ -117,7 +167,7 @@ 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:+ def test_with_token_and_file(self, tmp_path: Path) -> None:with patch("marimo._cli.pair.commands._token_dir", return_value=tmp_path):@@ -128,16 +178,16 @@ class TestPairPromptWithToken:"prompt","--url",TEST_URL,- "--session",- "s_ab12cd",+ "--file",+ "notebooks/my notebook.py","--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+ assert "--file 'notebooks/my notebook.py'" in result.output+ # The token hint should target the same file.+ assert "--file 'notebooks/my notebook.py' --token" in result.outputdef test_with_token_still_requires_url(self) -> None:result = _runner.invoke(