Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat(pair): target notebooks by stable session ID (#11013)

Kiran Gadhavea5d03aa6fbc5
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.ts
index d04582725c..cd59d075bf 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
@@ -154,63 +154,54 @@ describe("getTerminalCommand", () => {
).toBe(
String.raw`${cli} "$(MARIMO_PAIR_NEXT=1 uvx marimo@latest pair prompt \
--url http://localhost:8000 \
- --file notebooks/example.py \
--session s_ab12cd \
--with-token)"`,
);
},
);
- it("includes the url and file for each agent", () => {
+ 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 --file notebooks/example.py --claude)"`,
+ `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 --file notebooks/example.py --codex)"`,
+ `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 --file notebooks/example.py --opencode)"`,
+ `opencode --prompt "$(uv run marimo pair prompt --url http://localhost:8000 --opencode)"`,
);
});
- it("omits the file flag when the page URL has no file", () => {
- const command = getTerminalCommand(
- "claude",
- CONNECTION_WITHOUT_FILE,
- false,
- );
+ it("never passes a file to marimo pair prompt", () => {
+ const command = getTerminalCommand("claude", CONNECTION, false);
expect(command).not.toContain("--file");
- expect(command).not.toContain("--session");
+ expect(command).not.toContain("notebooks/example.py");
});
- it("shell-escapes a url containing metacharacters", () => {
- const command = getTerminalCommand(
- "claude",
- { url: "http://host:8000?auth=a&b", file: "notebook.py" },
- false,
+ it("omits the session outside the preview", () => {
+ expect(getTerminalCommand("claude", CONNECTION, false)).not.toContain(
+ "--session",
);
- 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) => {
+ 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", () => {
const command = getTerminalCommand(
"claude",
- { url: CONNECTION.url, file },
+ { url: "http://host:8000?auth=a&b" },
false,
);
- expect(command).toContain(expected);
+ expect(command).toContain("--url 'http://host:8000?auth=a&b'");
});
it("adds --with-token before the agent flag when requested", () => {
@@ -230,23 +221,22 @@ describe("getRawPrompt", () => {
expect(
getRawPrompt(
{
- url: "http://host/{file}",
- file: "{session}/it's.py",
- session: "{command}",
+ url: "http://host/{session}",
+ session: "{command}/it's",
},
- "tok'en {file} $&",
+ "tok'en {session} $&",
{
...PAIR_PREVIEW,
command: "custom marimo",
templates: {
...PAIR_PREVIEW.templates,
- prompt: "{command}\n{url}\n{file}{session}{authentication}",
+ prompt: "{command}\n{url}\n{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.`,
+ "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.`,
);
});
@@ -256,10 +246,7 @@ describe("getRawPrompt", () => {
{ ...CONNECTION_WITHOUT_FILE, session: "s_ab12cd" },
"Session: s_ab12cd\n",
],
- [
- { ...CONNECTION_WITHOUT_FILE, file: "notebook.py" },
- "File: notebook.py\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" +
@@ -270,13 +257,12 @@ describe("getRawPrompt", () => {
);
});
- it("renders the shared preview template with optional session context", () => {
+ it("renders the shared preview template with the session and no file", () => {
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 `uvx marimo@latest pair --help` first.\n" +
"Use `uvx marimo@latest` for all marimo commands.\n\n" +
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.tsx
index 4be3699474..3f55d63326 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
@@ -15,7 +15,10 @@ 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 {
+ type StableSessionId,
+ stableSessionIdAtom,
+} from "@/core/kernel/session";
import { filenameAtom } from "@/core/saving/file-state";
import {
DEFAULT_RUNTIME_CONFIG,
@@ -39,10 +42,13 @@ function wrapper({ children }: { children: React.ReactNode }) {
);
}
+const STABLE_ID = "sess-stable-1" as StableSessionId;
+
describe("PairWithAgentModal", () => {
beforeEach(() => {
vi.clearAllMocks();
store.set(pairPreviewAtom, PAIR_PREVIEW);
+ store.set(stableSessionIdAtom, STABLE_ID);
store.set(filenameAtom, "/project/my notebook.py");
store.set(runtimeConfigAtom, {
...DEFAULT_RUNTIME_CONFIG,
@@ -57,12 +63,13 @@ describe("PairWithAgentModal", () => {
afterEach(() => {
store.set(pairPreviewAtom, undefined);
+ store.set(stableSessionIdAtom, null);
store.set(filenameAtom, null);
vi.unstubAllGlobals();
});
it.each(["Claude", "Codex", "OpenCode", "Prompt"])(
- "omits skill installation and includes the current session in %s preview",
+ "omits skill installation and targets the stable session in %s preview",
async (tab) => {
await act(async () => {
render(<PairWithAgentModal onClose={vi.fn()} />, { wrapper });
@@ -74,59 +81,41 @@ describe("PairWithAgentModal", () => {
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(STABLE_ID);
+ expect(panel).not.toHaveTextContent("--file");
+ expect(panel).not.toHaveTextContent("File:");
+ expect(panel).not.toHaveTextContent("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);
+ const copied = vi.mocked(copyToClipboard).mock.calls[0][0];
+ expect(copied).toContain(STABLE_ID);
+ expect(copied).not.toContain("notebook.py");
},
);
- it.each([null, ""])(
- "omits the file when the URL and notebook filename are absent (%s)",
- async (filename) => {
- window.history.replaceState({}, "", "/");
- store.set(filenameAtom, filename);
+ it.each(["Claude", "Prompt"])(
+ "omits the session in %s preview before kernel-ready arrives",
+ async (tab) => {
+ store.set(stableSessionIdAtom, null);
await act(async () => {
render(<PairWithAgentModal onClose={vi.fn()} />, { wrapper });
});
- expect(screen.getByRole("tabpanel")).not.toHaveTextContent("--file");
- fireEvent.mouseDown(screen.getByRole("tab", { name: "Prompt" }), {
+ fireEvent.mouseDown(screen.getByRole("tab", { name: tab }), {
button: 0,
ctrlKey: false,
});
- expect(screen.getByRole("tabpanel")).not.toHaveTextContent("File:");
+
+ const panel = screen.getByRole("tabpanel");
+ expect(panel).not.toHaveTextContent("--session");
+ expect(panel).not.toHaveTextContent("Session:");
+ expect(panel).toHaveTextContent("http://localhost:8000");
},
);
@@ -147,7 +136,8 @@ describe("PairWithAgentModal", () => {
expect(
within(panel).getByText("npx skills add marimo-team/marimo-pair"),
).toBeVisible();
- expect(panel).not.toHaveTextContent(getSessionId());
+ expect(panel).not.toHaveTextContent(STABLE_ID);
+ expect(panel).not.toHaveTextContent("--file");
expect(panel).not.toHaveTextContent("MARIMO_PAIR_NEXT");
expect(panel).not.toHaveTextContent("/project/my notebook.py");
expect(panel).toHaveTextContent(
@@ -205,8 +195,7 @@ describe("PairWithAgentModal", () => {
expect(copyToClipboard).toHaveBeenCalledWith(
String.raw`claude "$(MARIMO_PAIR_NEXT=1 uvx marimo@latest pair prompt \
--url http://localhost:8000/ \
- --file notebook.py \
- --session ${getSessionId()} \
+ --session ${STABLE_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.ts
index 9c4cc62b4e..454ecdbfbb 100644
--- a/frontend/src/components/editor/actions/pair-with-agent-commands.ts
+++ b/frontend/src/components/editor/actions/pair-with-agent-commands.ts
@@ -38,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 or notebook filename, when known. */
+ /** The server's file key, when known. */
file?: string;
+ /** The stable session ID, when known. */
session?: string;
}
@@ -49,7 +50,7 @@ export interface ConnectionInfo {
*/
export function getTerminalCommand(
agent: Exclude<AgentTab, "prompt">,
- { url, file, session }: ConnectionInfo,
+ { url, session }: ConnectionInfo,
withToken: boolean,
preview?: PairPreviewConfig,
): string {
@@ -58,7 +59,6 @@ export function getTerminalCommand(
const base = [
`${prefix}${command} pair prompt`,
`--url ${shellQuote(url)}`,
- file ? `--file ${shellQuote(file)}` : "",
preview && session ? `--session ${shellQuote(session)}` : "",
withToken ? "--with-token" : "",
preview ? "" : `--${agent}`,
@@ -92,7 +92,6 @@ export function getRawPrompt(
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) })
diff --git a/frontend/src/components/editor/actions/pair-with-agent-modal.tsx b/frontend/src/components/editor/actions/pair-with-agent-modal.tsx
index b1ae62a12f..289b377eeb 100644
--- a/frontend/src/components/editor/actions/pair-with-agent-modal.tsx
+++ b/frontend/src/components/editor/actions/pair-with-agent-modal.tsx
@@ -18,8 +18,7 @@ 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 { stableSessionIdAtom } from "@/core/kernel/session";
import {
AGENT_LABELS,
AGENT_TABS,
@@ -54,16 +53,14 @@ export const PairWithAgentModal: React.FC<{
const [activeTab, setActiveTab] = useState<AgentTab>("claude");
const runtimeManager = useRuntimeManager();
const preview = useAtomValue(pairPreviewAtom);
- const filename = useFilename();
+ const stableSessionId = useAtomValue(stableSessionIdAtom);
const commandStep = preview ? 1 : 2;
const authToken = useAuthToken();
const hasToken = Boolean(authToken);
const connection: ConnectionInfo = {
url: runtimeManager.httpURL.toString(),
- file:
- getFileFromURL(window.location.href) ??
- (preview ? filename || undefined : undefined),
- session: preview ? getSessionId() : undefined,
+ file: preview ? undefined : getFileFromURL(window.location.href),
+ session: preview ? (stableSessionId ?? undefined) : undefined,
};
return (
diff --git a/frontend/src/core/config/pair.ts b/frontend/src/core/config/pair.ts
index 60bc33ee03..bb5756b0c9 100644
--- a/frontend/src/core/config/pair.ts
+++ b/frontend/src/core/config/pair.ts
@@ -7,7 +7,6 @@ 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(),
diff --git a/frontend/src/core/kernel/session.ts b/frontend/src/core/kernel/session.ts
index af894e1dcb..3fac04f9c1 100644
--- a/frontend/src/core/kernel/session.ts
+++ b/frontend/src/core/kernel/session.ts
@@ -1,5 +1,6 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { init } from "@paralleldrive/cuid2";
+import { atom } from "jotai";
import { Logger } from "@/utils/Logger";
import type { TypedString } from "@/utils/typed";
import { updateQueryParams } from "@/utils/urls";
@@ -9,6 +10,14 @@ import { store } from "../state/jotai";
export type SessionId = TypedString<"SessionId">;
+/**
+ * Server-owned identity of the notebook Session. It survives browser reloads
+ * and reconnects and ends with the Session.
+ */
+export type StableSessionId = TypedString<"StableSessionId">;
+
+export const stableSessionIdAtom = atom<StableSessionId | null>(null);
+
const createId = init({ length: 6 });
export function generateSessionId(): SessionId {
diff --git a/frontend/src/core/websocket/useMarimoKernelConnection.tsx b/frontend/src/core/websocket/useMarimoKernelConnection.tsx
index 0548beeb61..601a9e0f58 100644
--- a/frontend/src/core/websocket/useMarimoKernelConnection.tsx
+++ b/frontend/src/core/websocket/useMarimoKernelConnection.tsx
@@ -60,7 +60,11 @@ import {
handleRemoveUIElements,
} from "../kernel/handlers";
import { queryParamHandlers } from "../kernel/queryParamHandlers";
-import type { SessionId } from "../kernel/session";
+import {
+ type SessionId,
+ type StableSessionId,
+ stableSessionIdAtom,
+} from "../kernel/session";
import { initialRunCompletedAtom, kernelStateAtom } from "../kernel/state";
import { type LayoutState, useLayoutActions } from "../layout/state";
import { kioskModeAtom } from "../mode";
@@ -231,6 +235,7 @@ export function useMarimoKernelConnection(opts: {
addStartupLog,
} = useAlertActions();
const setKioskMode = useSetAtom(kioskModeAtom);
+ const setStableSessionId = useSetAtom(stableSessionIdAtom);
const setCapabilities = useSetAtom(capabilitiesAtom);
const runtimeManager = useRuntimeManager();
const transportType = useAtomValue(connectionTransportTypeAtom);
@@ -284,6 +289,10 @@ export function useMarimoKernelConnection(opts: {
invalidateDataSourceDiscovery();
}
setKioskMode(msg.data.kiosk);
+ setStableSessionId(
+ (msg.data.stable_session_id as StableSessionId | null | undefined) ??
+ null,
+ );
// A freshly started kernel has no breakpoints of its own; re-push
// the client's set so they still apply, and clear the stale
// highlighted line from the previous kernel instance.
diff --git a/marimo/_cli/pair/client.py b/marimo/_cli/pair/client.py
index 090314b4e9..811779788d 100644
--- a/marimo/_cli/pair/client.py
+++ b/marimo/_cli/pair/client.py
@@ -3,7 +3,6 @@ from __future__ import annotations
import http.client
import json
-import os
from dataclasses import dataclass
from typing import TYPE_CHECKING
from urllib.parse import urlsplit
@@ -45,6 +44,10 @@ class StaleSessionError(PairError):
"""The server rejected the session ID as unknown."""
+class StableSessionUnsupportedError(PairError):
+ """The server cannot resolve stable session IDs."""
+
+
@dataclass(frozen=True)
class SSEEvent:
name: str
@@ -183,10 +186,12 @@ def _raise_for_status(response: HTTPResponse) -> None:
return
detail = _response_detail(response)
response.close()
- if isinstance(detail, str) and detail.startswith("Invalid session id"):
+ if isinstance(detail, str) and detail.startswith(
+ ("Invalid session id", "Invalid stable session id")
+ ):
raise StaleSessionError(detail)
if detail == "Missing Marimo-Session-Id header":
- raise PairError("Internal: should not happen after resolution.")
+ raise StableSessionUnsupportedError
if detail:
raise PairError(detail)
raise PairError(f"Server returned {response.status}.")
@@ -205,7 +210,7 @@ def execute(
request_url = _endpoint_url(url, "/api/kernel/execute")
headers = {
"Content-Type": "application/json",
- "Marimo-Session-Id": session_id,
+ "Marimo-Stable-Session-Id": session_id,
}
if token is not None:
headers["Authorization"] = f"Bearer {token}"
@@ -314,54 +319,42 @@ def list_sessions(
raise PairError(message)
if "filename" not in session or "path" not in session:
raise PairError(message)
+ if "session_id" not in session:
+ raise StableSessionUnsupportedError
+ stable_session_id = session["session_id"]
filename = session["filename"]
path = session["path"]
- if (filename is not None and not isinstance(filename, str)) or (
- path is not None and not isinstance(path, str)
+ if (
+ not isinstance(stable_session_id, str)
+ or (filename is not None and not isinstance(filename, str))
+ or (path is not None and not isinstance(path, str))
):
raise PairError(message)
- sessions[session_id] = {"filename": filename, "path": path}
+ sessions[session_id] = {
+ "session_id": stable_session_id,
+ "filename": filename,
+ "path": path,
+ }
return sessions
-def resolve_session(*, url: str, token: str | None, file: str | None) -> str:
+def resolve_session(*, url: str, token: str | None) -> str:
sessions = list_sessions(url=url, token=token)
safe_url = display_url(url)
- if file is None:
- candidates = list(sessions)
- else:
- for field, value in (
- ("path", file),
- ("filename", file),
- ("path", os.path.abspath(file)),
- ):
- candidates = [
- session_id
- for session_id, session in sessions.items()
- if session[field] == value
- ]
- if candidates:
- break
-
- if len(candidates) == 1:
- return candidates[0]
- if not candidates:
- if file is None:
- message = f"No running session on {safe_url}."
- else:
- message = (
- f"No running session for notebook '{file}' on {safe_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.sort()
- if file is None:
- message = f"Server {safe_url} has {len(candidates)} running sessions."
- else:
- message = (
- f"Notebook '{file}' has {len(candidates)} running sessions "
- f"on {safe_url}."
- )
+ candidates = sorted(
+ session["session_id"]
+ for session in sessions.values()
+ if session["session_id"] is not None
+ )
+ message = f"Server {safe_url} has {len(candidates)} running sessions."
raise AmbiguousSessionError(
message, url=safe_url, candidates=tuple(candidates)
)
diff --git a/marimo/_cli/pair/commands.py b/marimo/_cli/pair/commands.py
index 50740e8466..d0edc349cd 100644
--- a/marimo/_cli/pair/commands.py
+++ b/marimo/_cli/pair/commands.py
@@ -18,6 +18,7 @@ from marimo._cli.pair.client import (
NoSessionError,
PairError,
PairInputError,
+ StableSessionUnsupportedError,
StaleSessionError,
display_url,
execute as execute_code,
@@ -213,16 +214,16 @@ class _DocsCommand(ColoredCommand):
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 notebook file:
+ If you do not have the server URL or session:
marimo pair notebook list
- marimo pair execute --url <URL> --file <FILE> --code-file - <<'PY'
+ marimo pair execute --url <URL> --session <SESSION> --code-file - <<'PY'
import marimo._code_mode as cm
async 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> --file <FILE> --code-file - <<'PY'
+ marimo pair execute --url <URL> --session <SESSION> --code-file - <<'PY'
import marimo._code_mode as cm
async with cm.get_context() as ctx:
cell = ctx.cells["<CELL_ID>"]
@@ -231,14 +232,11 @@ class _DocsCommand(ColoredCommand):
\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.
+ --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,
or when execution is unconfirmed.
@@ -263,7 +261,7 @@ class _DocsCommand(ColoredCommand):
ctx.delete_cell(cid)
ctx.packages.add("pandas>=2") # queued, installs on exit
If a cm call fails, run help(cm):
- marimo pair execute --url <URL> --file <FILE> -c 'import marimo._code_mode as cm; help(cm)'
+ marimo pair execute --url <URL> --session <SESSION> -c 'import marimo._code_mode as cm; help(cm)'
""",
)
def pair() -> None:
@@ -286,14 +284,7 @@ def pair() -> None:
"session_id",
required=False,
metavar="ID",
- help="Current session ID. Resolved from --file when omitted.",
-)
- "--file",
- "file_path",
- required=False,
- metavar="PATH",
- help="Notebook path or file key. Used to resolve --session when omitted.",
+ help="Stable session_id from marimo pair notebook list.",
)
@click.option(
"--token-file",
@@ -322,7 +313,6 @@ def execute(
ctx: click.Context,
url: str,
session_id: str | None,
- file_path: str | None,
token_file: Path | None,
code: str | None,
code_file: str | None,
@@ -345,7 +335,7 @@ def execute(
try:
token = load_token(token_file, os.environ)
if session_id is None:
- session_id = resolve_session(url=url, token=token, file=file_path)
+ session_id = resolve_session(url=url, token=token)
result = execute_code(
url=url,
session_id=session_id,
@@ -506,10 +496,21 @@ def _failure_guidance(
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):
+ return (
+ (
+ f"Server {safe_url} runs a marimo version without "
+ "session_id. Upgrade marimo on the server."
+ ),
+ None,
+ )
if isinstance(error, StaleSessionError):
- return "The session is stale.", (
- "Sessions change when the page reloads. List them again:\n"
- f"marimo pair notebook list --url {safe_url}"
+ return (
+ (
+ f"No session {session_id or '<ID>'} on {safe_url}. "
+ "The notebook was closed or restarted."
+ ),
+ f"marimo pair notebook list --url {safe_url}",
)
message = str(error)
if message == "Authentication failed.":
@@ -597,19 +598,12 @@ def docs(topic: str | None) -> None:
type=str,
help="URL of the running marimo kernel.",
)
- "--file",
- "file_path",
- default=None,
- type=str,
- help="Notebook path or file key from the page URL.",
-)
@click.option(
"--session",
"session_id",
default=None,
type=str,
- help="Current session ID to include in the prompt.",
+ help="Stable session_id to include in the prompt.",
)
@click.option(
"--claude",
@@ -637,7 +631,6 @@ def docs(topic: str | None) -> None:
)
def prompt(
url: str,
- file_path: str | None,
session_id: str | None,
claude: bool,
codex: bool,
@@ -654,7 +647,7 @@ def prompt(
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' --file 'notebooks/example.py' --claude)"
+ 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)"
@@ -708,23 +701,17 @@ def prompt(
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.
+ # shell and values may contain spaces or metacharacters.
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)}"
token_hint = ""
if token_file is not None:
@@ -734,13 +721,11 @@ def prompt(
f"--token \"$(cat '{token_file}')\"`."
)
- file_hint = f" (file {file_path})" if file_path else ""
-
# Output the prompt to the wrapper agent CLI
click.echo(
"Use the /marimo-pair skill to pair-program on a running "
"marimo notebook.\n\n"
- f"Connect to the notebook at: {url}{file_hint}\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"
@@ -762,7 +747,7 @@ def _group_notebooks(
url: str, sessions: dict[str, dict[str, str | None]]
) -> list[dict[str, object]]:
grouped: dict[str | None, dict[str, object]] = {}
- for session_id, session in sessions.items():
+ for routing_id, session in sessions.items():
key = session.get("path") or session.get("filename")
notebook = grouped.setdefault(
key,
@@ -775,7 +760,9 @@ def _group_notebooks(
)
notebook_sessions = notebook["sessions"]
assert isinstance(notebook_sessions, list)
- notebook_sessions.append({"id": session_id})
+ notebook_sessions.append(
+ {"id": routing_id, "session_id": session["session_id"]}
+ )
for notebook in grouped.values():
notebook_sessions = notebook["sessions"]
@@ -827,10 +814,16 @@ 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
- message = str(error).rstrip(".")
- warnings.append(
- f"Server {display_url(url)} could not be read: {message}."
- )
+ if isinstance(error, StableSessionUnsupportedError):
+ warnings.append(
+ f"Server {display_url(url)} runs a marimo version "
+ "without session_id. Upgrade marimo on the server."
+ )
+ else:
+ message = str(error).rstrip(".")
+ warnings.append(
+ f"Server {display_url(url)} could not be read: {message}."
+ )
else:
notebooks.extend(_group_notebooks(display_url(url), sessions))
diff --git a/marimo/_cli/pair/prompt.json b/marimo/_cli/pair/prompt.json
index 2fecd2b7bd..15f445719d 100644
--- a/marimo/_cli/pair/prompt.json
+++ b/marimo/_cli/pair/prompt.json
@@ -1,6 +1,5 @@
{
- "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",
+ "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."
diff --git a/marimo/_cli/pair/prompts.py b/marimo/_cli/pair/prompts.py
index dec5278406..34640929d1 100644
--- a/marimo/_cli/pair/prompts.py
+++ b/marimo/_cli/pair/prompts.py
@@ -16,7 +16,6 @@ def get_pair_command() -> str:
@dataclass(frozen=True)
class PromptTemplates:
prompt: str
- file: str
session: str
token_file: str
token: str
@@ -32,7 +31,6 @@ def load_prompt_templates() -> PromptTemplates:
def render_prompt(
*,
url: str,
- file_path: str | None = None,
session_id: str | None = None,
token_file: Path | None = None,
) -> str:
@@ -40,7 +38,6 @@ def render_prompt(
return templates.prompt.format(
command=get_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 ""
),
diff --git a/marimo/_messaging/notification.py b/marimo/_messaging/notification.py
index 3315584f79..629e5a98f3 100644
--- a/marimo/_messaging/notification.py
+++ b/marimo/_messaging/notification.py
@@ -42,6 +42,7 @@ from marimo._sql.parse import SqlCatalogCheckResult, SqlParseResult
from marimo._types.ids import (
CellId_t,
RequestId,
+ StableSessionId,
UIElementId,
VariableName,
WidgetModelId,
@@ -434,6 +435,8 @@ class KernelReadyNotification(Notification, tag="kernel-ready"):
kiosk: Whether running in kiosk mode.
capabilities: Available kernel capabilities.
auto_instantiated: Whether cells already executed (run mode).
+ stable_session_id: Server-owned Session identity that survives
+ browser reconnects. None where no server Session exists.
"""
name: ClassVar[str] = "kernel-ready"
@@ -451,6 +454,7 @@ class KernelReadyNotification(Notification, tag="kernel-ready"):
capabilities: KernelCapabilitiesNotification
consumer_capabilities: ConsumerCapabilities
auto_instantiated: bool = False
+ stable_session_id: StableSessionId | None = None
class CompletionResultNotification(Notification, tag="completion-result"):
diff --git a/marimo/_server/api/deps.py b/marimo/_server/api/deps.py
index 0e87e338b5..14109b94d6 100644
--- a/marimo/_server/api/deps.py
+++ b/marimo/_server/api/deps.py
@@ -10,7 +10,7 @@ from marimo._server.config import StarletteServerState
from marimo._server.session_manager import SessionManager
from marimo._server.tokens import SkewProtectionToken
from marimo._session.model import SessionMode
-from marimo._types.ids import SessionId
+from marimo._types.ids import SessionId, StableSessionId
from marimo._utils.http import HTTPException, HTTPStatus
if TYPE_CHECKING:
@@ -24,6 +24,8 @@ if TYPE_CHECKING:
LOGGER = loggers.marimo_logger()
+STABLE_SESSION_ID_HEADER = "Marimo-Stable-Session-Id"
+
class AppStateBase:
"""The app state."""
@@ -171,6 +173,30 @@ class AppState(AppStateBase):
raise ValueError(f"Invalid session id: {session_id}")
return session
+ def require_current_session_with_stable_id(self) -> Session:
+ """Resolve a session from the stable or browser routing header."""
+ stable_session_id = self.request.headers.get(STABLE_SESSION_ID_HEADER)
+ if stable_session_id is None:
+ return self.require_current_session()
+ if self.get_current_session_id() is not None:
+ raise HTTPException(
+ status_code=HTTPStatus.BAD_REQUEST,
+ detail=(
+ f"{STABLE_SESSION_ID_HEADER} cannot be combined with "
+ "Marimo-Session-Id."
+ ),
+ )
+
+ session = self.session_manager.get_session_by_stable_id(
+ StableSessionId(stable_session_id)
+ )
+ if session is None:
+ raise HTTPException(
+ status_code=HTTPStatus.NOT_FOUND,
+ detail=f"Invalid stable session id: {stable_session_id}",
+ )
+ return session
+
def require_query_params(self, param: str) -> str:
"""Get a query parameter or raise an error."""
value = self.request.query_params[param]
diff --git a/marimo/_server/api/endpoints/execution.py b/marimo/_server/api/endpoints/execution.py
index b1cb35d79e..bb622bf50e 100644
--- a/marimo/_server/api/endpoints/execution.py
+++ b/marimo/_server/api/endpoints/execution.py
@@ -337,7 +337,7 @@ async def execute_code(
app_state = AppState(request)
body = await parse_request(request, cls=ExecuteScratchpadRequest)
- session = app_state.require_current_session()
+ session = app_state.require_current_session_with_stable_id()
# Register cells into the graph without executing them so that
# code_mode's run_cell can resolve dependencies. The kernel
diff --git a/marimo/_server/api/endpoints/health.py b/marimo/_server/api/endpoints/health.py
index b0bd1a8210..67494beab9 100644
--- a/marimo/_server/api/endpoints/health.py
+++ b/marimo/_server/api/endpoints/health.py
@@ -25,6 +25,8 @@ from marimo._version import __version__
if TYPE_CHECKING:
from starlette.requests import Request
+ from marimo._types.ids import StableSessionId
+
LOGGER = _loggers.marimo_logger()
# Router for health/status endpoints
@@ -95,6 +97,7 @@ async def status(request: Request) -> JSONResponse:
class SessionInfo(TypedDict):
+ session_id: StableSessionId
filename: str | None
path: str | None
@@ -108,6 +111,7 @@ async def list_sessions(request: Request) -> JSONResponse:
sessions = {
session_id: SessionInfo(
+ session_id=session.stable_id,
filename=session.app_file_manager.filename,
path=session.app_file_manager.path,
)
diff --git a/marimo/_server/api/endpoints/ws/ws_kernel_ready.py b/marimo/_server/api/endpoints/ws/ws_kernel_ready.py
index 724b07b93a..8a338acc0d 100644
--- a/marimo/_server/api/endpoints/ws/ws_kernel_ready.py
+++ b/marimo/_server/api/endpoints/ws/ws_kernel_ready.py
@@ -93,6 +93,7 @@ def build_kernel_ready(
),
capabilities=KernelCapabilitiesNotification(),
auto_instantiated=auto_instantiated,
+ stable_session_id=session.stable_id,
)
diff --git a/marimo/_server/session_manager.py b/marimo/_server/session_manager.py
index 76665e642f..bd6e410fae 100644
--- a/marimo/_server/session_manager.py
+++ b/marimo/_server/session_manager.py
@@ -50,7 +50,7 @@ from marimo._session.session import Session, SessionImpl
from marimo._session.session_repository import SessionRepository
from marimo._session.startup import SessionStartup
from marimo._session.types import KernelState
-from marimo._types.ids import ConsumerId, SessionId
+from marimo._types.ids import ConsumerId, SessionId, StableSessionId
from marimo._utils.asyncio_utils import fire_and_forget
from marimo._utils.file_watcher import FileWatcherManager
@@ -481,6 +481,19 @@ class SessionManager:
# Search for kiosk sessions by consumer ID
return self._repository.get_by_consumer_id(ConsumerId(session_id))
+ def get_session_by_stable_id(
+ self, stable_session_id: StableSessionId
+ ) -> Session | None:
+ """Get a session by its stable ID."""
+ return next(
+ (
+ session
+ for session in self._repository.get_all()
+ if session.stable_id == stable_session_id
+ ),
+ None,
+ )
+
def get_session_by_file_key(
self, file_key: MarimoFileKey
) -> Session | None:
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index b398dbfbf4..3b8013da27 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -3038,7 +3038,8 @@ components:
\ per cell if resumed.\n app_config: Application configuration.\n \
\ kiosk: Whether running in kiosk mode.\n capabilities: Available\
\ kernel capabilities.\n auto_instantiated: Whether cells already executed\
- \ (run mode)."
+ \ (run mode).\n stable_session_id: Server-owned Session identity that\
+ \ survives\n browser reconnects. None where no server Session exists."
properties:
app_config:
$ref: '#/components/schemas/_AppConfig'
@@ -3088,6 +3089,11 @@ components:
- kernel-ready
resumed:
type: boolean
+ stable_session_id:
+ anyOf:
+ - type: string
+ - type: 'null'
+ default: null
ui_values:
anyOf:
- type: object
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index b341d11d08..378529d3dc 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -5677,6 +5677,8 @@ export interface components {
* kiosk: Whether running in kiosk mode.
* capabilities: Available kernel capabilities.
* auto_instantiated: Whether cells already executed (run mode).
+ * stable_session_id: Server-owned Session identity that survives
+ * browser reconnects. None where no server Session exists.
*/
KernelReadyNotification: {
app_config: components["schemas"]["_AppConfig"];
@@ -5699,6 +5701,8 @@ export interface components {
/** @enum {unknown} */
op: "kernel-ready";
resumed: boolean;
+ /** @default null */
+ stable_session_id?: string | null;
ui_values: Record<string, any> | null;
};
/**
diff --git a/tests/_cli/_pair_server.py b/tests/_cli/_pair_server.py
index b70867910c..ae1b46b3bc 100644
--- a/tests/_cli/_pair_server.py
+++ b/tests/_cli/_pair_server.py
@@ -25,6 +25,7 @@ if TYPE_CHECKING:
class PairTestServer:
url: str
session_id: str
+ stable_session_id: str
_process: subprocess.Popen[bytes]
_websocket: ClientConnection
_stderr_path: Path
@@ -193,9 +194,15 @@ def pair_test_server(tmp_path: Path) -> Generator[PairTestServer, None, None]:
open_timeout=5,
)
_wait_for_kernel_ready(websocket)
+ with urllib.request.urlopen(
+ f"{url}/api/sessions", 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,
_process=process,
_websocket=websocket,
_stderr_path=stderr_path,
diff --git a/tests/_cli/test_cli_pair.py b/tests/_cli/test_cli_pair.py
index 050a390555..243aadc7c0 100644
--- a/tests/_cli/test_cli_pair.py
+++ b/tests/_cli/test_cli_pair.py
@@ -22,6 +22,7 @@ from marimo._cli.pair.client import (
NoSessionError,
PairError,
PairInputError,
+ StableSessionUnsupportedError,
StaleSessionError,
)
from marimo._cli.pair.commands import (
@@ -64,16 +65,16 @@ Usage: main pair [OPTIONS] COMMAND [ARGS]...
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 notebook file:
+ If you do not have the server URL or session:
marimo pair notebook list
- marimo pair execute --url <URL> --file <FILE> --code-file - <<'PY'
+ marimo pair execute --url <URL> --session <SESSION> --code-file - <<'PY'
import marimo._code_mode as cm
async 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> --file <FILE> --code-file - <<'PY'
+ marimo pair execute --url <URL> --session <SESSION> --code-file - <<'PY'
import marimo._code_mode as cm
async with cm.get_context() as ctx:
cell = ctx.cells["<CELL_ID>"]
@@ -81,14 +82,11 @@ Usage: main pair [OPTIONS] COMMAND [ARGS]...
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.
+ --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,
or when execution is unconfirmed.
@@ -111,7 +109,7 @@ Usage: main pair [OPTIONS] COMMAND [ARGS]...
ctx.delete_cell(cid)
ctx.packages.add("pandas>=2") # queued, installs on exit
If a cm call fails, run help(cm):
- marimo pair execute --url <URL> --file <FILE> -c 'import marimo._code_mode as cm; help(cm)'
+ marimo pair execute --url <URL> --session <SESSION> -c 'import marimo._code_mode as cm; help(cm)'
Options:
-h, --help Show this message and exit.
@@ -130,7 +128,7 @@ Commands:
assert "--claude" in result.output
assert "--codex" in result.output
assert "--opencode" in result.output
- assert "--file" in result.output
+ assert "--file" not in result.output
assert "--session" in result.output
@@ -157,9 +155,7 @@ Usage: main pair execute [OPTIONS]
Options:
--url URL Server URL. [required]
- --session ID Current session ID. Resolved from --file when omitted.
- --file PATH Notebook path or file key. Used to resolve --session when
- omitted.
+ --session ID Stable session_id from marimo pair notebook list.
--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
@@ -536,9 +532,9 @@ Options:
assert result.exit_code == 2
assert result.stdout == ""
assert result.stderr == (
- "error: The session is stale.\n"
- " next: Sessions change when the page reloads. List them again:\n"
- " marimo pair notebook list --url http://one\n"
+ "error: No session s_old on http://one. "
+ "The notebook was closed or restarted.\n"
+ " next: marimo pair notebook list --url http://one\n"
)
def test_execute_auth_failure_has_token_next(
@@ -621,12 +617,12 @@ Options:
"session": {"id": "s_ab12cd"},
}
- def test_execute_reports_internal_resolution_error(
+ def test_execute_reports_server_without_stable_sessions(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
def fail_execute(**kwargs: Any) -> ExecutionResult:
del kwargs
- raise PairError("Internal: should not happen after resolution.")
+ raise StableSessionUnsupportedError
monkeypatch.setattr(commands, "execute_code", fail_execute)
result = _runner.invoke(
@@ -645,10 +641,17 @@ Options:
assert result.exit_code == 2
payload = json.loads(result.output)
- assert payload["success"] is False
- assert (
- payload["error"] == "Internal: should not happen after resolution."
- )
+ assert payload == {
+ "success": False,
+ "error": (
+ "Server https://localhost:8000 runs a marimo version "
+ "without session_id. Upgrade marimo on the server."
+ ),
+ "output": None,
+ "stdout": None,
+ "stderr": None,
+ "session": {"id": "s_ab12cd"},
+ }
assert "next" not in payload
def test_execute_reports_interrupt(
@@ -720,7 +723,7 @@ Options:
assert execute_calls[0]["stream"] is True
assert result.output == ""
- def test_execute_resolves_one_session_from_file(
+ def test_execute_resolves_one_session_when_omitted(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
resolve_calls: list[dict[str, Any]] = []
@@ -745,26 +748,48 @@ Options:
"execute",
"--url",
"http://one",
- "--file",
- "analysis.py",
"-c",
"print(1)",
],
)
assert result.exit_code == 0
- assert resolve_calls == [
- {"url": "http://one", "token": None, "file": "analysis.py"}
- ]
+ assert resolve_calls == [{"url": "http://one", "token": None}]
assert execute_calls[0]["session_id"] == "s_one"
+ def test_execute_rejects_file_selector(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.setattr(
+ commands,
+ "execute_code",
+ lambda **_kwargs: pytest.fail("execute must not run"),
+ )
+
+ result = _runner.invoke(
+ cli_main,
+ [
+ "pair",
+ "execute",
+ "--url",
+ "http://one",
+ "--file",
+ "analysis.py",
+ "-c",
+ "print(1)",
+ ],
+ )
+
+ assert result.exit_code == 2
+ assert "unexpected argument '--file'" in result.output
+
def test_execute_no_match_exits_two_with_list_next(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
def fake_resolve(**kwargs: Any) -> str:
del kwargs
raise NoSessionError(
- "No running session for notebook 'gone.py' on http://one.",
+ "No running session on http://one.",
url="http://user:password@one?access_token=secret",
)
@@ -781,8 +806,6 @@ Options:
"execute",
"--url",
"http://one",
- "--file",
- "gone.py",
"-c",
"print(1)",
],
@@ -791,7 +814,7 @@ Options:
assert result.exit_code == 2
payload = json.loads(result.output)
assert payload["success"] is False
- assert "No running session for notebook 'gone.py'" in payload["error"]
+ assert payload["error"] == "No running session on http://one."
assert payload["next"].endswith(
"marimo pair notebook list --url http://one"
)
@@ -805,9 +828,9 @@ Options:
def fake_resolve(**kwargs: Any) -> str:
del kwargs
raise AmbiguousSessionError(
- "Notebook 'analysis.py' has 2 running sessions on http://one.",
+ "Server http://one has 2 running sessions.",
url="http://user:password@one?access_token=secret",
- candidates=("s_a", "s_b"),
+ candidates=("sess-a", "sess-b"),
)
monkeypatch.setattr(commands, "resolve_session", fake_resolve)
@@ -823,8 +846,6 @@ Options:
"execute",
"--url",
"http://one",
- "--file",
- "analysis.py",
"-c",
"print(1)",
],
@@ -834,11 +855,11 @@ Options:
payload = json.loads(result.output)
assert "has 2 running sessions" in payload["error"]
assert (
- "s_a: marimo pair execute --url http://one --session s_a"
+ "sess-a: marimo pair execute --url http://one --session sess-a"
in (payload["next"])
)
assert (
- "s_b: marimo pair execute --url http://one --session s_b"
+ "sess-b: marimo pair execute --url http://one --session sess-b"
in (payload["next"])
)
assert "password" not in result.output
@@ -883,7 +904,7 @@ Options:
) -> None:
def fail_execute(**kwargs: Any) -> ExecutionResult:
del kwargs
- raise StaleSessionError("Invalid session id: s_old")
+ raise StaleSessionError("Invalid stable session id: sess-old")
monkeypatch.setattr(commands, "execute_code", fail_execute)
result = _runner.invoke(
@@ -894,7 +915,7 @@ Options:
"--url",
"http://user:password@one?access_token=secret",
"--session",
- "s_old",
+ "sess-old",
"-c",
"print(1)",
],
@@ -902,7 +923,10 @@ Options:
assert result.exit_code == 2
payload = json.loads(result.output)
- assert payload["error"] == "The session is stale."
+ assert payload["error"] == (
+ "No session sess-old on http://one. "
+ "The notebook was closed or restarted."
+ )
assert payload["next"].endswith(
"marimo pair notebook list --url http://one"
)
@@ -1018,10 +1042,12 @@ Options:
"list_sessions",
lambda **_kwargs: {
"session-2": {
+ "session_id": "sess-stable-2",
"filename": "analysis.py",
"path": "/work/analysis.py",
},
"session-1": {
+ "session_id": "sess-stable-1",
"filename": "analysis.py",
"path": "/work/analysis.py",
},
@@ -1041,8 +1067,14 @@ Options:
"name": "analysis.py",
"path": "/work/analysis.py",
"sessions": [
- {"id": "session-1"},
- {"id": "session-2"},
+ {
+ "id": "session-1",
+ "session_id": "sess-stable-1",
+ },
+ {
+ "id": "session-2",
+ "session_id": "sess-stable-2",
+ },
],
}
],
@@ -1110,6 +1142,7 @@ Options:
assert token is None
return {
f"session-{url[-1]}": {
+ "session_id": f"sess-{url[-1]}",
"filename": "analysis.py",
"path": f"/work/{url[-1]}/analysis.py",
}
@@ -1145,10 +1178,12 @@ Options:
"list_sessions",
lambda **_kwargs: {
"session-b": {
+ "session_id": "sess-b",
"filename": "analysis.py",
"path": "/work/b/analysis.py",
},
"session-a": {
+ "session_id": "sess-a",
"filename": "analysis.py",
"path": "/work/a/analysis.py",
},
@@ -1180,6 +1215,7 @@ Options:
raise PairError("Could not connect to http://bad.")
return {
"session-1": {
+ "session_id": "sess-stable-1",
"filename": "analysis.py",
"path": "/work/analysis.py",
}
@@ -1206,7 +1242,12 @@ Options:
"server": {"url": "http://good"},
"name": "analysis.py",
"path": "/work/analysis.py",
- "sessions": [{"id": "session-1"}],
+ "sessions": [
+ {
+ "id": "session-1",
+ "session_id": "sess-stable-1",
+ }
+ ],
}
],
"warnings": [
@@ -1227,6 +1268,7 @@ Options:
calls.append(url)
return {
"session-1": {
+ "session_id": "sess-stable-1",
"filename": "analysis.py",
"path": "/work/analysis.py",
}
@@ -1269,6 +1311,29 @@ Options:
assert payload["next"].startswith("No sessions found.")
assert "marimo edit <notebook.py> --no-token" in payload["next"]
+ def test_list_warns_when_server_has_no_stable_sessions(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ def fail_list_sessions(**_kwargs: Any) -> None:
+ raise StableSessionUnsupportedError
+
+ monkeypatch.setattr(commands, "list_sessions", fail_list_sessions)
+
+ result = _runner.invoke(
+ cli_main,
+ ["pair", "notebook", "list", "--url", "http://one"],
+ )
+
+ assert result.exit_code == 0
+ payload = json.loads(result.output)
+ assert payload["notebooks"] == []
+ assert payload["warnings"] == [
+ (
+ "Server http://one runs a marimo version without session_id. "
+ "Upgrade marimo on the server."
+ )
+ ]
+
def test_list_empty_registry_succeeds(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
@@ -1367,7 +1432,7 @@ Use `execute-code.sh --url 'https://localhost:8000?auth=tok123'` from the marimo
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:
+ def test_prompt_rejects_file_selector(self) -> None:
result = _runner.invoke(
cli_main,
[
@@ -1379,12 +1444,10 @@ Once you are connected, send a fun toast (mo.status.toast(...)) to the user insi
"notebooks/example.py",
],
)
- assert result.exit_code == 0
- assert TEST_URL in result.output
- assert "notebooks/example.py" in result.output
- assert "--file notebooks/example.py" in result.output
+ assert result.exit_code == 2
+ assert "unexpected argument '--file'" in result.output
- def test_prompt_without_file_omits_flag(self) -> None:
+ def test_prompt_without_session_omits_selector(self) -> None:
result = _runner.invoke(
cli_main, ["pair", "prompt", "--url", TEST_URL]
)
@@ -1408,65 +1471,13 @@ Use `execute-code.sh --url 'https://localhost:8000?auth=tok123' --session s_ab12
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 argv
-
- def test_prompt_shell_quotes_file_paths(self) -> None:
+ def test_prompt_shell_quotes_session_ids(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'""",
- ),
+ ("sess-stable", "--session sess-stable"),
+ ("sess stable", "--session 'sess stable'"),
+ ("sess'quote", """--session 'sess'"'"'quote'"""),
]
- for file_path, expected in cases:
+ for session_id, expected in cases:
result = _runner.invoke(
cli_main,
[
@@ -1474,8 +1485,8 @@ Once you are connected, send a fun toast (mo.status.toast(...)) to the user insi
"prompt",
"--url",
TEST_URL,
- "--file",
- file_path,
+ "--session",
+ session_id,
],
)
assert result.exit_code == 0
@@ -1654,10 +1665,8 @@ Once connected, send a fun toast using `mo.status.toast(...)` (`import marimo as
"prompt",
"--url",
"http://localhost:2718/{session}",
- "--file",
- "{command}/it's notebook.py",
"--session",
- "{file}",
+ "{command}/it's session",
],
env={"MARIMO_PAIR_NEXT": "1"},
)
@@ -1667,8 +1676,7 @@ Once connected, send a fun toast using `mo.status.toast(...)` (`import marimo as
Pair with me on this running marimo notebook.
URL: http://localhost:2718/{session}
-File: {command}/it's notebook.py
-Session: {file}
+Session: {command}/it's session
Run `uvx marimo@latest pair --help` first.
Use `uvx marimo@latest` for all marimo commands.
@@ -1685,8 +1693,8 @@ Once connected, send a fun toast using `mo.status.toast(...)` (`import marimo as
"prompt",
"--url",
"http://localhost:2718",
- "--file",
- "notebook.py",
+ "--session",
+ "sess-stable",
],
env={"MARIMO_PAIR_NEXT": flag},
)
@@ -1696,7 +1704,7 @@ Once connected, send a fun toast using `mo.status.toast(...)` (`import marimo as
Pair with me on this running marimo notebook.
URL: http://localhost:2718
-File: notebook.py
+Session: sess-stable
Run `uvx marimo@latest pair --help` first.
Use `uvx marimo@latest` for all marimo commands.
@@ -1757,7 +1765,7 @@ class TestPairPromptWithToken:
if sys.platform != "win32":
assert oct(token_file.stat().st_mode & 0o777) == "0o600"
- def test_with_token_and_file(self, tmp_path: Path) -> None:
+ def test_with_token_and_session(self, tmp_path: Path) -> None:
with patch(
"marimo._cli.pair.commands._token_dir", return_value=tmp_path
):
@@ -1768,16 +1776,16 @@ class TestPairPromptWithToken:
"prompt",
"--url",
TEST_URL,
- "--file",
- "notebooks/my notebook.py",
+ "--session",
+ "sess stable",
"--with-token",
],
input="my-secret-token\n",
)
assert result.exit_code == 0
- 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.output
+ 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(
diff --git a/tests/_cli/test_pair_client.py b/tests/_cli/test_pair_client.py
index 00d6ce5752..bf18e3f4a5 100644
--- a/tests/_cli/test_pair_client.py
+++ b/tests/_cli/test_pair_client.py
@@ -17,6 +17,7 @@ from marimo._cli.pair.client import (
PairError,
PairInputError,
SSEEvent,
+ StableSessionUnsupportedError,
StaleSessionError,
)
@@ -210,7 +211,7 @@ def test_execute_sends_request_and_streams_in_event_order(
"url": "https://example.com/base/api/kernel/execute?access_token=query-token",
"headers": {
"Content-Type": "application/json",
- "Marimo-Session-Id": "session-1",
+ "Marimo-Stable-Session-Id": "session-1",
"Authorization": "Bearer secret-token",
},
"body": json.dumps({"code": "print(1)"}).encode(),
@@ -453,11 +454,16 @@ def test_list_sessions_sends_request_and_parses_response(
json.dumps(
{
"session-1": {
+ "session_id": "sess-stable-1",
"filename": "analysis.py",
"path": "/work/analysis.py",
"state": "idle",
},
- "session-2": {"filename": None, "path": None},
+ "session-2": {
+ "session_id": "sess-stable-2",
+ "filename": None,
+ "path": None,
+ },
}
).encode()
)
@@ -473,10 +479,15 @@ def test_list_sessions_sends_request_and_parses_response(
assert sessions == {
"session-1": {
+ "session_id": "sess-stable-1",
"filename": "analysis.py",
"path": "/work/analysis.py",
},
- "session-2": {"filename": None, "path": None},
+ "session-2": {
+ "session_id": "sess-stable-2",
+ "filename": None,
+ "path": None,
+ },
}
assert calls == [
{
@@ -510,10 +521,39 @@ def test_list_sessions_omits_authorization_without_token(
[],
{"session-1": None},
{"session-1": {}},
- {"session-1": {"filename": "analysis.py"}},
- {"session-1": {"path": "/work/analysis.py"}},
- {"session-1": {"filename": [], "path": None}},
- {"session-1": {"filename": None, "path": []}},
+ {
+ "session-1": {
+ "session_id": "sess-stable",
+ "filename": "analysis.py",
+ }
+ },
+ {
+ "session-1": {
+ "session_id": "sess-stable",
+ "path": "/work/analysis.py",
+ }
+ },
+ {
+ "session-1": {
+ "session_id": "sess-stable",
+ "filename": [],
+ "path": None,
+ }
+ },
+ {
+ "session-1": {
+ "session_id": "sess-stable",
+ "filename": None,
+ "path": [],
+ }
+ },
+ {
+ "session-1": {
+ "session_id": None,
+ "filename": None,
+ "path": None,
+ }
+ },
],
)
def test_list_sessions_rejects_malformed_response(
@@ -556,6 +596,27 @@ def test_list_sessions_rejects_invalid_json(
assert response.closed
+def test_list_sessions_rejects_server_without_stable_ids(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ response = io.BytesIO(
+ json.dumps(
+ {
+ "session-1": {
+ "filename": "analysis.py",
+ "path": "/work/analysis.py",
+ }
+ }
+ ).encode()
+ )
+ _patch_response(monkeypatch, response)
+
+ with pytest.raises(StableSessionUnsupportedError):
+ client.list_sessions(url="http://localhost:2718", token=None)
+
+ assert response.closed
+
+
def test_registry_urls_skips_invalid_entries(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
@@ -652,73 +713,68 @@ def test_raise_for_status_maps_invalid_session_id() -> None:
assert response.closed
-def test_raise_for_status_uses_json_detail() -> None:
+def test_raise_for_status_maps_invalid_stable_session_id() -> None:
+ response = FakeStatusResponse(
+ 404,
+ json.dumps({"detail": "Invalid stable session id: sess-old"}).encode(),
+ )
+
+ with pytest.raises(StaleSessionError, match="Invalid stable session id"):
+ client._raise_for_status(response)
+
+ assert response.closed
+
+
+def test_raise_for_status_maps_missing_legacy_header_to_upgrade() -> None:
response = FakeStatusResponse(
500,
json.dumps({"detail": "Missing Marimo-Session-Id header"}).encode(),
)
- with pytest.raises(
- PairError, match="Internal: should not happen after resolution"
- ):
+ with pytest.raises(StableSessionUnsupportedError):
client._raise_for_status(response)
+ assert response.closed
-def test_resolve_session_matches_path(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- monkeypatch.setattr(
- client,
- "list_sessions",
- lambda **_kwargs: {
- "s_one": {"filename": "analysis.py", "path": "/work/analysis.py"}
- },
- )
- assert (
- client.resolve_session(
- url="http://one", token=None, file="/work/analysis.py"
- )
- == "s_one"
+def test_raise_for_status_uses_json_detail() -> None:
+ response = FakeStatusResponse(
+ 500, json.dumps({"detail": "Some other server error"}).encode()
)
+ with pytest.raises(PairError, match="Some other server error") as error:
+ client._raise_for_status(response)
-def test_resolve_session_matches_filename(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- monkeypatch.setattr(
- client,
- "list_sessions",
- lambda **_kwargs: {
- "s_one": {"filename": "nb.py", "path": "/work/nb.py"}
- },
- )
+ assert type(error.value) is PairError
+ assert response.closed
- assert (
- client.resolve_session(url="http://one", token=None, file="nb.py")
- == "s_one"
- )
+def test_raise_for_status_falls_back_to_status_code() -> None:
+ response = FakeStatusResponse(502, b"<html>Bad Gateway</html>")
-def test_resolve_session_matches_abspath(
- monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+ with pytest.raises(PairError, match=r"Server returned 502\."):
+ client._raise_for_status(response)
+
+ assert response.closed
+
+
+def test_resolve_session_returns_only_stable_session_id(
+ monkeypatch: pytest.MonkeyPatch,
) -> None:
- notebook = tmp_path / "nb.py"
- monkeypatch.chdir(tmp_path)
monkeypatch.setattr(
client,
"list_sessions",
lambda **_kwargs: {
- "s_one": {
- "filename": "other.py",
- "path": str(notebook.resolve()),
+ "routing-id": {
+ "session_id": "sess-stable",
+ "filename": "analysis.py",
+ "path": "/work/analysis.py",
}
},
)
- assert (
- client.resolve_session(url="http://one", token=None, file="nb.py")
- == "s_one"
+ assert client.resolve_session(url="http://one", token=None) == (
+ "sess-stable"
)
@@ -727,11 +783,10 @@ def test_resolve_session_zero_matches(
) -> None:
monkeypatch.setattr(client, "list_sessions", lambda **_kwargs: {})
- with pytest.raises(NoSessionError, match=r"gone\.py") as exc_info:
+ with pytest.raises(NoSessionError, match="No running session") as exc_info:
client.resolve_session(
url="http://user:password@one?access_token=secret",
token=None,
- file="gone.py",
)
assert exc_info.value.url == "http://one"
@@ -739,24 +794,6 @@ def test_resolve_session_zero_matches(
assert "secret" not in str(exc_info.value)
-def test_resolve_session_stops_at_first_matching_tier(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- monkeypatch.setattr(
- client,
- "list_sessions",
- lambda **_kwargs: {
- "s_exact": {"filename": "other.py", "path": "nb.py"},
- "s_filename": {"filename": "nb.py", "path": "/work/nb.py"},
- },
- )
-
- assert (
- client.resolve_session(url="http://one", token=None, file="nb.py")
- == "s_exact"
- )
-
-
def test_resolve_session_many_matches(
monkeypatch: pytest.MonkeyPatch,
) -> None:
@@ -764,12 +801,20 @@ def test_resolve_session_many_matches(
client,
"list_sessions",
lambda **_kwargs: {
- "s_b": {"filename": "nb.py", "path": "/b/nb.py"},
- "s_a": {"filename": "nb.py", "path": "/a/nb.py"},
+ "routing-b": {
+ "session_id": "sess-b",
+ "filename": "nb.py",
+ "path": "/b/nb.py",
+ },
+ "routing-a": {
+ "session_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, file="nb.py")
+ client.resolve_session(url="http://one", token=None)
- assert exc_info.value.candidates == ("s_a", "s_b")
+ assert exc_info.value.candidates == ("sess-a", "sess-b")
diff --git a/tests/_cli/test_pair_integration.py b/tests/_cli/test_pair_integration.py
index 7b656f7bbe..7eaf217023 100644
--- a/tests/_cli/test_pair_integration.py
+++ b/tests/_cli/test_pair_integration.py
@@ -35,7 +35,7 @@ def _command(server: PairTestServer, *arguments: str) -> list[str]:
"--url",
server.url,
"--session",
- server.session_id,
+ server.stable_session_id,
*arguments,
]
@@ -88,6 +88,17 @@ 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
+
+ result = _run(server, "-c", "print('stable')")
+
+ assert result.returncode == 0, result.stderr
+ payload = json.loads(result.stdout)
+ assert payload["stdout"] == "stable\n"
+ assert payload["session"]["id"] == server.stable_session_id
+
+
@pytest.mark.skipif(os.name != "posix", reason="SIGINT requires POSIX")
def test_interrupt_disconnects_and_kernel_recovers(
server: PairTestServer,
@@ -117,7 +128,7 @@ def test_interrupt_disconnects_and_kernel_recovers(
assert payload["success"] is True
assert payload["stdout"] == "alive\n"
assert payload["output"] is None
- assert payload["session"]["id"] == server.session_id
+ assert payload["session"]["id"] == server.stable_session_id
def test_missing_input_does_not_read_stdin_or_execute(
diff --git a/tests/_server/api/endpoints/test_execution.py b/tests/_server/api/endpoints/test_execution.py
index d64f0def4f..faa1fe34a8 100644
--- a/tests/_server/api/endpoints/test_execution.py
+++ b/tests/_server/api/endpoints/test_execution.py
@@ -35,6 +35,8 @@ from tests._server.mocks import (
)
if TYPE_CHECKING:
+ from collections.abc import AsyncGenerator
+
from starlette.testclient import TestClient
SESSION_ID = SessionId("session-123")
@@ -42,6 +44,7 @@ HEADERS = {
"Marimo-Session-Id": SESSION_ID,
**token_header("fake-token"),
}
+STABLE_SESSION_HEADER = "Marimo-Stable-Session-Id"
def _count_execute_interrupts(
@@ -260,6 +263,98 @@ class TestExecutionRoutes_EditMode:
assert response.headers["content-type"] == "application/json"
assert "success" in response.json()
+ @staticmethod
+ @with_session(SESSION_ID)
+ def test_execute_with_stable_session_id(client: TestClient) -> None:
+ from unittest.mock import patch
+
+ from marimo._runtime.commands import ExecuteScratchpadCommand
+ from marimo._server import scratchpad as scratchpad_mod
+
+ session = get_session_manager(client).get_session(SESSION_ID)
+ assert session is not None
+
+ captured: list[object] = []
+
+ def capture(req: object, from_consumer_id: object) -> None: # noqa: ARG001
+ captured.append(req)
+
+ async def empty_stream(
+ self: object, # noqa: ARG001
+ ) -> AsyncGenerator[str, None]:
+ if False:
+ yield ""
+
+ with (
+ patch.object(session, "put_control_request", side_effect=capture),
+ patch.object(
+ scratchpad_mod.ScratchCellListener,
+ "stream",
+ empty_stream,
+ ),
+ ):
+ response = client.post(
+ "/api/kernel/execute",
+ headers={
+ STABLE_SESSION_HEADER: session.stable_id,
+ **token_header("fake-token"),
+ },
+ json={"code": "x = 1"},
+ )
+
+ assert response.status_code == 200, response.text
+ scratchpad_commands = [
+ command
+ for command in captured
+ if isinstance(command, ExecuteScratchpadCommand)
+ ]
+ assert len(scratchpad_commands) == 1
+ assert scratchpad_commands[0].code == "x = 1"
+
+ @staticmethod
+ @with_session(SESSION_ID)
+ def test_execute_rejects_conflicting_session_ids(
+ client: TestClient,
+ ) -> None:
+ session = get_session_manager(client).get_session(SESSION_ID)
+ assert session is not None
+
+ response = client.post(
+ "/api/kernel/execute",
+ headers={
+ **HEADERS,
+ STABLE_SESSION_HEADER: session.stable_id,
+ },
+ json={"code": "x = 1"},
+ )
+
+ assert response.status_code == 400, response.text
+ assert response.json() == {
+ "detail": (
+ "Marimo-Stable-Session-Id cannot be combined with "
+ "Marimo-Session-Id."
+ )
+ }
+
+ @staticmethod
+ @with_session(SESSION_ID)
+ def test_execute_rejects_unknown_stable_session_id(
+ client: TestClient,
+ ) -> None:
+ response = client.post(
+ "/api/kernel/execute",
+ headers={
+ STABLE_SESSION_HEADER: "sess-unknown",
+ **token_header("fake-token"),
+ },
+ json={"code": "x = 1"},
+ )
+
+ assert response.status_code == 404, response.text
+ assert response.json() == {
+ "detail": "Invalid stable session id: sess-unknown"
+ }
+
@staticmethod
@with_session(SESSION_ID)
def test_execute_injects_screenshot_meta(client: TestClient) -> None:
diff --git a/tests/_server/api/endpoints/test_health.py b/tests/_server/api/endpoints/test_health.py
index 58114b9b2a..b92be7f9a6 100644
--- a/tests/_server/api/endpoints/test_health.py
+++ b/tests/_server/api/endpoints/test_health.py
@@ -4,8 +4,15 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import patch
+import pytest
+
from marimo import __version__
-from tests._server.mocks import token_header, with_session
+from marimo._types.ids import SessionId
+from tests._server.mocks import (
+ get_session_manager,
+ token_header,
+ with_session,
+)
if TYPE_CHECKING:
from starlette.testclient import TestClient
@@ -53,6 +60,75 @@ def test_version(client: TestClient) -> None:
assert response.text == __version__
+def test_sessions_requires_auth(client: TestClient) -> None:
+ response = client.get("/api/sessions")
+ assert response.status_code == 401, response.text
+
+
+def test_sessions_empty(client: TestClient) -> None:
+ response = client.get("/api/sessions", headers=token_header())
+ assert response.status_code == 200, response.text
+ assert response.json() == {}
+
+
[email protected]("connection_id", [SESSION_ID, "session-456"])
+def test_sessions_stable_id_survives_reconnect(
+ client: TestClient, connection_id: str
+) -> None:
+ with client.websocket_connect(
+ f"/ws?session_id={SESSION_ID}", headers=token_header()
+ ) as websocket:
+ assert websocket.receive_json()["op"] == "kernel-ready"
+ session = get_session_manager(client).get_session(
+ SessionId(SESSION_ID)
+ )
+ assert session is not None
+ expected = {
+ "session_id": session.stable_id,
+ "filename": session.app_file_manager.filename,
+ "path": session.app_file_manager.path,
+ }
+ response = client.get("/api/sessions", headers=token_header())
+ assert response.status_code == 200, response.text
+ assert response.json() == {SESSION_ID: expected}
+
+ with client.websocket_connect(
+ f"/ws?session_id={connection_id}", headers=token_header()
+ ) as websocket:
+ assert websocket.receive_json()["op"] == "reconnected"
+ response = client.get("/api/sessions", headers=token_header())
+ assert response.status_code == 200, response.text
+ assert response.json() == {connection_id: expected}
+
+
+def test_sessions_stable_id_changes_after_restart(client: TestClient) -> None:
+ with client.websocket_connect(
+ f"/ws?session_id={SESSION_ID}", headers=token_header()
+ ) as websocket:
+ assert websocket.receive_json()["op"] == "kernel-ready"
+ response = client.get("/api/sessions", headers=token_header())
+ assert response.status_code == 200, response.text
+ previous = response.json()[SESSION_ID]
+
+ response = client.post("/api/kernel/restart_session", headers=HEADERS)
+ assert response.status_code == 200, response.text
+ response = client.get("/api/sessions", headers=token_header())
+ assert response.status_code == 200, response.text
+ assert response.json() == {}
+
+ with client.websocket_connect(
+ f"/ws?session_id={SESSION_ID}", headers=token_header()
+ ) as websocket:
+ assert websocket.receive_json()["op"] == "kernel-ready"
+ response = client.get("/api/sessions", headers=token_header())
+ assert response.status_code == 200, response.text
+ current = response.json()[SESSION_ID]
+ assert current["session_id"] != previous["session_id"]
+ assert response.json() == {
+ SESSION_ID: {**previous, "session_id": current["session_id"]}
+ }
+
+
def test_memory(client: TestClient) -> None:
# Unauthorized
response = client.get("/api/status")
diff --git a/tests/_server/templates/test_templates_api.py b/tests/_server/templates/test_templates_api.py
index 821fca8590..2c2d5c92b7 100644
--- a/tests/_server/templates/test_templates_api.py
+++ b/tests/_server/templates/test_templates_api.py
@@ -39,8 +39,7 @@ def test_render_notebook_pair_preview(
"command": command,
"templates": snapshot(
{
- "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",
+ "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.",