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): add opt-in CLI prompts for agent pairing (#10889)
Kiran Gadhave4c64fc404813
diff --git a/frontend/src/__tests__/fixtures/pair-preview.ts b/frontend/src/__tests__/fixtures/pair-preview.tsnew file mode 100644index 0000000000..decdd73c86--- /dev/null+++ b/frontend/src/__tests__/fixtures/pair-preview.ts@@ -0,0 +1,19 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { readFileSync } from "node:fs";+import path from "node:path";+import { pairPreviewSchema } from "@/core/config/pair";++// Read the Python-owned resource only in tests to check the shared contract.+export const PAIR_PREVIEW = pairPreviewSchema.parse({+ command: "uv run marimo",+ templates: JSON.parse(+ readFileSync(+ path.resolve(+ import.meta.dirname,+ "../../../../marimo/_cli/pair/prompt.json",+ ),+ "utf8",+ ),+ ),+});diff --git a/frontend/src/__tests__/mount.test.ts b/frontend/src/__tests__/mount.test.tsindex 8262c94c21..24ed07f91e 100644--- a/frontend/src/__tests__/mount.test.ts+++ b/frontend/src/__tests__/mount.test.ts@@ -8,6 +8,8 @@ import { connectionAtom } from "@/core/network/connection";import { store } from "@/core/state/jotai";import { isStaticNotebook } from "@/core/static/static-state";import { WebSocketState } from "@/core/websocket/types";+import { pairPreviewAtom } from "@/core/config/pair";+import { PAIR_PREVIEW } from "./fixtures/pair-preview";import { mount, visibleForTesting } from "../mount";// Mock React DOM@@ -82,6 +84,22 @@ describe("mount", () => {mockElement,);+ it("hydrates the server's Pair preview configuration", () => {+ const error = mountRead({ pairPreview: PAIR_PREVIEW });++ expect(error).toBeUndefined();+ expect(store.get(pairPreviewAtom)).toEqual(PAIR_PREVIEW);+ });++ it("uses legacy Pair behavior when the host omits preview configuration", () => {+ store.set(pairPreviewAtom, PAIR_PREVIEW);++ const error = mountRead();++ expect(error).toBeUndefined();+ expect(store.get(pairPreviewAtom)).toBeUndefined();+ });+describe("connection state initialization", () => {it("should set connection to CONNECTING when runtimeConfig has lazy=false", () => {mount(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 c705e13add..12164c099c 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@@ -10,10 +10,12 @@ import {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",};const CONNECTION_WITHOUT_FILE: ConnectionInfo = {@@ -104,6 +106,61 @@ describe("getMarimoCommand", () => {});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 uv run marimo 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 uv run marimo pair prompt \+ --url http://localhost:8000 \+ --file notebooks/example.py \+ --session s_ab12cd \+ --with-token)"`,+ );+ },+ );+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 --file notebooks/example.py --claude)"`,@@ -169,6 +226,64 @@ describe("getTerminalCommand", () => {});describe("getRawPrompt", () => {+ it("uses supplied templates without reinterpreting inserted values", () => {+ expect(+ getRawPrompt(+ {+ url: "http://host/{file}",+ file: "{session}/it's.py",+ session: "{command}",+ },+ "tok'en {file} $&",+ {+ ...PAIR_PREVIEW,+ command: "custom marimo",+ templates: {+ ...PAIR_PREVIEW.templates,+ prompt: "{command}\n{url}\n{file}{session}{authentication}",+ },+ },+ ),+ ).toBe(+ "custom marimo\nhttp://host/{file}\nFile: {session}/it's.py\nSession: {command}\n" ++ `\n\nFor authenticated Pair commands, set \`export MARIMO_TOKEN='tok'"'"'en {file} $&'\` in the shell that runs marimo.`,+ );+ });++ it.each([+ [CONNECTION_WITHOUT_FILE, ""],+ [+ { ...CONNECTION_WITHOUT_FILE, session: "s_ab12cd" },+ "Session: s_ab12cd\n",+ ],+ [+ { ...CONNECTION_WITHOUT_FILE, file: "notebook.py" },+ "File: notebook.py\n",+ ],+ ])("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 `uv run marimo pair --help` first.\n" ++ "Use `uv run marimo` 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 optional session context", () => {+ 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" ++ "File: notebooks/example.py\n" ++ "Session: s_ab12cd\n\n" ++ "Run `uv run marimo pair --help` first.\n" ++ "Use `uv run marimo` for all marimo commands.\n\n" ++ "Once connected, send a fun toast using `mo.status.toast(...)` (`import marimo as mo`).",+ );+ });+it("references the file-scoped execute-code command", () => {const prompt = getRawPrompt(CONNECTION, null);expect(prompt).toContain(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.tsxnew file mode 100644index 0000000000..0cdf45e3cc--- /dev/null+++ b/frontend/src/components/editor/actions/__tests__/pair-with-agent-modal.test.tsx@@ -0,0 +1,218 @@+/* Copyright 2026 Marimo. All rights reserved. */++import {+ act,+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from "@testing-library/react";+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 { Dialog } from "@/components/ui/dialog";+import { TooltipProvider } from "@/components/ui/tooltip";+import { pairPreviewAtom } from "@/core/config/pair";+import { getSessionId } from "@/core/kernel/session";+import { filenameAtom } from "@/core/saving/file-state";+import {+ DEFAULT_RUNTIME_CONFIG,+ runtimeConfigAtom,+} from "@/core/runtime/config";+import { store } from "@/core/state/jotai";+import { PairWithAgentModal } from "../pair-with-agent-modal";+import { copyToClipboard } from "@/utils/copy";++vi.mock("@/utils/copy", () => ({+ copyToClipboard: vi.fn().mockResolvedValue(undefined),+}));++function wrapper({ children }: { children: React.ReactNode }) {+ return (+ <Provider store={store}>+ <TooltipProvider>+ <Dialog open={true}>{children}</Dialog>+ </TooltipProvider>+ </Provider>+ );+}++describe("PairWithAgentModal", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ store.set(pairPreviewAtom, PAIR_PREVIEW);+ store.set(filenameAtom, "/project/my notebook.py");+ store.set(runtimeConfigAtom, {+ ...DEFAULT_RUNTIME_CONFIG,+ url: "http://localhost:8000",+ });+ window.history.replaceState({}, "", "/?file=notebook.py");+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue(new Response(JSON.stringify({ token: null }))),+ );+ });++ afterEach(() => {+ store.set(pairPreviewAtom, undefined);+ store.set(filenameAtom, null);+ vi.unstubAllGlobals();+ });++ it.each(["Claude", "Codex", "OpenCode", "Prompt"])(+ "omits skill installation and includes the current session in %s preview",+ async (tab) => {+ await act(async () => {+ render(<PairWithAgentModal onClose={vi.fn()} />, { wrapper });+ });+ fireEvent.mouseDown(screen.getByRole("tab", { name: tab }), {+ button: 0,+ ctrlKey: false,+ });++ const panel = screen.getByRole("tabpanel");+ expect(within(panel).queryAllByText(/skill/i)).toEqual([]);+ expect(panel).toHaveTextContent(getSessionId());+ expect(panel).toHaveTextContent(+ tab === "Prompt" ? "File: notebook.py" : "--file notebook.py",+ );+ expect(panel).not.toHaveTextContent("/project/my notebook.py");+ expect(panel).toHaveTextContent(+ tab === "Prompt" ? "1. Copy this prompt" : "1. Run in your terminal",+ );+ },+ );++ it.each(["Claude", "Codex", "OpenCode", "Prompt"])(+ "includes the known notebook file in %s preview when the URL has no file",+ async (tab) => {+ window.history.replaceState({}, "", "/");+ await act(async () => {+ render(<PairWithAgentModal onClose={vi.fn()} />, { wrapper });+ });+ fireEvent.mouseDown(screen.getByRole("tab", { name: tab }), {+ button: 0,+ ctrlKey: false,+ });++ const panel = screen.getByRole("tabpanel");+ const fileHint =+ tab === "Prompt"+ ? "File: /project/my notebook.py"+ : "--file '/project/my notebook.py'";+ expect(panel).toHaveTextContent(fileHint);+ 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(fileHint);+ },+ );++ it.each([null, ""])(+ "omits the file when the URL and notebook filename are absent (%s)",+ async (filename) => {+ window.history.replaceState({}, "", "/");+ store.set(filenameAtom, filename);+ await act(async () => {+ render(<PairWithAgentModal onClose={vi.fn()} />, { wrapper });+ });+ expect(screen.getByRole("tabpanel")).not.toHaveTextContent("--file");+ fireEvent.mouseDown(screen.getByRole("tab", { name: "Prompt" }), {+ button: 0,+ ctrlKey: false,+ });+ expect(screen.getByRole("tabpanel")).not.toHaveTextContent("File:");+ },+ );++ it.each(["Claude", "Codex", "OpenCode", "Prompt"])(+ "preserves the %s skill flow without preview configuration",+ async (tab) => {+ store.set(pairPreviewAtom, undefined);+ window.history.replaceState({}, "", "/");+ await act(async () => {+ render(<PairWithAgentModal onClose={vi.fn()} />, { wrapper });+ });+ fireEvent.mouseDown(screen.getByRole("tab", { name: tab }), {+ 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(getSessionId());+ 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",+ );+ },+ );++ 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" })),+ );+ await act(async () => {+ render(<PairWithAgentModal onClose={vi.fn()} />, { wrapper });+ });+ fireEvent.mouseDown(screen.getByRole("tab", { name: "Prompt" }), {+ button: 0,+ ctrlKey: false,+ });++ const panel = screen.getByRole("tabpanel");+ expect(panel).toHaveTextContent("********oken");+ expect(panel).not.toHaveTextContent("secret-token");+ fireEvent.click(+ within(panel).getByRole("button", { name: "Copy prompt" }),+ );+ await waitFor(() => expect(copyToClipboard).toHaveBeenCalledOnce());+ expect(vi.mocked(copyToClipboard).mock.calls[0][0]).toContain(+ preview ? "export MARIMO_TOKEN=secret-token" : "--token secret-token",+ );+ expect(vi.mocked(copyToClipboard).mock.calls[0][0]).not.toContain(+ "********oken",+ );+ },+ );++ 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" })),+ );+ await act(async () => {+ render(<PairWithAgentModal onClose={vi.fn()} />, { wrapper });+ });++ const panel = screen.getByRole("tabpanel");+ expect(panel).toHaveTextContent("2. Paste when prompted for a token");+ expect(panel).not.toHaveTextContent("secret-token");+ fireEvent.click(+ within(panel).getByRole("button", { name: "Copy command" }),+ );+ await waitFor(() =>+ expect(copyToClipboard).toHaveBeenCalledWith(+ String.raw`claude "$(MARIMO_PAIR_NEXT=1 uv run marimo pair prompt \+ --url http://localhost:8000/ \+ --file notebook.py \+ --session ${getSessionId()} \+ --with-token)"`,+ ),+ );+ fireEvent.click(within(panel).getByRole("button", { name: "Copy token" }));+ await waitFor(() =>+ expect(copyToClipboard).toHaveBeenLastCalledWith("secret-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 2949c3fc39..9c4cc62b4e 100644--- a/frontend/src/components/editor/actions/pair-with-agent-commands.ts+++ b/frontend/src/components/editor/actions/pair-with-agent-commands.ts@@ -3,6 +3,7 @@import { assertNever } from "@/utils/assertNever";import { KnownQueryParams } from "@/core/constants";import { shellQuote } from "@/utils/shell";+import type { PairPreviewConfig } from "@/core/config/pair";export type AgentTab = "claude" | "codex" | "opencode" | "prompt";@@ -37,8 +38,9 @@ function getFileFlag(file: string | undefined): string {/** Identifies the specific running notebook to pair on. */export interface ConnectionInfo {url: string;- /** The server's file key, when the page URL identifies a notebook. */+ /** The server's file key or notebook filename, when known. */file?: string;+ session?: string;}/**@@ -47,19 +49,29 @@ export interface ConnectionInfo {*/export function getTerminalCommand(agent: Exclude<AgentTab, "prompt">,- { url, file }: ConnectionInfo,+ { url, file, session }: ConnectionInfo,withToken: boolean,+ preview?: PairPreviewConfig,): string {- const fileFlag = getFileFlag(file);- const tokenFlag = withToken ? " --with-token" : "";- const base = `${getMarimoCommand()} pair prompt --url ${shellQuote(url)}${fileFlag}${tokenFlag}`;+ const command = preview?.command ?? getMarimoCommand();+ const prefix = preview ? "MARIMO_PAIR_NEXT=1 " : "";+ const base = [+ `${prefix}${command} pair prompt`,+ `--url ${shellQuote(url)}`,+ file ? `--file ${shellQuote(file)}` : "",+ preview && session ? `--session ${shellQuote(session)}` : "",+ withToken ? "--with-token" : "",+ preview ? "" : `--${agent}`,+ ]+ .filter(Boolean)+ .join(preview ? " \\\n " : " ");switch (agent) {case "claude":- return `claude "$(${base} --claude)"`;+ return `claude "$(${base})"`;case "codex":- return `codex "$(${base} --codex)"`;+ return `codex "$(${base})"`;case "opencode":- return `opencode --prompt "$(${base} --opencode)"`;+ return `opencode --prompt "$(${base})"`;default:assertNever(agent);}@@ -71,9 +83,23 @@ export function getTerminalCommand(* an agent behaves the same as the terminal commands.*/export function getRawPrompt(- { url, file }: ConnectionInfo,+ { url, file, session }: ConnectionInfo,token: string | null,+ preview?: PairPreviewConfig,): string {+ if (preview) {+ const { command, templates } = preview;+ return formatPrompt(templates.prompt, {+ command,+ url,+ file: file ? formatPrompt(templates.file, { file }) : "",+ session: session ? formatPrompt(templates.session, { session }) : "",+ authentication: token+ ? formatPrompt(templates.token, { token: shellQuote(token) })+ : "",+ });+ }+const fileFlag = getFileFlag(file);const fileHint = file ? ` (file ${file})` : "";const executeCmd = `execute-code.sh --url ${shellQuote(url)}${fileFlag}`;@@ -91,6 +117,17 @@ export function getRawPrompt(].join("\n");}+function formatPrompt(+ template: string,+ values: Record<string, string>,+): string {+ // Replace once so inserted file names or tokens cannot become placeholders.+ return template.replaceAll(+ /\{(\w+)\}/g,+ (placeholder, key: string) => values[key] ?? placeholder,+ );+}+/** Mask all but the last 4 chars of a token for display. */export function maskToken(token: string): string {if (token.length <= 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 602bccc90f..b1ae62a12f 100644--- a/frontend/src/components/editor/actions/pair-with-agent-modal.tsx+++ b/frontend/src/components/editor/actions/pair-with-agent-modal.tsx@@ -2,6 +2,7 @@import { CheckIcon, CopyIcon } from "lucide-react";import React, { useEffect, useState } from "react";+import { useAtomValue } from "jotai";import { Button } from "@/components/ui/button";import {DialogContent,@@ -16,6 +17,9 @@ 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 { getSessionId } from "@/core/kernel/session";+import { useFilename } from "@/core/saving/filename";import {AGENT_LABELS,AGENT_TABS,@@ -49,11 +53,17 @@ export const PairWithAgentModal: React.FC<{}> = ({ onClose }) => {const [activeTab, setActiveTab] = useState<AgentTab>("claude");const runtimeManager = useRuntimeManager();+ const preview = useAtomValue(pairPreviewAtom);+ const filename = useFilename();+ const commandStep = preview ? 1 : 2;const authToken = useAuthToken();const hasToken = Boolean(authToken);const connection: ConnectionInfo = {url: runtimeManager.httpURL.toString(),- file: getFileFromURL(window.location.href),+ file:+ getFileFromURL(window.location.href) ??+ (preview ? filename || undefined : undefined),+ session: preview ? getSessionId() : undefined,};return (@@ -94,23 +104,34 @@ export const PairWithAgentModal: React.FC<{value={tab}className="mt-4 flex flex-col gap-4">- <Step- index={1}- title="Install the skill"- hint="Run once per machine."- >- <CommandBlock command={SKILL_INSTALL} />- </Step>- <Step index={2} title="Run in your terminal">+ {!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"><CommandBlock- command={getTerminalCommand(tab, connection, hasToken)}+ command={getTerminalCommand(+ tab,+ connection,+ hasToken,+ preview,+ )}/></Step>{hasToken && authToken && (- <Step index={3} title="Paste when prompted for a token">+ <Step+ index={commandStep + 1}+ title="Paste when prompted for a token"+ ><CommandBlockcommand={authToken}display={maskToken(authToken)}+ copyLabel="Copy token"/></Step>)}@@ -118,15 +139,17 @@ 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={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={2}+ index={commandStep}title="Copy this prompt into your agent"hint={hasToken@@ -135,10 +158,11 @@ export const PairWithAgentModal: React.FC<{}><CommandBlock- command={getRawPrompt(connection, authToken)}+ command={getRawPrompt(connection, authToken, preview)}display={getRawPrompt(connection,authToken ? maskToken(authToken) : null,+ preview,)}multiline={true}/>@@ -177,7 +201,8 @@ const CommandBlock: React.FC<{command: string;display?: string;multiline?: boolean;-}> = ({ command, display, multiline = false }) => {+ copyLabel?: string;+}> = ({ command, display, multiline = false, copyLabel = "Copy command" }) => {const [copied, setCopied] = useState(false);const copy = Events.stopPropagation(async (e) => {@@ -195,6 +220,7 @@ const CommandBlock: React.FC<{</pre><Tooltip content="Copied!" open={copied}><Button+ aria-label="Copy prompt"onClick={copy}size="xs"variant="ghost"@@ -213,11 +239,11 @@ const CommandBlock: React.FC<{return (<div className="flex items-center gap-2 rounded-md bg-muted px-3 py-2 font-mono text-xs">- <code className="flex-1 select-all wrap-break-word">+ <code className="flex-1 whitespace-pre-wrap select-all wrap-break-word">{display ?? command}</code><Tooltip content="Copied!" open={copied}>- <Button onClick={copy} size="xs" variant="ghost">+ <Button aria-label={copyLabel} onClick={copy} size="xs" variant="ghost">{copied ? (<CheckIcon size={14} strokeWidth={1.5} />) : (diff --git a/frontend/src/core/config/pair.ts b/frontend/src/core/config/pair.tsnew file mode 100644index 0000000000..60bc33ee03--- /dev/null+++ b/frontend/src/core/config/pair.ts@@ -0,0 +1,19 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { atom } from "jotai";+import { z } from "zod";++export const pairPreviewSchema = z.object({+ command: z.string(),+ templates: z.object({+ prompt: z.string(),+ file: z.string(),+ session: z.string(),+ token_file: z.string(),+ token: z.string(),+ }),+});++export type PairPreviewConfig = z.infer<typeof pairPreviewSchema>;++export const pairPreviewAtom = atom<PairPreviewConfig | undefined>(undefined);diff --git a/frontend/src/mount.tsx b/frontend/src/mount.tsxindex e9446cd964..77dcfd936b 100644--- a/frontend/src/mount.tsx+++ b/frontend/src/mount.tsx@@ -10,6 +10,7 @@ import {userConfigAtom,} from "@/core/config/config";import { KnownQueryParams } from "@/core/constants";+import { pairPreviewAtom, pairPreviewSchema } from "@/core/config/pair";import { getFilenameFromDOM } from "@/core/dom/htmlUtils";import { getMarimoCode } from "@/core/meta/globals";import {@@ -208,6 +209,7 @@ const mountOptionsSchema = z.object({* marimo config overrides*/configOverrides: passthroughObject,+ pairPreview: pairPreviewSchema.optional(),/*** marimo app config*/@@ -345,6 +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);// Runtime configif (parsedOptions.data.runtimeConfig.length > 0) {diff --git a/marimo/_cli/pair/commands.py b/marimo/_cli/pair/commands.pyindex d6d77679d3..895a8df7a4 100644--- a/marimo/_cli/pair/commands.py+++ b/marimo/_cli/pair/commands.py@@ -26,7 +26,9 @@ from marimo._cli.pair.client import (registry_urls,resolve_session,)+from marimo._cli.pair.prompts import render_promptfrom marimo._server.ai.skills import utils as skills_utils+from marimo._utils.env import is_env_trueSKILL_NAME = "marimo-pair"SKILL_FILE = "SKILL.md"@@ -202,38 +204,56 @@ class _DocsCommand(ColoredCommand):cls=ColoredGroup,help="""Pair with a live marimo notebook.+ \b+ 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.+ Otherwise, these commands use MARIMO_TOKEN when set.+\bWorkflow:- If you do not have the server URL and session id:+ If you do not have the server URL or notebook file:marimo pair notebook list- marimo pair execute --url <URL> --session <SESSION> --code-file - <<'PY'+ marimo pair execute --url <URL> --file <FILE> --code-file - <<'PY'import marimo._code_mode as cmasync with cm.get_context() as ctx:ctx.packages.add("pandas")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> --file <FILE> --code-file - <<'PY'import marimo._code_mode as cmasync with cm.get_context() as ctx:cell = ctx.cells["<CELL_ID>"]print(cell.status, cell.errors, [o.data for o in cell.console_outputs])PY+ \b+ Target selection:+ If the notebook file is known, use --file <FILE> without --session.+ This resolves the notebook's current session after a page reload.+ If no file is known, use the supplied --session <SESSION>.+ If --file matches multiple sessions, use the supplied session for the intended notebook.+ If the intended session is unclear, run marimo pair notebook list again.+ Session IDs change when the page reloads. If execute reports a stale+ session, run marimo pair notebook list again.+ If both options are supplied, --session takes precedence over --file.+ Do not switch sessions after authentication or connection errors,+ or when execution is unconfirmed.+\bRules:- Cells are the unit of work. The scratchpad is temporary; only cm edits persist.+ 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.Use async with. Do not await ctx methods.Install packages with ctx.packages.add, not uv add or pip. Installs changethe project; confirm when the user did not ask.If an empty cell exists, edit_cell it instead of creating one.delete_cell drops the cell's variables. Ask before deleting.- Session IDs change when the page reloads. If execute reports a stale- session, run notebook list again.\b- Code-mode API (this marimo version):+ Code-mode API:+ Prefer marimo._code_mode to inspect, create, edit, run, and delete notebook cells.ctx.cells # each has .id .code .status .errors .console_outputsctx.create_cell(code) # returns the new cell idctx.edit_cell(cid, code)@@ -241,7 +261,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> --file <FILE> -c 'import marimo._code_mode as cm; help(cm)'""",)def pair() -> None:@@ -582,6 +602,13 @@ def docs(topic: str | None) -> None:type=str,help="Notebook path or file key from the page URL.",)+ "--session",+ "session_id",+ default=None,+ type=str,+ help="Current session ID to include in the prompt.",+)@click.option("--claude",is_flag=True,@@ -604,11 +631,12 @@ def docs(topic: str | None) -> None:"--with-token",is_flag=True,default=False,- help="Prompt for an auth token and store it in a temp file.",+ help="Prompt for an auth token and store it in a temp file. Leave empty if MARIMO_TOKEN is set.",)def prompt(url: str,file_path: str | None,+ session_id: str | None,claude: bool,codex: bool,opencode: bool,@@ -629,50 +657,75 @@ def prompt(# With an auth tokenclaude "$(uvx marimo@latest pair prompt --url 'https://localhost:8000' --claude --with-token)""""+ preview = is_env_true("MARIMO_PAIR_NEXT")+ 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,+ )++ token_file: Path | None = None+ if with_token:+ token = click.prompt(+ "Auth token (leave empty if MARIMO_TOKEN is set)",+ default="",+ show_default=False,+ hide_input=True,+ err=True,+ )+ if token:+ token_dir = _token_dir()+ url_hash = hashlib.sha256(url.encode()).hexdigest()[:6]+ token_file = token_dir / f"{url_hash}-token.txt"+ token_dir.mkdir(parents=True, exist_ok=True)+ # Open the token file for writing, creating it with restrictive+ # permissions if needed and truncating it if it already exists.+ flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC+ fd = os.open(token_file, flags, 0o600)+ try:+ os.write(fd, token.encode())+ finally:+ os.close(fd)++ if preview:+ click.echo(+ render_prompt(+ url=url,+ file_path=file_path,+ session_id=session_id,+ token_file=token_file,+ )+ )+ return+# 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 skills- 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,- )+ execute_cmd = f"execute-code.sh --url {shlex.quote(url)}"+ # The legacy script accepts only one selector. Match execute's precedence.+ if session_id:+ execute_cmd += f" --session {shlex.quote(session_id)}"+ elif file_path:+ execute_cmd += f" --file {shlex.quote(file_path)}"- # Prompt for token and write it to a temp file if --with-token is settoken_hint = ""- if with_token:- token_dir = _token_dir()- url_hash = hashlib.sha256(url.encode()).hexdigest()[:6]- token_file = token_dir / f"{url_hash}-token.txt"- token = click.prompt("Auth token", hide_input=True, err=True)- token_dir.mkdir(parents=True, exist_ok=True)- # Open the token file for writing, creating it with restrictive- # permissions if needed and truncating it if it already exists.- flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC- fd = os.open(token_file, flags, 0o600)- try:- os.write(fd, token.encode())- finally:- os.close(fd)-+ if token_file is not None:token_hint = (f"\n\nAn auth token is stored at {token_file}. "f"Pass it via `{execute_cmd} "diff --git a/marimo/_cli/pair/prompt.json b/marimo/_cli/pair/prompt.jsonnew file mode 100644index 0000000000..2fecd2b7bd--- /dev/null+++ b/marimo/_cli/pair/prompt.json@@ -0,0 +1,7 @@+{+ "prompt": "Pair with me on this running marimo notebook.\n\nURL: {url}\n{file}{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}",+ "file": "File: {file}\n",+ "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."+}diff --git a/marimo/_cli/pair/prompts.py b/marimo/_cli/pair/prompts.pynew file mode 100644index 0000000000..7271a02db3--- /dev/null+++ b/marimo/_cli/pair/prompts.py@@ -0,0 +1,51 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import shlex+from dataclasses import dataclass+from pathlib import Path++from marimo._utils.parse_dataclass import parse_raw++PAIR_COMMAND = "uv run marimo"+++@dataclass(frozen=True)+class PromptTemplates:+ prompt: str+ file: str+ session: str+ token_file: str+ token: str+++def load_prompt_templates() -> PromptTemplates:+ return parse_raw(+ Path(__file__).with_name("prompt.json").read_text(encoding="utf-8"),+ PromptTemplates,+ )+++def render_prompt(+ *,+ url: str,+ file_path: str | None = None,+ session_id: str | None = None,+ token_file: Path | None = None,+) -> str:+ templates = load_prompt_templates()+ return templates.prompt.format(+ command=PAIR_COMMAND,+ url=url,+ file=templates.file.format(file=file_path) if file_path else "",+ session=(+ templates.session.format(session=session_id) if session_id else ""+ ),+ authentication=(+ templates.token_file.format(+ token_file=shlex.quote(str(token_file))+ )+ if token_file is not None+ else ""+ ),+ )diff --git a/marimo/_templates.py b/marimo/_templates.pyindex 39cbc2b558..c5c7e4d3ec 100644--- a/marimo/_templates.py+++ b/marimo/_templates.py@@ -6,11 +6,13 @@ import htmlimport jsonimport osimport re+from dataclasses import asdictfrom pathlib import Pathfrom textwrap import dedentfrom typing import TYPE_CHECKING, Any, Literal, castfrom marimo._ast.app_config import _AppConfig+from marimo._cli.pair.prompts import PAIR_COMMAND, load_prompt_templatesfrom marimo._config.config import MarimoConfig, PartialMarimoConfigfrom marimo._convert.common.filename import parse_titlefrom marimo._convert.converters import MarimoConvert@@ -21,6 +23,7 @@ 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 is_env_truefrom marimo._utils.versions import is_editablefrom marimo._version import __version__@@ -136,6 +139,15 @@ def _get_mount_config("runtime_config": runtime_config,}+ pair_preview = ""+ if is_env_true("MARIMO_PAIR_NEXT"):+ pair_preview = ',\n "pairPreview": ' + json_script(+ {+ "command": PAIR_COMMAND,+ "templates": asdict(load_prompt_templates()),+ }+ )+return """{{"filename": {filename},"cwd": {cwd},@@ -150,9 +162,12 @@ def _get_mount_config("view": {view},"notebook": {notebook},"session": {session},- "runtimeConfig": {runtime_config}+ "runtimeConfig": {runtime_config}{pair_preview}}}-""".format(**{k: json_script(v) for k, v in options.items()}).strip()+""".format(+ **{k: json_script(v) for k, v in options.items()},+ pair_preview=pair_preview,+ ).strip()def home_page_template(diff --git a/tests/_cli/test_cli_pair.py b/tests/_cli/test_cli_pair.pyindex 2ac4735aec..51bba2a054 100644--- a/tests/_cli/test_cli_pair.py+++ b/tests/_cli/test_cli_pair.py@@ -3,6 +3,8 @@ from __future__ import annotationsimport hashlibimport json+import re+import shleximport sysfrom pathlib import Pathfrom typing import Any@@ -36,6 +38,11 @@ _runner = CliRunner()TEST_URL = "https://localhost:8000?auth=tok123"[email protected](autouse=True)+def _isolate_pair_preview(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("MARIMO_PAIR_NEXT", raising=False)++class TestPairGroup:def test_pair_help(self) -> None:result = _runner.invoke(cli_main, ["pair", "--help"])@@ -47,35 +54,51 @@ 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.+ Otherwise, these commands use MARIMO_TOKEN when set.+Workflow:- If you do not have the server URL and session id:+ If you do not have the server URL or notebook file:marimo pair notebook list- marimo pair execute --url <URL> --session <SESSION> --code-file - <<'PY'+ marimo pair execute --url <URL> --file <FILE> --code-file - <<'PY'import marimo._code_mode as cmasync with cm.get_context() as ctx:ctx.packages.add("pandas")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> --file <FILE> --code-file - <<'PY'import marimo._code_mode as cmasync with cm.get_context() as ctx:cell = ctx.cells["<CELL_ID>"]print(cell.status, cell.errors, [o.data for o in cell.console_outputs])PY+ Target selection:+ If the notebook file is known, use --file <FILE> without --session.+ This resolves the notebook's current session after a page reload.+ If no file is known, use the supplied --session <SESSION>.+ If --file matches multiple sessions, use the supplied session for the intended notebook.+ If the intended session is unclear, run marimo pair notebook list again.+ Session IDs change when the page reloads. If execute reports a stale+ session, run marimo pair notebook list again.+ If both options are supplied, --session takes precedence over --file.+ Do not switch sessions after authentication or connection errors,+ or when execution is unconfirmed.+Rules:- Cells are the unit of work. The scratchpad is temporary; only cm edits persist.+ 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.Use async with. Do not await ctx methods.Install packages with ctx.packages.add, not uv add or pip. Installs changethe project; confirm when the user did not ask.If an empty cell exists, edit_cell it instead of creating one.delete_cell drops the cell's variables. Ask before deleting.- Session IDs change when the page reloads. If execute reports a stale- session, run notebook list again.- Code-mode API (this marimo version):+ Code-mode API:+ Prefer marimo._code_mode to inspect, create, edit, run, and delete notebook cells.ctx.cells # each has .id .code .status .errors .console_outputsctx.create_cell(code) # returns the new cell idctx.edit_cell(cid, code)@@ -83,7 +106,7 @@ 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> --file <FILE> -c 'import marimo._code_mode as cm; help(cm)'Options:-h, --help Show this message and exit.@@ -103,7 +126,7 @@ Commands:assert "--codex" in result.outputassert "--opencode" in result.outputassert "--file" in result.output- assert "--session" not in result.output+ assert "--session" in result.outputclass TestPairExecute:@@ -1321,14 +1344,23 @@ class TestPairPrompt:result = _runner.invoke(cli_main, ["pair", "prompt"])assert result.exit_code != 0- def test_prompt_outputs_url(self) -> None:+ @pytest.mark.parametrize("flag", [None, "0", "false", ""])+ def test_prompt_outputs_url(self, flag: str | None) -> None:result = _runner.invoke(- cli_main, ["pair", "prompt", "--url", TEST_URL]+ cli_main,+ ["pair", "prompt", "--url", TEST_URL],+ env={"MARIMO_PAIR_NEXT": flag},)assert result.exit_code == 0- assert TEST_URL in result.output- assert "execute-code.sh" in result.output- assert "marimo-pair" in result.output+ 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.+""")def test_prompt_with_file(self) -> None:result = _runner.invoke(@@ -1355,13 +1387,62 @@ class TestPairPrompt:assert "--file" not in result.outputassert "--session" not in result.output- def test_prompt_rejects_removed_session_option(self) -> None:+ 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 "--session" in result.output+ 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.+""")++ @pytest.mark.parametrize("flag", [None, "0", "false", ""])+ @pytest.mark.parametrize("with_token", [False, True])+ def test_legacy_prompt_with_both_selectors_uses_session(+ self, tmp_path: Path, flag: str | None, with_token: bool+ ) -> None:+ args = [+ "pair",+ "prompt",+ "--url",+ TEST_URL,+ "--file",+ "notebooks/my notebook.py",+ "--session",+ "s_ab12cd",+ ]+ if with_token:+ args.append("--with-token")+ with patch.object(commands, "_token_dir", return_value=tmp_path):+ result = _runner.invoke(+ cli_main,+ args,+ input="test-token\n" if with_token else None,+ env={"MARIMO_PAIR_NEXT": flag},+ )++ assert result.exit_code == 0+ execution_commands = re.findall(+ r"`(execute-code\.sh [^`]+)`", result.stdout+ )+ assert len(execution_commands) == (2 if with_token else 1)+ for command in execution_commands:+ argv = shlex.split(command)+ assert argv[:5] == [+ "execute-code.sh",+ "--url",+ TEST_URL,+ "--session",+ "s_ab12cd",+ ]+ assert "--file" not in argvdef test_prompt_shell_quotes_file_paths(self) -> None:cases = [@@ -1455,7 +1536,172 @@ class TestPairPrompt:assert "could not be found" not in result.output+class TestPairPromptPreview:+ 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 `uv run marimo pair --help` first.+Use `uv run marimo` 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 `uv run marimo pair --help` first.+Use `uv run marimo` 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}",+ "--file",+ "{command}/it's notebook.py",+ "--session",+ "{file}",+ ],+ 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}+File: {command}/it's notebook.py+Session: {file}++Run `uv run marimo pair --help` first.+Use `uv run marimo` 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",+ "--file",+ "notebook.py",+ ],+ 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+File: notebook.py++Run `uv run marimo pair --help` first.+Use `uv run marimo` 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:diff --git a/tests/_server/templates/test_templates_api.py b/tests/_server/templates/test_templates_api.pyindex 4351776e5d..0011bb0470 100644--- a/tests/_server/templates/test_templates_api.py+++ b/tests/_server/templates/test_templates_api.py@@ -3,6 +3,9 @@ from __future__ import annotationsimport unittest+import pytest+from inline_snapshot import snapshot+from marimo._schemas.session import (VERSION,Cell,@@ -17,6 +20,42 @@ from marimo._server.templates.api import (from tests._server.templates.utils import parse_mount_config[email protected]("flag", ["1", "true", " TRUE "])+def test_render_notebook_pair_preview(+ monkeypatch: pytest.MonkeyPatch, flag: str+) -> None:+ monkeypatch.setenv("MARIMO_PAIR_NEXT", flag)+ html = render_notebook(+ code="import marimo\napp = marimo.App()", mode="edit"+ )+ assert parse_mount_config(html)["pairPreview"] == snapshot(+ {+ "command": "uv run marimo",+ "templates": {+ "prompt": "Pair with me on this running marimo notebook.\n\nURL: {url}\n{file}{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}",+ "file": "File: {file}\n",+ "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.",+ },+ }+ )++[email protected]("flag", [None, "", "0", "false"])+def test_render_notebook_omits_pair_preview(+ monkeypatch: pytest.MonkeyPatch, flag: str | None+) -> None:+ if flag is None:+ monkeypatch.delenv("MARIMO_PAIR_NEXT", raising=False)+ else:+ monkeypatch.setenv("MARIMO_PAIR_NEXT", flag)+ html = render_notebook(+ code="import marimo\napp = marimo.App()", mode="edit"+ )+ assert "pairPreview" not in parse_mount_config(html)++class TestRenderNotebook(unittest.TestCase):def setUp(self) -> None:self.code = """