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: sandboxed home (#7702)
Dylan Madisetti993beb7ee426
diff --git a/.github/workflows/test_cli.yaml b/.github/workflows/test_cli.yamlindex 094dd8353b..6d5814b0e2 100644--- a/.github/workflows/test_cli.yaml+++ b/.github/workflows/test_cli.yaml@@ -146,7 +146,7 @@ jobs:- name: Install Python depsrun: |- uv add pytest pytest-asyncio pytest-timeout nbformat+ uv add pytest pytest-asyncio pytest-timeout nbformat pyzmq- name: Download wheeluses: actions/download-artifact@v4diff --git a/examples/misc/notebook_dir.py b/examples/misc/notebook_dir.pyindex b9a54bd4ca..90016c5a50 100644--- a/examples/misc/notebook_dir.py+++ b/examples/misc/notebook_dir.py@@ -1,3 +1,9 @@+# /// script+# requires-python = ">=3.13"+# dependencies = [+# "marimo",+# ]+# ///import marimo__generated_with = "0.15.5"diff --git a/frontend/src/components/editor/KernelStartupErrorModal.tsx b/frontend/src/components/editor/KernelStartupErrorModal.tsxnew file mode 100644index 0000000000..2f80bfae28--- /dev/null+++ b/frontend/src/components/editor/KernelStartupErrorModal.tsx@@ -0,0 +1,101 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { useAtom } from "jotai";+import { CopyIcon, HomeIcon, XCircleIcon } from "lucide-react";+import { kernelStartupErrorAtom } from "@/core/errors/state";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "../ui/alert-dialog";+import { Button } from "../ui/button";+import { toast } from "../ui/use-toast";++/**+ * Modal that displays kernel startup errors.+ * Shows when the kernel fails to start in sandbox mode,+ * displaying the stderr output so users can diagnose the issue.+ */+export const KernelStartupErrorModal: React.FC = () => {+ const [error, setError] = useAtom(kernelStartupErrorAtom);++ if (error === null) {+ return null;+ }++ const handleCopy = async () => {+ try {+ await navigator.clipboard.writeText(error);+ toast({+ title: "Copied to clipboard",+ description: "Error details have been copied to your clipboard.",+ });+ } catch {+ toast({+ title: "Failed to copy",+ description: "Could not copy to clipboard.",+ variant: "danger",+ });+ }+ };++ const handleClose = () => {+ setError(null);+ };++ const handleReturnHome = () => {+ const withoutSearch = document.baseURI.split("?")[0];+ window.open(withoutSearch, "_self");+ };++ return (+ <AlertDialog open={true} onOpenChange={(open) => !open && handleClose()}>+ <AlertDialogContent className="max-w-2xl">+ <AlertDialogHeader>+ <AlertDialogTitle className="flex items-center gap-2 text-destructive">+ <XCircleIcon className="h-5 w-5" />+ Kernel Startup Failed+ </AlertDialogTitle>+ <AlertDialogDescription>+ The kernel failed to start. This usually happens when the package+ manager can't install your notebook's dependencies.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <div className="my-4">+ <div className="flex items-center justify-between mb-2">+ <span className="text-sm font-medium text-muted-foreground">+ Error Details+ </span>+ <Button+ variant="outline"+ size="xs"+ onClick={handleCopy}+ className="flex items-center gap-1"+ >+ <CopyIcon className="h-3 w-3" />+ Copy+ </Button>+ </div>+ <pre className="bg-muted p-4 rounded-md text-sm font-mono overflow-auto max-h-80 whitespace-pre-wrap break-words">+ {error}+ </pre>+ </div>+ <AlertDialogFooter>+ <Button+ variant="outline"+ onClick={handleReturnHome}+ className="flex items-center gap-2"+ >+ <HomeIcon className="h-4 w-4" />+ Return to Home+ </Button>+ <AlertDialogAction onClick={handleClose}>Dismiss</AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );+};diff --git a/frontend/src/core/MarimoApp.tsx b/frontend/src/core/MarimoApp.tsxindex 63747e9288..a89c4e449f 100644--- a/frontend/src/core/MarimoApp.tsx+++ b/frontend/src/core/MarimoApp.tsx@@ -12,6 +12,7 @@ import { getInitialAppMode } from "@/core/mode";import { CssVariables } from "@/theme/ThemeProvider";import { reactLazyWithPreload } from "@/utils/lazy";import { ErrorBoundary } from "../components/editor/boundary/ErrorBoundary";+import { KernelStartupErrorModal } from "../components/editor/KernelStartupErrorModal";import { ModalProvider } from "../components/modal/ImperativeModal";import { Toaster } from "../components/ui/toaster";import { TooltipProvider } from "../components/ui/tooltip";@@ -91,6 +92,7 @@ const Providers = memo(({ children }: PropsWithChildren) => {{children}<Toaster /><TailwindIndicator />+ <KernelStartupErrorModal /></ModalProvider></LocaleProvider></SlotzProvider>diff --git a/frontend/src/core/errors/state.ts b/frontend/src/core/errors/state.tsindex 7f835d5ae1..13c001d715 100644--- a/frontend/src/core/errors/state.ts+++ b/frontend/src/core/errors/state.ts@@ -1,11 +1,17 @@/* Copyright 2026 Marimo. All rights reserved. */-import { useAtomValue } from "jotai";+import { atom, useAtomValue } from "jotai";import { createReducerAndAtoms } from "@/utils/createReducer";import type { Identified } from "@/utils/typed";import { generateUUID } from "@/utils/uuid";import type { Banner } from "../kernel/messages";+/**+ * Atom for storing kernel startup error message.+ * When set to a non-null value, shows a modal with the error details.+ */+export const kernelStartupErrorAtom = atom<string | null>(null);+interface BannerState {banners: Identified<Banner>[];}diff --git a/frontend/src/core/islands/main.ts b/frontend/src/core/islands/main.tsindex 36bf8099a1..866c52bad8 100644--- a/frontend/src/core/islands/main.ts+++ b/frontend/src/core/islands/main.ts@@ -192,6 +192,8 @@ export async function initialize() {return;case "cache-info":return;+ case "kernel-startup-error":+ return;default:logNever(msg.data);}diff --git a/frontend/src/core/websocket/types.ts b/frontend/src/core/websocket/types.tsindex 8ed793e833..6ad83b7758 100644--- a/frontend/src/core/websocket/types.ts+++ b/frontend/src/core/websocket/types.ts@@ -16,6 +16,7 @@ export const WebSocketClosedReason = {KERNEL_DISCONNECTED: "KERNEL_DISCONNECTED",ALREADY_RUNNING: "ALREADY_RUNNING",MALFORMED_QUERY: "MALFORMED_QUERY",+ KERNEL_STARTUP_ERROR: "KERNEL_STARTUP_ERROR",} as const;export type WebSocketClosedReason =diff --git a/frontend/src/core/websocket/useMarimoKernelConnection.tsx b/frontend/src/core/websocket/useMarimoKernelConnection.tsxindex ad43c7f75a..a7e053d880 100644--- a/frontend/src/core/websocket/useMarimoKernelConnection.tsx+++ b/frontend/src/core/websocket/useMarimoKernelConnection.tsx@@ -40,7 +40,7 @@ import {} from "../datasets/request-registry";import { useDatasetsActions } from "../datasets/state";import { UI_ELEMENT_REGISTRY } from "../dom/uiregistry";-import { useBannersActions } from "../errors/state";+import { kernelStartupErrorAtom, useBannersActions } from "../errors/state";import { FUNCTIONS_REGISTRY } from "../functions/FunctionRegistry";import {handleCellNotificationeration,@@ -105,6 +105,7 @@ export function useMarimoKernelConnection(opts: {const setCapabilities = useSetAtom(capabilitiesAtom);const runtimeManager = useRuntimeManager();const setCacheInfo = useSetAtom(cacheInfoAtom);+ const setKernelStartupError = useSetAtom(kernelStartupErrorAtom);const handleMessage = (e: MessageEvent<JsonString<NotificationPayload>>) => {const msg = jsonParseWithSpecialChar(e.data);@@ -134,6 +135,11 @@ export function useMarimoKernelConnection(opts: {case "interrupted":return;+ case "kernel-startup-error":+ // Full error received via message before websocket close+ setKernelStartupError(msg.data.error);+ return;+case "send-ui-element-message": {const modelId = msg.data.model_id;const uiElement = msg.data.ui_element;@@ -413,6 +419,17 @@ export function useMarimoKernelConnection(opts: {return;default:+ // Check for kernel startup error (full error already received via message)+ if (e.reason === "MARIMO_KERNEL_STARTUP_ERROR") {+ setConnection({+ state: WebSocketState.CLOSED,+ code: WebSocketClosedReason.KERNEL_STARTUP_ERROR,+ reason: "Failed to start kernel sandbox",+ });+ ws.close(); // prevent reconnecting+ return;+ }+// Session should be valid// - browser tab might have been closed or re-opened// - computer might have just woken from sleepdiff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.pyindex 0eb8442fc2..40d43e4309 100644--- a/marimo/_cli/cli.py+++ b/marimo/_cli/cli.py@@ -326,19 +326,6 @@ edit_help_msg = "\n".join(type=bool,help=sandbox_message,)- "--dangerous-sandbox/--no-dangerous-sandbox",- is_flag=True,- default=None,- show_default=False,- type=bool,- hidden=True,- help="""Enables the usage of package sandboxing when running a multi-edit-notebook server. This behavior can lead to surprising and unintended consequences,-such as incorrectly overwriting package requirements or failing to write out-requirements. These and other issues are described in-https://github.com/marimo-team/marimo/issues/5219.""",-)@click.option("--trusted/--untrusted",is_flag=True,@@ -428,7 +415,6 @@ def edit(allow_origins: Optional[tuple[str, ...]],skip_update_check: bool,sandbox: Optional[bool],- dangerous_sandbox: Optional[bool],trusted: Optional[bool],profile_dir: Optional[str],watch: bool,@@ -442,7 +428,7 @@ def edit(name: Optional[str],args: tuple[str, ...],) -> None:- from marimo._cli.sandbox import run_in_sandbox, should_run_in_sandbox+ from marimo._cli.sandbox import SandboxMode, resolve_sandbox_modepass_on_stdin = token_password_file == "-"# We support unix-style piping, e.g. cat notebook.py | marimo edit@@ -508,15 +494,29 @@ def edit(# We check this after name validation, because this will convert# URLs into local file paths- if should_run_in_sandbox(- sandbox=sandbox, dangerous_sandbox=dangerous_sandbox, name=name- ):++ # Resolve sandbox mode: None, SandboxMode.SINGLE, or SandboxMode.MULTI+ sandbox_mode = resolve_sandbox_mode(sandbox=sandbox, name=name)++ # Single-file sandbox: wrap with uv run+ if sandbox_mode is SandboxMode.SINGLE:from marimo._cli.sandbox import run_in_sandbox- # TODO: consider adding recommended as wellrun_in_sandbox(sys.argv[1:], name=name, additional_features=["lsp"])return+ # Multi-file sandbox: use IPC kernels with per-notebook sandboxed venvs+ if sandbox_mode is SandboxMode.MULTI:+ # Check for pyzmq dependency+ from marimo._dependencies.dependencies import DependencyManager++ if not DependencyManager.zmq.has():+ raise click.UsageError(+ "pyzmq is required when running the marimo edit server on a directory with --sandbox.\n"+ "Install it with: pip install 'marimo[sandbox]'\n"+ "Or: pip install pyzmq"+ )+start(file_router=AppFileRouter.infer(name),development_mode=GLOBAL_SETTINGS.DEVELOPMENT_MODE,@@ -545,6 +545,7 @@ def edit(server_startup_command=server_startup_command,asset_url=asset_url,timeout=timeout,+ sandbox_mode=sandbox_mode,)@@ -941,7 +942,11 @@ def run(name: str,args: tuple[str, ...],) -> None:- from marimo._cli.sandbox import run_in_sandbox, should_run_in_sandbox+ from marimo._cli.sandbox import (+ SandboxMode,+ resolve_sandbox_mode,+ run_in_sandbox,+ )if prompt_run_in_docker_container(name, trusted=trusted):from marimo._cli.run_docker import run_in_docker@@ -976,9 +981,8 @@ def run(# We check this after name validation, because this will convert# URLs into local file paths- if should_run_in_sandbox(- sandbox=sandbox, dangerous_sandbox=None, name=name- ):+ # For run command, only single-file sandbox is possible (no directory support)+ if resolve_sandbox_mode(sandbox=sandbox, name=name) is SandboxMode.SINGLE:run_in_sandbox(sys.argv[1:], name=name)returndiff --git a/marimo/_cli/sandbox.py b/marimo/_cli/sandbox.pyindex 17c62fd306..fda2b21011 100644--- a/marimo/_cli/sandbox.py+++ b/marimo/_cli/sandbox.py@@ -4,12 +4,14 @@ from __future__ import annotationsimport atexitimport osimport platform+import shutilimport signalimport subprocessimport sysimport tempfile+from enum import Enumfrom pathlib import Path-from typing import Any, Literal, Optional+from typing import Literal, Optionalimport click@@ -26,6 +28,18 @@ from marimo._utils.uv import find_uv_binfrom marimo._utils.versions import is_editablefrom marimo._version import __version__++class SandboxMode(Enum):+ """Sandbox mode for marimo notebooks.++ - SINGLE: Single-file sandbox (wraps entire process with uv run)+ - MULTI: Multi-file sandbox (IPC kernels with per-notebook venvs)+ """++ SINGLE = "single"+ MULTI = "multi"++LOGGER = _loggers.marimo_logger()DepFeatures = Literal["lsp", "recommended"]@@ -77,58 +91,39 @@ def maybe_prompt_run_in_sandbox(name: str | None) -> bool:return False-def should_run_in_sandbox(- sandbox: bool | None, dangerous_sandbox: bool | None, name: str | None-) -> bool:- """Return whether the named notebook should be run in a sandbox.+def resolve_sandbox_mode(+ sandbox: bool | None, name: str | None+) -> SandboxMode | None:+ """Determine sandbox mode for the given target.- Prompts the user if sandbox is None and the notebook has sandbox metadata.+ Returns:+ - None: No sandboxing+ - SandboxMode.SINGLE: Single-file sandbox (wrap with uv run)+ - SandboxMode.MULTI: Multi-file sandbox (IPC kernels with per-notebook venvs)- The `sandbox` arg is whether the user requested sandbox. Even- if running in sandbox was requested, it may not be allowed- if the target is a directory (unless overridden by `dangerous_sandbox`).+ When sandbox is None, prompts the user if the notebook has sandbox metadata+ (only for single notebooks, not directories)."""-- # Dangerous sandbox can be forced on by setting an environment variable;- # this allows our VS Code extension to force sandbox regardless of the- # marimo version.- if sandbox and os.getenv("MARIMO_DANGEROUS_SANDBOX"):- dangerous_sandbox = True-- if dangerous_sandbox and (name is None or os.path.isdir(name)):- sandbox = True- click.echo(- click.style(- "Warning: Using sandbox with multi-notebook edit servers is dangerous.\n",- fg="yellow",- )- + "Notebook dependencies may not be respected, may not be written, and may be overwritten.\n"- + "Learn more: https://github.com/marimo-team/marimo/issues/5219l.\n",- err=True,- )+ # Determine if target is a directory (or None = current directory)+ is_directory = name is None or os.path.isdir(name)# When the sandbox flag is omitted we infer whether to- # to start in sandbox mode by examining the notebook file and- # prompting the user.+ # start in sandbox mode by examining the notebook file and+ # prompting the user. Only prompt for single notebooks, not directories.if sandbox is None:- sandbox = maybe_prompt_run_in_sandbox(name)-- # Validation: we don't yet support multi-notebook sandboxed servers.- if (- sandbox- and not dangerous_sandbox- and (name is None or os.path.isdir(name))- ):- raise click.UsageError(- """marimo's package sandbox requires a notebook name:+ # Don't prompt for directories - user must explicitly pass --sandbox+ if not is_directory:+ sandbox = maybe_prompt_run_in_sandbox(name)+ else:+ sandbox = False- * marimo edit --sandbox my_notebook.py+ if not sandbox:+ return None- Multi-notebook sandboxed servers (marimo edit --sandbox) are not supported.- Follow this issue at: https://github.com/marimo-team/marimo/issues/2598."""- )-- return sandbox+ # Sandbox enabled - determine mode based on target type+ # Directory or home page -> multi-file sandbox (IPC kernels)+ # Single file -> single-file sandbox (uv run wrapper)+ return SandboxMode.MULTI if is_directory else SandboxMode.SINGLEdef _is_versioned(dependency: str) -> bool:@@ -299,8 +294,6 @@ def construct_uv_command(cmd = ["marimo"] + argsif "--sandbox" in cmd:cmd.remove("--sandbox")- if "--dangerous-sandbox" in cmd:- cmd.remove("--dangerous-sandbox")pyproject = (PyProjectReader.from_filename(name)@@ -366,6 +359,15 @@ def run_in_sandbox(additional_features: Optional[list[DepFeatures]] = None,additional_deps: Optional[list[str]] = None,) -> int:+ """Run marimo in a sandboxed uv environment.++ This wraps the marimo command with `uv run` to create an isolated+ virtual environment with the notebook's dependencies.++ Used for "single" sandbox mode (marimo edit --sandbox notebook.py).+ For "multi" sandbox mode (directory), see IPCKernelManagerImpl which+ creates per-notebook sandboxed kernels.+ """# If we fall back to the plain "uv" path, ensure it's actually on the systemif find_uv_bin() == "uv" and not DependencyManager.which("uv"):raise click.UsageError("uv must be installed to use --sandbox")@@ -384,7 +386,7 @@ def run_in_sandbox(process = subprocess.Popen(uv_cmd, env=env)- def handler(sig: int, frame: Any) -> None:+ def handler(sig: int, frame: object) -> None:del sigdel frametry:@@ -399,3 +401,165 @@ def run_in_sandbox(signal.signal(signal.SIGINT, handler)return process.wait()+++# Dependencies required for IPC kernel communication (ZeroMQ-based)+IPC_KERNEL_DEPS: list[str] = ["pyzmq"]+++def get_sandbox_requirements(+ filename: str | None,+ additional_deps: list[str] | None = None,+) -> list[str]:+ """Get normalized requirements for sandbox venv.++ Reads dependencies from the notebook's PEP 723 script metadata,+ normalizes marimo dependency, and adds any additional deps+ (e.g., IPC_KERNEL_DEPS for kernel communication).++ Args:+ filename: Path to notebook file, or None for empty deps.+ additional_deps: Extra dependencies to add if not already present.++ Returns:+ List of normalized requirement strings.+ """+ pyproject = (+ PyProjectReader.from_filename(filename)+ if filename is not None+ else PyProjectReader({}, config_path=None)+ )++ dependencies = _resolve_requirements_txt_lines(pyproject)+ normalized = _normalize_sandbox_dependencies(+ dependencies, __version__, additional_features=[]+ )++ # Add additional deps if not already present+ if additional_deps:+ existing_lower = {+ d.lower().split("[")[0].split(">=")[0].split("==")[0]+ for d in normalized+ }+ for dep in additional_deps:+ if dep.lower() not in existing_lower:+ normalized.append(dep)++ return normalized+++def build_sandbox_venv(+ filename: str | None,+ additional_deps: list[str] | None = None,+) -> tuple[str, str]:+ """Build sandbox venv and install dependencies.++ Creates an ephemeral virtual environment using uv with the notebook's+ dependencies installed. Used for "multi" sandbox mode where each notebook+ gets its own sandboxed environment.++ Args:+ filename: Path to notebook file for reading dependencies.+ additional_deps: Extra dependencies to add (e.g., IPC_KERNEL_DEPS).++ Returns:+ Tuple of (sandbox_dir, venv_python_path).++ Raises:+ RuntimeError: If dependency installation fails.+ """+ uv_bin = find_uv_bin()++ # Create temp directory for sandbox venv+ sandbox_dir = tempfile.mkdtemp(prefix="marimo-sandbox-")+ venv_path = os.path.join(sandbox_dir, "venv")++ # Phase 1: Create venv+ echo(f"Creating sandbox environment: {muted(venv_path)}", err=True)+ subprocess.run(+ [uv_bin, "venv", "--seed", venv_path],+ check=True,+ capture_output=True,+ )++ # Get venv Python path+ if sys.platform == "win32":+ venv_python = os.path.join(venv_path, "Scripts", "python.exe")+ else:+ venv_python = os.path.join(venv_path, "bin", "python")++ # Phase 2: Install dependencies+ requirements = get_sandbox_requirements(filename, additional_deps)+ echo("Installing sandbox dependencies...", err=True)++ # Separate editable installs from regular requirements+ # Editable installs look like "-e /path/to/package"+ editable_reqs = [r for r in requirements if r.startswith("-e ")]+ regular_reqs = [r for r in requirements if not r.startswith("-e ")]++ # Install editable packages directly (not via requirements file)+ for editable in editable_reqs:+ # Extract path from "-e /path/to/package"+ editable_path = editable[3:].strip()+ result = subprocess.run(+ [+ uv_bin,+ "pip",+ "install",+ "--python",+ venv_python,+ "-e",+ editable_path,+ ],+ capture_output=True,+ text=True,+ )+ if result.returncode != 0:+ echo(+ f"Warning: Editable install failed: {result.stderr}",+ err=True,+ )++ # Install regular packages via requirements file+ if regular_reqs:+ req_file = os.path.join(sandbox_dir, "requirements.txt")+ with open(req_file, "w", encoding="utf-8") as f:+ f.write("\n".join(regular_reqs))++ result = subprocess.run(+ [+ uv_bin,+ "pip",+ "install",+ "--python",+ venv_python,+ "-r",+ req_file,+ ],+ capture_output=True,+ text=True,+ )+ if result.returncode != 0:+ # Clean up on failure+ cleanup_sandbox_dir(sandbox_dir)+ raise RuntimeError(+ f"Failed to install sandbox dependencies: {result.stderr}"+ )++ return sandbox_dir, venv_python+++def cleanup_sandbox_dir(sandbox_dir: str | None) -> None:+ """Clean up sandbox directory.++ Safely removes the sandbox directory and all its contents.+ Silently ignores errors (e.g., if directory doesn't exist).++ Args:+ sandbox_dir: Path to sandbox directory, or None (no-op).+ """+ if sandbox_dir:+ try:+ shutil.rmtree(sandbox_dir)+ except OSError:+ passdiff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.pyindex bc205f9253..4102776808 100644--- a/marimo/_dependencies/dependencies.py+++ b/marimo/_dependencies/dependencies.py@@ -239,6 +239,7 @@ class DependencyManager:redshift_connector = Dependency("redshift_connector")mcp = Dependency("mcp")pydantic_ai = Dependency("pydantic_ai")+ zmq = Dependency("zmq") # pyzmq for sandbox IPC kernels# Version requirements to properly support the new superfences introduced in# pymdown#2470diff --git a/marimo/_ipc/types.py b/marimo/_ipc/types.pyindex 36ddb31ef9..71d1f49894 100644--- a/marimo/_ipc/types.py+++ b/marimo/_ipc/types.py@@ -34,6 +34,9 @@ class KernelArgs(msgspec.Struct):log_level: intprofile_path: typing.Union[str, None]connection_info: ConnectionInfo+ # Runtime behavior flags+ virtual_files_supported: bool = True+ redirect_console_to_browser: bool = Truedef encode_json(self) -> bytes:return encode_json_bytes(self)diff --git a/marimo/_messaging/notification.py b/marimo/_messaging/notification.pyindex d8a203cedf..861cf25250 100644--- a/marimo/_messaging/notification.py+++ b/marimo/_messaging/notification.py@@ -246,6 +246,13 @@ class BannerNotification(Notification, tag="banner"):action: Optional[Literal["restart"]] = None+class KernelStartupErrorNotification(Notification, tag="kernel-startup-error"):+ """Notification sent when kernel fails to start (e.g., sandbox build failure)."""++ name: ClassVar[str] = "kernel-startup-error"+ error: str++class ReloadNotification(Notification, tag="reload"):name: ClassVar[str] = "reload"@@ -446,6 +453,7 @@ NotificationMessage = Union[MissingPackageAlertNotification,InstallingPackageAlertNotification,StartupLogsNotification,+ KernelStartupErrorNotification,# VariablesVariablesNotification,VariableValuesNotification,diff --git a/marimo/_server/api/endpoints/assets.py b/marimo/_server/api/endpoints/assets.pyindex ed2640e7d6..07065c1441 100644--- a/marimo/_server/api/endpoints/assets.py+++ b/marimo/_server/api/endpoints/assets.py@@ -12,6 +12,7 @@ from starlette.responses import FileResponse, HTMLResponse, Responsefrom starlette.staticfiles import StaticFilesfrom marimo import _loggers+from marimo._cli.sandbox import SandboxModefrom marimo._config.manager import get_default_config_managerfrom marimo._output.utils import uri_decode_component, uri_encode_componentfrom marimo._runtime.virtual_file import EMPTY_VIRTUAL_FILE, read_virtual_file@@ -23,6 +24,7 @@ from marimo._server.templates.templates import (inject_script,notebook_page_template,)+from marimo._utils.async_path import AsyncPathfrom marimo._utils.paths import marimo_package_pathif TYPE_CHECKING:@@ -144,6 +146,25 @@ async def index(request: Request) -> HTMLResponse:app_manager = app_state.session_manager.app_manager(file_key)app_config = app_manager.app.config+ # Pre-compute notebook snapshot for faster initial render+ # Only in SandboxMode.MULTI where each notebook gets its own IPC kernel+ notebook_snapshot = None+ if (+ app_state.session_manager.sandbox_mode is SandboxMode.MULTI+ and app_manager.filename+ ):+ from marimo._convert.converters import MarimoConvert++ filepath = AsyncPath(app_manager.filename)+ if await filepath.exists():+ try:+ content = await filepath.read_text(encoding="utf-8")+ notebook_snapshot = MarimoConvert.from_py(+ content+ ).to_notebook_v1()+ except Exception:+ LOGGER.debug("Failed to pre-compute notebook snapshot")+# Make filename relative to file router's directory if possiblefilename = app_manager.filenamedirectory = app_state.session_manager.file_router.directory@@ -162,6 +183,7 @@ async def index(request: Request) -> HTMLResponse:app_config=app_config,filename=filename,mode=app_state.mode,+ notebook_snapshot=notebook_snapshot,runtime_config=[{"url": app_state.remote_url}]if app_state.remote_urlelse None,diff --git a/marimo/_server/api/endpoints/editing.py b/marimo/_server/api/endpoints/editing.pyindex 89cd139b77..f9b08a39f3 100644--- a/marimo/_server/api/endpoints/editing.py+++ b/marimo/_server/api/endpoints/editing.py@@ -5,6 +5,7 @@ from typing import TYPE_CHECKINGfrom starlette.authentication import requires+from marimo._cli.sandbox import SandboxModefrom marimo._messaging.notification import UpdateCellIdsNotificationfrom marimo._server.api.deps import AppStatefrom marimo._server.api.utils import dispatch_control_request, parse_request@@ -136,7 +137,17 @@ async def format_cell(request: Request) -> FormatResponse:body = await parse_request(request, cls=FormatCellsRequest)formatter = DefaultFormatter(line_length=body.line_length)- return FormatResponse(codes=await formatter.format(body.codes))+ try:+ return FormatResponse(codes=await formatter.format(body.codes))+ except ModuleNotFoundError:+ app_state = AppState(request)+ # Installation occurs in the kernel which is not useful for multi mode.+ if app_state.session_manager.sandbox_mode is SandboxMode.MULTI:+ # Re-raise without name so error handler won't send install notification+ raise ModuleNotFoundError(+ "Server does not have a formatter. Please install ruff"+ ) from None+ raise@router.post("/set_cell_config")diff --git a/marimo/_server/api/endpoints/ws/ws_formatter.py b/marimo/_server/api/endpoints/ws/ws_formatter.pynew file mode 100644index 0000000000..59fd3836e9--- /dev/null+++ b/marimo/_server/api/endpoints/ws/ws_formatter.py@@ -0,0 +1,50 @@+# Copyright 2026 Marimo. All rights reserved.+"""WebSocket message formatting utilities.++This module handles the wire format for WebSocket transport:+wrapping serialized notification data with operation metadata.+"""++from __future__ import annotations++from typing import TYPE_CHECKING++from marimo._messaging.serde import serialize_kernel_message++if TYPE_CHECKING:+ from marimo._messaging.notification import NotificationMessage+++def format_wire_message(op: str, data: bytes) -> str:+ """Format a serialized message for WebSocket transport.++ Wraps serialized notification data with operation metadata+ for the WebSocket wire protocol.++ Args:+ op: The operation name (e.g., "cell-op", "kernel-ready")+ data: The serialized notification data as bytes++ Returns:+ JSON string in wire format: {"op": "...", "data": ...}+ """+ return f'{{"op": "{op}", "data": {data.decode("utf-8")}}}'+++def serialize_notification_for_websocket(+ notification: NotificationMessage,+) -> str:+ """Serialize and format a notification for WebSocket transport.++ Combines serialization and wire formatting into a single operation.+ Useful when you have a notification object and need the final wire format.++ Args:+ notification: The notification to serialize and format++ Returns:+ JSON string in wire format: {"op": "...", "data": ...}+ """+ serialized = serialize_kernel_message(notification)+ op = notification.name+ return format_wire_message(op, serialized)diff --git a/marimo/_server/api/endpoints/ws/ws_message_loop.py b/marimo/_server/api/endpoints/ws/ws_message_loop.pyindex ab99354f82..b5d228e90b 100644--- a/marimo/_server/api/endpoints/ws/ws_message_loop.py+++ b/marimo/_server/api/endpoints/ws/ws_message_loop.py@@ -13,6 +13,7 @@ from marimo._messaging.notification import ()from marimo._messaging.serde import deserialize_kernel_notification_namefrom marimo._messaging.types import KernelMessage+from marimo._server.api.endpoints.ws.ws_formatter import format_wire_messageif TYPE_CHECKING:from starlette.websockets import WebSocket@@ -79,7 +80,7 @@ class WebSocketMessageLoop:# Serialize messagetry:- text = f'{{"op": "{op}", "data": {data.decode("utf-8")}}}'+ text = format_wire_message(op, data)except Exception as e:LOGGER.error("Failed to deserialize message: %s", str(e))LOGGER.error("Message: %s", data)diff --git a/marimo/_server/api/endpoints/ws_endpoint.py b/marimo/_server/api/endpoints/ws_endpoint.pyindex 8540e9ac9d..40b55fdf5d 100644--- a/marimo/_server/api/endpoints/ws_endpoint.py+++ b/marimo/_server/api/endpoints/ws_endpoint.py@@ -15,6 +15,7 @@ from marimo._dependencies.dependencies import DependencyManagerfrom marimo._messaging.notification import (AlertNotification,BannerNotification,+ KernelStartupErrorNotification,NotificationMessage,ReconnectedNotification,)@@ -26,6 +27,9 @@ from marimo._server.api.endpoints.ws.ws_connection_validator import (ConnectionParams,WebSocketConnectionValidator,)+from marimo._server.api.endpoints.ws.ws_formatter import (+ serialize_notification_for_websocket,+)from marimo._server.api.endpoints.ws.ws_kernel_ready import (build_kernel_ready,is_rtc_available,@@ -44,6 +48,7 @@ from marimo._server.session_manager import SessionManagerfrom marimo._session import Sessionfrom marimo._session.consumer import SessionConsumerfrom marimo._session.events import SessionEventBus+from marimo._session.managers.ipc import KernelStartupErrorfrom marimo._session.model import (ConnectionState,SessionMode,@@ -377,7 +382,12 @@ class WebSocketHandler(SessionConsumer):params=self.params,websocket=self.websocket,)- session, connection_type = connector.connect()+ try:+ session, connection_type = connector.connect()+ except KernelStartupError as e:+ LOGGER.error("Kernel startup failed: %s", e)+ await self._close_kernel_startup_error(str(e))+ returnLOGGER.debug("Connected to session %s with type %s",session.initialization_id,@@ -425,6 +435,18 @@ class WebSocketHandler(SessionConsumer):"MARIMO_ALREADY_CONNECTED",)+ async def _close_kernel_startup_error(self, error_message: str) -> None:+ """Send full error as message, then close the WebSocket."""+ if self.websocket.application_state is WebSocketState.CONNECTED:+ notification = KernelStartupErrorNotification(error=error_message)+ text = serialize_notification_for_websocket(notification)+ await self.websocket.send_text(text)+ # Then close with simple reason+ await self.websocket.close(+ WebSocketCodes.UNEXPECTED_ERROR,+ "MARIMO_KERNEL_STARTUP_ERROR",+ )+def on_attach(self, session: Session, event_bus: SessionEventBus) -> None:del sessiondel event_busdiff --git a/marimo/_server/session_manager.py b/marimo/_server/session_manager.pyindex a4a6139632..9fb0eb186d 100644--- a/marimo/_server/session_manager.py+++ b/marimo/_server/session_manager.py@@ -13,6 +13,7 @@ from pathlib import Pathfrom typing import TYPE_CHECKING, Optional, TypeVarfrom marimo import _loggers+from marimo._cli.sandbox import SandboxModefrom marimo._config.manager import MarimoConfigManagerfrom marimo._runtime.commands import (SerializedCLIArgs,@@ -76,6 +77,7 @@ class SessionManager:redirect_console_to_browser: bool,ttl_seconds: Optional[int],watch: bool = False,+ sandbox_mode: SandboxMode | None = None,) -> None:# Core configurationself.file_router = file_router@@ -88,6 +90,7 @@ class SessionManager:self.argv = argvself.redirect_console_to_browser = redirect_console_to_browserself._config_manager = config_manager+ self.sandbox_mode = sandbox_modeself._repository = SessionRepository()@@ -188,6 +191,7 @@ class SessionManager:ttl_seconds=self.ttl_seconds,auto_instantiate=auto_instantiate,extensions=extensions,+ sandbox_mode=self.sandbox_mode,)# Add to repositorydiff --git a/marimo/_server/start.py b/marimo/_server/start.pyindex 753d747466..e791895173 100644--- a/marimo/_server/start.py+++ b/marimo/_server/start.py@@ -11,6 +11,7 @@ import uvicornimport marimo._server.api.lifespans as lifespansfrom marimo._cli.print import echo+from marimo._cli.sandbox import SandboxModefrom marimo._config.manager import get_default_config_managerfrom marimo._config.settings import GLOBAL_SETTINGSfrom marimo._mcp.server.main import setup_mcp_server@@ -177,6 +178,7 @@ def start(server_startup_command: Optional[str] = None,asset_url: Optional[str] = None,timeout: Optional[float] = None,+ sandbox_mode: SandboxMode | None = None,) -> None:"""Start the server.@@ -243,6 +245,7 @@ def start(auth_token=auth_token,redirect_console_to_browser=redirect_console_to_browser,watch=watch,+ sandbox_mode=sandbox_mode,)log_level = "info" if development_mode else "error"diff --git a/marimo/_session/extensions/extensions.py b/marimo/_session/extensions/extensions.pyindex d3d6da8a42..095433a29f 100644--- a/marimo/_session/extensions/extensions.py+++ b/marimo/_session/extensions/extensions.py@@ -196,14 +196,13 @@ class NotificationListenerExtension(SessionExtension):kernel_manager: KernelManager,queue_manager: QueueManager,) -> Distributor[KernelMessage]:- from marimo._session.model import SessionMode-- if kernel_manager.mode == SessionMode.EDIT:- return ConnectionDistributor(kernel_manager.kernel_connection)+ # IPC kernels (home sandbox mode) and run mode use stream_queue+ # Edit mode without IPC uses kernel_connection+ if queue_manager.stream_queue is not None:+ return QueueDistributor(queue=queue_manager.stream_queue)else:- q = queue_manager.stream_queue- assert q is not None- return QueueDistributor(queue=q)+ # Edit mode with original kernel manager uses connection+ return ConnectionDistributor(kernel_manager.kernel_connection)def on_attach(self, session: Session, event_bus: SessionEventBus) -> None:del event_busdiff --git a/marimo/_session/managers/__init__.py b/marimo/_session/managers/__init__.pynew file mode 100644index 0000000000..3b25543d43--- /dev/null+++ b/marimo/_session/managers/__init__.py@@ -0,0 +1,28 @@+# Copyright 2026 Marimo. All rights reserved.+"""Queue and Kernel managers for session management.++This module contains the infrastructure components for managing+kernel processes/threads and their associated communication queues.++Standard implementations (QueueManagerImpl, KernelManagerImpl):+ Use multiprocessing.Process for edit mode and threading.Thread for run mode.+ Communicate via multiprocessing or threading queues.++IPC implementations (IPCQueueManagerImpl, IPCKernelManagerImpl):+ Launch kernel as subprocess with ZeroMQ IPC.+ Each notebook gets its own sandboxed virtual environment.+"""++from marimo._session.managers.ipc import (+ IPCKernelManagerImpl,+ IPCQueueManagerImpl,+)+from marimo._session.managers.kernel import KernelManagerImpl+from marimo._session.managers.queue import QueueManagerImpl++__all__ = [+ "QueueManagerImpl",+ "KernelManagerImpl",+ "IPCQueueManagerImpl",+ "IPCKernelManagerImpl",+]diff --git a/marimo/_session/managers/ipc.py b/marimo/_session/managers/ipc.pynew file mode 100644index 0000000000..f4df727800--- /dev/null+++ b/marimo/_session/managers/ipc.py@@ -0,0 +1,308 @@+# Copyright 2026 Marimo. All rights reserved.+"""IPC-based managers using ZeroMQ.++These implementations launch the kernel as a subprocess and communicate+via ZeroMQ channels. Each notebook gets its own sandboxed virtual environment.+"""++from __future__ import annotations++import os+import signal+import subprocess+import sys+from typing import TYPE_CHECKING, Optional, Union, cast++from marimo import _loggers+from marimo._cli.sandbox import (+ IPC_KERNEL_DEPS,+ build_sandbox_venv,+ cleanup_sandbox_dir,+)+from marimo._config.settings import GLOBAL_SETTINGS+from marimo._messaging.types import KernelMessage+from marimo._runtime import commands+from marimo._session.model import SessionMode+from marimo._session.queue import ProcessLike, QueueType+from marimo._session.types import KernelManager, QueueManager+from marimo._utils.typed_connection import TypedConnection++if TYPE_CHECKING:+ from marimo._ast.cell import CellConfig+ from marimo._config.manager import MarimoConfigReader+ from marimo._ipc.queue_manager import QueueManager as IPCQueueManagerType+ from marimo._ipc.types import ConnectionInfo+ from marimo._runtime.commands import AppMetadata+ from marimo._types.ids import CellId_t++LOGGER = _loggers.marimo_logger()+++class KernelStartupError(Exception):+ """Raised when kernel subprocess fails to start."""+++class IPCQueueManagerImpl(QueueManager):+ """Manages queues for a session via ZeroMQ IPC.++ This wraps the ZeroMQ-based IPC QueueManager to provide queues+ for communication with the kernel subprocess.+ """++ def __init__(self, ipc: IPCQueueManagerType) -> None:+ self._ipc = ipc++ @classmethod+ def from_ipc(cls, ipc: IPCQueueManagerType) -> IPCQueueManagerImpl:+ """Create an IPCQueueManagerImpl from an IPC queue manager."""+ return cls(ipc)++ @property+ def control_queue( # type: ignore[override]+ self,+ ) -> QueueType[commands.CommandMessage]:+ return self._ipc.control_queue++ @property+ def set_ui_element_queue( # type: ignore[override]+ self,+ ) -> QueueType[commands.UpdateUIElementCommand]:+ return self._ipc.set_ui_element_queue++ @property+ def completion_queue( # type: ignore[override]+ self,+ ) -> QueueType[commands.CodeCompletionCommand]:+ return self._ipc.completion_queue++ @property+ def input_queue( # type: ignore[override]+ self,+ ) -> QueueType[str]:+ return self._ipc.input_queue++ @property+ def stream_queue( # type: ignore[override]+ self,+ ) -> QueueType[Union[KernelMessage, None]]:+ return cast(+ QueueType[Union[KernelMessage, None]],+ self._ipc.stream_queue,+ )++ @property+ def win32_interrupt_queue( # type: ignore[override]+ self,+ ) -> Optional[QueueType[bool]]:+ return self._ipc.win32_interrupt_queue++ def close_queues(self) -> None:+ self._ipc.close_queues()++ def put_control_request(self, request: commands.CommandMessage) -> None:+ # Completions are on their own queue+ if isinstance(request, commands.CodeCompletionCommand):+ self.completion_queue.put(request)+ return++ self.control_queue.put(request)+ # Update UI elements are on both queues so they can be batched+ if isinstance(request, commands.UpdateUIElementCommand):+ self.set_ui_element_queue.put(request)++ def put_input(self, text: str) -> None:+ self.input_queue.put(text)+++class IPCKernelManagerImpl(KernelManager):+ """IPC-based kernel manager to spawn sandboxed kernels.++ Launches the kernel as a subprocess and communicates via ZeroMQ channels.+ Each notebook gets its own sandboxed virtual environment.+ """++ def __init__(+ self,+ *,+ queue_manager: IPCQueueManagerImpl,+ connection_info: ConnectionInfo,+ mode: SessionMode,+ configs: dict[CellId_t, CellConfig],+ app_metadata: AppMetadata,+ config_manager: MarimoConfigReader,+ virtual_files_supported: bool = True,+ redirect_console_to_browser: bool = True,+ ) -> None:+ self.queue_manager = queue_manager+ self.connection_info = connection_info+ self.mode = mode+ self.configs = configs+ self.app_metadata = app_metadata+ self.config_manager = config_manager+ self.virtual_files_supported = virtual_files_supported+ self.redirect_console_to_browser = redirect_console_to_browser++ self._process: subprocess.Popen[bytes] | None = None+ self.kernel_task: ProcessLike | None = None+ self._sandbox_dir: str | None = None++ def start_kernel(self) -> None:+ from marimo._cli.print import echo, muted+ from marimo._ipc.types import KernelArgs++ # Build kernel args+ kernel_args = KernelArgs(+ configs=self.configs,+ app_metadata=self.app_metadata,+ user_config=self.config_manager.get_config(hide_secrets=False),+ log_level=GLOBAL_SETTINGS.LOG_LEVEL,+ profile_path=None,+ connection_info=self.connection_info,+ virtual_files_supported=self.virtual_files_supported,+ redirect_console_to_browser=self.redirect_console_to_browser,+ )++ # Build environment+ env = os.environ.copy()++ # Build sandbox venv with IPC dependencies+ try:+ self._sandbox_dir, venv_python = build_sandbox_venv(+ self.app_metadata.filename,+ additional_deps=IPC_KERNEL_DEPS,+ )+ cmd = [venv_python, "-m", "marimo._ipc.launch_kernel"]+ except Exception as e:+ cleanup_sandbox_dir(self._sandbox_dir)+ raise KernelStartupError(+ f"Failed to build sandbox environment.\n\n{e}"+ ) from e++ echo(+ f"Running kernel in sandbox: {muted(' '.join(cmd))}",+ err=True,+ )+ # Set MARIMO_MANAGE_SCRIPT_METADATA for sandbox+ env["MARIMO_MANAGE_SCRIPT_METADATA"] = "true"++ LOGGER.debug(f"Launching kernel: {' '.join(cmd)}")++ try:+ self._process = subprocess.Popen(+ cmd,+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ env=env,+ )++ # Send connection info via stdin+ assert self._process.stdin is not None+ self._process.stdin.write(kernel_args.encode_json())+ self._process.stdin.flush()+ self._process.stdin.close()++ # Wait for ready signal+ assert self._process.stdout is not None+ ready = self._process.stdout.readline().decode().strip()+ if ready != "KERNEL_READY":+ assert self._process.stderr is not None+ stderr = self._process.stderr.read().decode()+ raise KernelStartupError(+ f"Kernel failed to start.\n\n"+ f"Command: {' '.join(cmd)}\n\n"+ f"Stderr:\n{stderr}"+ )++ LOGGER.debug("Kernel ready")++ # Create a ProcessLike wrapper for the subprocess+ self.kernel_task = _SubprocessWrapper(self._process)+ except KernelStartupError:+ # Already a KernelStartupError, just cleanup and re-raise+ cleanup_sandbox_dir(self._sandbox_dir)+ raise+ except Exception as e:+ # Wrap other exceptions as KernelStartupError+ cleanup_sandbox_dir(self._sandbox_dir)+ raise KernelStartupError(+ f"Failed to start kernel subprocess.\n\n{e}"+ ) from e++ @property+ def pid(self) -> int | None:+ if self._process is None:+ return None+ return self._process.pid++ @property+ def profile_path(self) -> str | None:+ # Profiling not currently supported with IPC kernel+ return None++ def is_alive(self) -> bool:+ if self._process is None:+ return False+ return self._process.poll() is None++ def interrupt_kernel(self) -> None:+ if self._process is None:+ return++ if self._process.pid is not None:+ q = self.queue_manager.win32_interrupt_queue+ if sys.platform == "win32" and q is not None:+ LOGGER.debug("Queueing interrupt request for kernel.")+ q.put_nowait(True)+ else:+ LOGGER.debug("Sending SIGINT to kernel")+ os.kill(self._process.pid, signal.SIGINT)++ def close_kernel(self) -> None:+ if self._process is not None:+ self.queue_manager.put_control_request(+ commands.StopKernelCommand()+ )+ self.queue_manager.close_queues()++ # Terminate process if still alive+ if self._process.poll() is None:+ self._process.terminate()+ try:+ self._process.wait(timeout=5)+ except subprocess.TimeoutExpired:+ self._process.kill()++ # Always attempt cleanup, even if _process is None+ cleanup_sandbox_dir(self._sandbox_dir)+ self._sandbox_dir = None++ @property+ def kernel_connection(self) -> TypedConnection[KernelMessage]:+ # IPC kernel uses stream_queue instead of kernel_connection+ raise NotImplementedError(+ "IPC kernel uses stream_queue, not kernel_connection"+ )+++class _SubprocessWrapper(ProcessLike):+ """Wrapper to make subprocess.Popen compatible with ProcessLike."""++ def __init__(self, process: subprocess.Popen[bytes]) -> None:+ self._process = process++ @property+ def pid(self) -> int | None:+ return self._process.pid++ def is_alive(self) -> bool:+ return self._process.poll() is None++ def terminate(self) -> None:+ self._process.terminate()++ def kill(self) -> None:+ self._process.kill()++ def join(self, timeout: Optional[float] = None) -> None:+ self._process.wait(timeout=timeout)diff --git a/marimo/_session/managers.py b/marimo/_session/managers/kernel.pysimilarity index 64%rename from marimo/_session/managers.pyrename to marimo/_session/managers/kernel.pyindex 775fae7ed7..549ddcde63 100644--- a/marimo/_session/managers.py+++ b/marimo/_session/managers/kernel.py@@ -1,138 +1,44 @@# Copyright 2026 Marimo. All rights reserved.-"""Queue and Kernel managers for session management.--This module contains the infrastructure components for managing-kernel processes/threads and their associated communication queues.-"""+"""Kernel manager implementation using multiprocessing Process or threading Thread."""from __future__ import annotationsimport os-import queueimport signalimport sysimport threadingimport time-from multiprocessing import Process, connection, get_context-from multiprocessing.queues import Queue as MPQueue-from typing import Any, Optional, Union+from multiprocessing import Process, connection+from typing import TYPE_CHECKING, Any, Optional, Unionfrom uuid import uuid4from marimo import _loggers-from marimo._ast.cell import CellConfig-from marimo._config.manager import MarimoConfigReaderfrom marimo._config.settings import GLOBAL_SETTINGSfrom marimo._messaging.types import KernelMessagefrom marimo._output.formatters.formatters import register_formattersfrom marimo._runtime import commands, runtime-from marimo._runtime.commands import AppMetadatafrom marimo._session.model import SessionModefrom marimo._session.queue import ProcessLikefrom marimo._session.types import KernelManager, QueueManager-from marimo._types.ids import CellId_tfrom marimo._utils.print import print_from marimo._utils.typed_connection import TypedConnection-LOGGER = _loggers.marimo_logger()---class QueueManagerImpl(QueueManager):- """Manages queues for a session."""-- def __init__(self, *, use_multiprocessing: bool):- context = get_context("spawn") if use_multiprocessing else None-- # Control messages for the kernel (run, set UI element, set config, etc- # ) are sent through the control queue- self.control_queue: Union[- MPQueue[commands.CommandMessage],- queue.Queue[commands.CommandMessage],- ] = context.Queue() if context is not None else queue.Queue()-- # Set UI element queues are stored in both the control queue and- # this queue, so that the backend can merge/batch set-ui-element- # requests.- self.set_ui_element_queue: Union[- MPQueue[commands.UpdateUIElementCommand],- queue.Queue[commands.UpdateUIElementCommand],- ] = context.Queue() if context is not None else queue.Queue()-- # Code completion requests are sent through a separate queue- self.completion_queue: Union[- MPQueue[commands.CodeCompletionCommand],- queue.Queue[commands.CodeCompletionCommand],- ] = context.Queue() if context is not None else queue.Queue()-- self.win32_interrupt_queue: (- Union[MPQueue[bool], queue.Queue[bool]] | None- )- if sys.platform == "win32":- self.win32_interrupt_queue = (- context.Queue() if context is not None else queue.Queue()- )- else:- self.win32_interrupt_queue = None-- # Input messages for the user's Python code are sent through the- # input queue- self.input_queue: Union[MPQueue[str], queue.Queue[str]] = (- context.Queue(maxsize=1)- if context is not None- else queue.Queue(maxsize=1)- )- self.stream_queue: Optional[- queue.Queue[Union[KernelMessage, None]]- ] = None- if not use_multiprocessing:- self.stream_queue = queue.Queue()-- def close_queues(self) -> None:- if isinstance(self.control_queue, MPQueue):- # cancel join thread because we don't care if the queues still have- # things in it: don't want to make the child process wait for the- # queues to empty- self.control_queue.cancel_join_thread()- self.control_queue.close()- else:- # kernel thread cleans up read/write conn and IOloop handler on- # exit; we don't join the thread because we don't want to block- self.control_queue.put(commands.StopKernelCommand())-- if isinstance(self.set_ui_element_queue, MPQueue):- self.set_ui_element_queue.cancel_join_thread()- self.set_ui_element_queue.close()-- if isinstance(self.input_queue, MPQueue):- # again, don't make the child process wait for the queues to empty- self.input_queue.cancel_join_thread()- self.input_queue.close()-- if isinstance(self.completion_queue, MPQueue):- self.completion_queue.cancel_join_thread()- self.completion_queue.close()+if TYPE_CHECKING:+ from marimo._ast.cell import CellConfig+ from marimo._config.manager import MarimoConfigReader+ from marimo._runtime.commands import AppMetadata+ from marimo._types.ids import CellId_t- if isinstance(self.win32_interrupt_queue, MPQueue):- self.win32_interrupt_queue.cancel_join_thread()- self.win32_interrupt_queue.close()-- def put_control_request(self, request: commands.CommandMessage) -> None:- """Put a control request in the control queue."""- # Completions are on their own queue- if isinstance(request, commands.CodeCompletionCommand):- self.completion_queue.put(request)- return+LOGGER = _loggers.marimo_logger()- self.control_queue.put(request)- # Update UI elements are on both queues so they can be batched- if isinstance(request, commands.UpdateUIElementCommand):- self.set_ui_element_queue.put(request)- def put_input(self, text: str) -> None:- """Put an input request in the input queue."""- self.input_queue.put(text)+class KernelManagerImpl(KernelManager):+ """Kernel manager using multiprocessing Process or threading Thread.+ Uses Process for edit mode (allows SIGINT interrupts) and Thread for+ run mode (lower memory overhead).+ """-class KernelManagerImpl(KernelManager):def __init__(self,*,@@ -144,7 +50,7 @@ class KernelManagerImpl(KernelManager):virtual_files_supported: bool,redirect_console_to_browser: bool,) -> None:- self.kernel_task: Optional[ProcessLike | threading.Thread] = None+ self.kernel_task: Optional[Union[ProcessLike, threading.Thread]] = Noneself.queue_manager = queue_managerself.mode = modeself.configs = configs@@ -197,7 +103,9 @@ class KernelManagerImpl(KernelManager):# We can't terminate threads, so we have to wait until they# naturally exit before cleaning up resources- def launch_kernel_with_cleanup(*args: Any) -> None:+ def launch_kernel_with_cleanup(+ *args: Any,+ ) -> None:runtime.launch_kernel(*args)# install formatter import hooks, which will be shared by alldiff --git a/marimo/_session/managers/queue.py b/marimo/_session/managers/queue.pynew file mode 100644index 0000000000..700f0bc3e8--- /dev/null+++ b/marimo/_session/managers/queue.py@@ -0,0 +1,110 @@+# Copyright 2026 Marimo. All rights reserved.+"""Queue manager implementation using multiprocessing or threading queues."""++from __future__ import annotations++import queue+import sys+from multiprocessing import get_context+from multiprocessing.queues import Queue as MPQueue+from typing import Optional, Union++from marimo._messaging.types import KernelMessage+from marimo._runtime import commands+from marimo._session.types import QueueManager+++class QueueManagerImpl(QueueManager):+ """Manages queues for a session using multiprocessing or threading queues."""++ def __init__(self, *, use_multiprocessing: bool):+ context = get_context("spawn") if use_multiprocessing else None++ # Control messages for the kernel (run, set UI element, set config, etc+ # ) are sent through the control queue+ self.control_queue: Union[+ MPQueue[commands.CommandMessage],+ queue.Queue[commands.CommandMessage],+ ] = context.Queue() if context is not None else queue.Queue()++ # Set UI element queues are stored in both the control queue and+ # this queue, so that the backend can merge/batch set-ui-element+ # requests.+ self.set_ui_element_queue: Union[+ MPQueue[commands.UpdateUIElementCommand],+ queue.Queue[commands.UpdateUIElementCommand],+ ] = context.Queue() if context is not None else queue.Queue()++ # Code completion requests are sent through a separate queue+ self.completion_queue: Union[+ MPQueue[commands.CodeCompletionCommand],+ queue.Queue[commands.CodeCompletionCommand],+ ] = context.Queue() if context is not None else queue.Queue()++ self.win32_interrupt_queue: (+ Union[MPQueue[bool], queue.Queue[bool]] | None+ )+ if sys.platform == "win32":+ self.win32_interrupt_queue = (+ context.Queue() if context is not None else queue.Queue()+ )+ else:+ self.win32_interrupt_queue = None++ # Input messages for the user's Python code are sent through the+ # input queue+ self.input_queue: Union[MPQueue[str], queue.Queue[str]] = (+ context.Queue(maxsize=1)+ if context is not None+ else queue.Queue(maxsize=1)+ )+ self.stream_queue: Optional[+ queue.Queue[Union[KernelMessage, None]]+ ] = None+ if not use_multiprocessing:+ self.stream_queue = queue.Queue()++ def close_queues(self) -> None:+ if isinstance(self.control_queue, MPQueue):+ # cancel join thread because we don't care if the queues still have+ # things in it: don't want to make the child process wait for the+ # queues to empty+ self.control_queue.cancel_join_thread()+ self.control_queue.close()+ else:+ # kernel thread cleans up read/write conn and IOloop handler on+ # exit; we don't join the thread because we don't want to block+ self.control_queue.put(commands.StopKernelCommand())++ if isinstance(self.set_ui_element_queue, MPQueue):+ self.set_ui_element_queue.cancel_join_thread()+ self.set_ui_element_queue.close()++ if isinstance(self.input_queue, MPQueue):+ # again, don't make the child process wait for the queues to empty+ self.input_queue.cancel_join_thread()+ self.input_queue.close()++ if isinstance(self.completion_queue, MPQueue):+ self.completion_queue.cancel_join_thread()+ self.completion_queue.close()++ if isinstance(self.win32_interrupt_queue, MPQueue):+ self.win32_interrupt_queue.cancel_join_thread()+ self.win32_interrupt_queue.close()++ def put_control_request(self, request: commands.CommandMessage) -> None:+ """Put a control request in the control queue."""+ # Completions are on their own queue+ if isinstance(request, commands.CodeCompletionCommand):+ self.completion_queue.put(request)+ return++ self.control_queue.put(request)+ # Update UI elements are on both queues so they can be batched+ if isinstance(request, commands.UpdateUIElementCommand):+ self.set_ui_element_queue.put(request)++ def put_input(self, text: str) -> None:+ """Put an input request in the input queue."""+ self.input_queue.put(text)diff --git a/marimo/_session/notebook/file_manager.py b/marimo/_session/notebook/file_manager.pyindex 5c8d01c8ee..5e04b31d59 100644--- a/marimo/_session/notebook/file_manager.py+++ b/marimo/_session/notebook/file_manager.py@@ -186,6 +186,17 @@ class AppFileManager:elif path.exists():header = handler.extract_header(path)+ # For new .py files in sandbox mode, generate header with marimo+ if header is None and str(path).endswith(".py"):+ from marimo._config.settings import GLOBAL_SETTINGS++ if GLOBAL_SETTINGS.MANAGE_SCRIPT_METADATA:+ from marimo._utils.scripts import write_pyproject_to_script++ header = write_pyproject_to_script(+ {"dependencies": ["marimo"]}+ )+# Rewrap with header if relevant and set filename.notebook = NotebookSerializationV1(app=notebook.app,diff --git a/marimo/_session/session.py b/marimo/_session/session.pyindex fb6c44404c..4ba3c60e2f 100644--- a/marimo/_session/session.py+++ b/marimo/_session/session.py@@ -11,6 +11,7 @@ from typing import TYPE_CHECKING, Optionalfrom uuid import uuid4from marimo import _loggers+from marimo._cli.sandbox import SandboxModefrom marimo._config.manager import MarimoConfigManager, ScriptConfigManagerfrom marimo._messaging.notification import (NotificationMessage,@@ -48,6 +49,7 @@ from marimo._session.state.session_view import SessionViewfrom marimo._session.types import (KernelManager,KernelState,+ QueueManager,Session,)from marimo._types.ids import ConsumerId@@ -87,6 +89,7 @@ class SessionImpl(Session):auto_instantiate: bool,ttl_seconds: Optional[int],extensions: list[SessionExtension] | None = None,+ sandbox_mode: SandboxMode | None = None,) -> Session:"""Create a new session.@@ -98,19 +101,45 @@ class SessionImpl(Session):)configs = app_file_manager.app.cell_manager.config_map()- use_multiprocessing = mode == SessionMode.EDIT- queue_manager = QueueManagerImpl(- use_multiprocessing=use_multiprocessing- )- kernel_manager = KernelManagerImpl(- queue_manager=queue_manager,- mode=mode,- configs=configs,- app_metadata=app_metadata,- config_manager=config_manager,- virtual_files_supported=virtual_files_supported,- redirect_console_to_browser=redirect_console_to_browser,- )++ # Create kernel manager+ # SandboxMode.MULTI uses IPC kernels with per-notebook sandboxed venvs+ queue_manager: QueueManager+ kernel_manager: KernelManager+ if sandbox_mode is SandboxMode.MULTI:+ from marimo._ipc import QueueManager as IPCQueueManager+ from marimo._session.managers import (+ IPCKernelManagerImpl,+ IPCQueueManagerImpl,+ )++ ipc_queue_manager, connection_info = IPCQueueManager.create()+ queue_manager = IPCQueueManagerImpl.from_ipc(ipc_queue_manager)+ kernel_manager = IPCKernelManagerImpl(+ queue_manager=queue_manager,+ connection_info=connection_info,+ mode=mode,+ configs=configs,+ app_metadata=app_metadata,+ config_manager=config_manager,+ virtual_files_supported=virtual_files_supported,+ redirect_console_to_browser=redirect_console_to_browser,+ )+ else:+ # Original kernel: Process for edit, Thread for run+ use_multiprocessing = mode == SessionMode.EDIT+ queue_manager = QueueManagerImpl(+ use_multiprocessing=use_multiprocessing+ )+ kernel_manager = KernelManagerImpl(+ queue_manager=queue_manager,+ mode=mode,+ configs=configs,+ app_metadata=app_metadata,+ config_manager=config_manager,+ virtual_files_supported=virtual_files_supported,+ redirect_console_to_browser=redirect_console_to_browser,+ )extensions = [*(extensions or []),diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yamlindex f875712c60..8dd9831347 100644--- a/packages/openapi/api.yaml+++ b/packages/openapi/api.yaml@@ -2201,6 +2201,20 @@ components:- capabilitiestitle: KernelReadyNotificationtype: object+ KernelStartupErrorNotification:+ description: Notification sent when kernel fails to start (e.g., sandbox build+ failure).+ properties:+ error:+ type: string+ op:+ enum:+ - kernel-startup-error+ required:+ - op+ - error+ title: KernelStartupErrorNotification+ type: objectKeymapConfig:description: "Configuration for keymaps.\n\n **Keys.**\n\n - `preset`:\\ one of `\"default\"` or `\"vim\"`\n - `overrides`: a dict of keymap actions\@@ -2341,6 +2355,7 @@ components:- $ref: '#/components/schemas/MissingPackageAlertNotification'- $ref: '#/components/schemas/InstallingPackageAlertNotification'- $ref: '#/components/schemas/StartupLogsNotification'+ - $ref: '#/components/schemas/KernelStartupErrorNotification'- $ref: '#/components/schemas/VariablesNotification'- $ref: '#/components/schemas/VariableValuesNotification'- $ref: '#/components/schemas/QueryParamsSetNotification'@@ -2376,6 +2391,7 @@ components:installing-package-alert: '#/components/schemas/InstallingPackageAlertNotification'interrupted: '#/components/schemas/InterruptedNotification'kernel-ready: '#/components/schemas/KernelReadyNotification'+ kernel-startup-error: '#/components/schemas/KernelStartupErrorNotification'missing-package-alert: '#/components/schemas/MissingPackageAlertNotification'query-params-append: '#/components/schemas/QueryParamsAppendNotification'query-params-clear: '#/components/schemas/QueryParamsClearNotification'diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.tsindex 4ac68520ca..ba9c595937 100644--- a/packages/openapi/src/api.ts+++ b/packages/openapi/src/api.ts@@ -4146,6 +4146,15 @@ export interface components {resumed: boolean;ui_values: Record<string, any> | null;};+ /**+ * KernelStartupErrorNotification+ * @description Notification sent when kernel fails to start (e.g., sandbox build failure).+ */+ KernelStartupErrorNotification: {+ error: string;+ /** @enum {unknown} */+ op: "kernel-startup-error";+ };/*** KeymapConfig* @description Configuration for keymaps.@@ -4234,6 +4243,7 @@ export interface components {| components["schemas"]["MissingPackageAlertNotification"]| components["schemas"]["InstallingPackageAlertNotification"]| components["schemas"]["StartupLogsNotification"]+ | components["schemas"]["KernelStartupErrorNotification"]| components["schemas"]["VariablesNotification"]| components["schemas"]["VariableValuesNotification"]| components["schemas"]["QueryParamsSetNotification"]diff --git a/pixi.lock b/pixi.lockindex 4b5ee84fb9..3cf28900fb 100644--- a/pixi.lock+++ b/pixi.lock@@ -1132,8 +1132,8 @@ packages:timestamp: 1727801725384- pypi: ./name: marimo- version: 0.18.4- sha256: 00d04a9c700e085afe77f6f44d2455742a7247499a2022ef89fe8f9c04858e5d+ version: 0.19.0+ sha256: e3b89cad4941115582da49edd3ebfebc3505ef26c2462d9e226798d3e4d59d6crequires_dist:- click>=8.0,<9- jedi>=0.18.0@@ -1156,7 +1156,10 @@ packages:- duckdb>=1.0.0 ; extra == 'sql'- polars[pyarrow]>=1.9.0 ; extra == 'sql'- sqlglot[rs]>=26.2.0 ; extra == 'sql'+ - pyzmq>=27.1.0 ; extra == 'sandbox'+ - uv>=0.9.21 ; extra == 'sandbox'- marimo[sql] ; extra == 'recommended'+ - marimo[sandbox] ; extra == 'recommended'- altair>=5.4.0 ; extra == 'recommended'- openai>=1.55.3 ; extra == 'recommended'- ruff ; extra == 'recommended'diff --git a/pyproject.toml b/pyproject.tomlindex 9034d814a3..119fcdc494 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -87,10 +87,17 @@ sql = ["sqlglot[rs]>=26.2.0" # SQL cells parsing]+# For per-notebook sandboxed kernels+sandbox = [+ "pyzmq>=27.1.0", # IPC communication for sandbox kernels+ "uv>=0.9.21", # for sandbox management+]+# List of deps that are recommended for most users# in order to unlock all features in marimorecommended = ["marimo[sql]",+ "marimo[sandbox]", # For `marimo edit --sandbox DIRECTORY`"altair>=5.4.0", # Plotting in datasource viewer"openai>=1.55.3", # AI features"ruff", # Formattingdiff --git a/tests/_cli/test_cli.py b/tests/_cli/test_cli.pyindex 37179fef72..b0cfb351e5 100644--- a/tests/_cli/test_cli.py+++ b/tests/_cli/test_cli.py@@ -29,7 +29,6 @@ from marimo._dependencies.dependencies import DependencyManagerfrom marimo._server.templates.templates import get_versionfrom marimo._utils.platform import is_windowsfrom marimo._utils.toml import read_toml-from tests.utils import try_assert_n_timesif TYPE_CHECKING:from collections.abc import Iterator@@ -795,64 +794,14 @@ def test_cli_sandbox_edit_new_file() -> None:@pytest.mark.skipif(not HAS_UV, reason="uv is required for sandbox tests")-def test_cli_sandbox_edit_none_not_supported() -> None:+def test_cli_edit_sandbox_multi_notebook() -> None:+ # With IPC-based kernel, sandbox now works with multi-notebook serversport = _get_port()p = subprocess.Popen(["marimo","edit",- "-p",- str(port),- "--headless",- "--no-token",- "--sandbox",- ],- stderr=subprocess.PIPE,- )-- def _assert():- assert p.returncode != 0-- try_assert_n_times(5, _assert)- assert p.stderr is not None- assert "not supported" in p.stderr.read().decode()--[email protected](not HAS_UV, reason="uv is required for sandbox tests")-def test_cli_sandbox_edit_directory_not_supported() -> None:- port = _get_port()- p = subprocess.Popen(- [- "marimo",- "edit",- "../",- "-p",- str(port),- "--headless",- "--no-token","--sandbox",- ],- stderr=subprocess.PIPE,- )-- def _assert():- assert p.returncode != 0-- try_assert_n_times(5, _assert)- assert p.stderr is not None- assert "not supported" in p.stderr.read().decode()--[email protected](not HAS_UV, reason="uv is required for sandbox tests")-def test_cli_edit_none_dangerous_sandbox_allowed() -> None:- # sandbox is disallowed in a multi-notebook edit server,- # but can be overridden with --dangerous-sandbox.- port = _get_port()- p = subprocess.Popen(- [- "marimo",- "edit",- "--dangerous-sandbox","-p",str(port),"--headless",@@ -871,16 +820,15 @@ def test_cli_edit_none_dangerous_sandbox_allowed() -> None:@pytest.mark.skipif(not HAS_UV, reason="uv is required for sandbox tests")-def test_cli_edit_directory_dangerous_sandbox_allowed() -> None:- # sandbox is disallowed in a multi-notebook edit server,- # but can be overridden with --dangerous-sandbox.+def test_cli_edit_directory_sandbox() -> None:+ # With IPC-based kernel, sandbox now works with directoriesport = _get_port()p = subprocess.Popen(["marimo","edit","../",- "--dangerous-sandbox",+ "--sandbox","-p",str(port),"--headless",@@ -1237,14 +1185,13 @@ def test_cli_with_custom_pyproject_config_no_file(tmp_path: Path) -> None:# TODO: fix this, it does not get overridden in tests (maybe it is using a different marimo version that the one in CI)# assert b'"manager": "uv"' in contents- # marimo edit --dangerous-sandbox, in the directory with pyproject.toml,- # for vscode extension compatibility+ # marimo edit --sandbox, in the directory with pyproject.tomlport = _get_port()p = subprocess.Popen(["marimo","edit",- "--dangerous-sandbox",+ "--sandbox","-p",str(port),"--headless",diff --git a/tests/_cli/test_sandbox.py b/tests/_cli/test_sandbox.pyindex 79e6d2d98c..b4571cc6e0 100644--- a/tests/_cli/test_sandbox.py+++ b/tests/_cli/test_sandbox.py@@ -3,14 +3,12 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Anyfrom unittest.mock import patch-import click-import pytest-from marimo._cli.sandbox import (+ SandboxMode,_ensure_marimo_in_script_metadata,_normalize_sandbox_dependencies,construct_uv_command,- should_run_in_sandbox,+ resolve_sandbox_mode,)from marimo._utils.inline_script_metadata import PyProjectReader@@ -126,7 +124,7 @@ def test_construct_uv_cmd_marimo_edit_empty_file() -> None:additional_deps=[],)assert "--refresh" in uv_cmd- assert uv_cmd[0] == "uv"+ assert uv_cmd[0].endswith("uv")assert uv_cmd[1] == "run"@@ -141,7 +139,7 @@ def test_construct_uv_cmd_marimo_edit_file_no_sandbox(additional_deps=[],)assert "--refresh" in uv_cmd- assert uv_cmd[0] == "uv"+ assert uv_cmd[0].endswith("uv")assert uv_cmd[1] == "run"@@ -157,7 +155,7 @@ def test_construct_uv_cmd_marimo_edit_sandboxed_file(additional_deps=[],)assert "--refresh" not in uv_cmd- assert uv_cmd[0] == "uv"+ assert uv_cmd[0].endswith("uv")assert uv_cmd[1] == "run"@@ -413,8 +411,8 @@ import marimoassert "numpy" in requirements-def test_should_run_in_sandbox_user_confirms(tmp_path: Path) -> None:- """Test that should_run_in_sandbox returns True when user types 'y'."""+def test_resolve_sandbox_mode_user_confirms(tmp_path: Path) -> None:+ """Test that resolve_sandbox_mode returns SandboxMode.SINGLE when user types 'y'."""# Create a file with dependenciesscript_path = tmp_path / "test.py"script_path.write_text(@@ -435,55 +433,70 @@ import marimowith patch("marimo._cli.sandbox.sys.stdin.isatty", return_value=True):- result = should_run_in_sandbox(+ result = resolve_sandbox_mode(sandbox=None,- dangerous_sandbox=None,name=str(script_path),)- assert result+ assert result is SandboxMode.SINGLE-def test_should_run_in_sandbox_explicit_flag() -> None:- """Test that should_run_in_sandbox returns True when sandbox=True."""- result = should_run_in_sandbox(+def test_resolve_sandbox_mode_explicit_single() -> None:+ """Test that resolve_sandbox_mode returns SandboxMode.SINGLE for single file with sandbox=True."""+ result = resolve_sandbox_mode(sandbox=True,- dangerous_sandbox=None,name="test.py",)- assert result+ assert result is SandboxMode.SINGLE-def test_should_run_in_sandbox_explicit_false() -> None:- """Test that should_run_in_sandbox returns False when sandbox=False."""- result = should_run_in_sandbox(+def test_resolve_sandbox_mode_explicit_false() -> None:+ """Test that resolve_sandbox_mode returns None when sandbox=False."""+ result = resolve_sandbox_mode(sandbox=False,- dangerous_sandbox=None,name="test.py",)- assert not result+ assert result is None-def test_should_run_in_sandbox_dangerous_sandbox(tmp_path: Path) -> None:- """Test that dangerous_sandbox allows sandbox for directories."""+def test_resolve_sandbox_mode_directory(tmp_path: Path) -> None:+ """Test that resolve_sandbox_mode returns SandboxMode.MULTI for directories."""dir_path = tmp_path / "notebooks"dir_path.mkdir()- # Without dangerous_sandbox, should raise an error- with pytest.raises(click.UsageError):- should_run_in_sandbox(- sandbox=True,- dangerous_sandbox=False,- name=str(dir_path),- )+ # Directory with sandbox=True returns SandboxMode.MULTI+ result = resolve_sandbox_mode(+ sandbox=True,+ name=str(dir_path),+ )+ assert result is SandboxMode.MULTI- # With dangerous_sandbox, should work- with patch("click.echo"):- result = should_run_in_sandbox(- sandbox=True,- dangerous_sandbox=True,- name=str(dir_path),- )- assert result++def test_resolve_sandbox_mode_all_cases(tmp_path: Path) -> None:+ """Test resolve_sandbox_mode for all cases."""+ dir_path = tmp_path / "notebooks"+ dir_path.mkdir()+ file_path = tmp_path / "notebook.py"+ file_path.write_text("# test")++ # sandbox=False always returns None+ assert resolve_sandbox_mode(sandbox=False, name=None) is None+ assert resolve_sandbox_mode(sandbox=False, name=str(dir_path)) is None+ assert resolve_sandbox_mode(sandbox=False, name=str(file_path)) is None++ # sandbox=True with None (current dir) -> SandboxMode.MULTI+ assert resolve_sandbox_mode(sandbox=True, name=None) is SandboxMode.MULTI++ # sandbox=True with directory -> SandboxMode.MULTI+ assert (+ resolve_sandbox_mode(sandbox=True, name=str(dir_path))+ is SandboxMode.MULTI+ )++ # sandbox=True with file -> SandboxMode.SINGLE+ assert (+ resolve_sandbox_mode(sandbox=True, name=str(file_path))+ is SandboxMode.SINGLE+ )def test_construct_uv_cmd_without_python_version(tmp_path: Path) -> None:@@ -559,3 +572,102 @@ app = marimo.App()_ensure_marimo_in_script_metadata(str(script_path))assert script_path.read_text() == original+++# Tests for IPC sandbox functions+++def test_ipc_kernel_deps_constant() -> None:+ """Test IPC_KERNEL_DEPS constant contains expected deps."""+ from marimo._cli.sandbox import IPC_KERNEL_DEPS++ assert "pyzmq" in IPC_KERNEL_DEPS+++def test_get_sandbox_requirements_adds_additional_deps(tmp_path: Path) -> None:+ """Test that additional deps are added when not present."""+ from marimo._cli.sandbox import get_sandbox_requirements++ script_path = tmp_path / "test.py"+ script_path.write_text(+ """# /// script+# dependencies = ["numpy"]+# ///+import marimo+"""+ )++ with patch("marimo._cli.sandbox.is_editable", return_value=False):+ reqs = get_sandbox_requirements(+ str(script_path),+ additional_deps=["pyzmq", "msgspec"],+ )++ assert any("numpy" in r for r in reqs)+ assert "pyzmq" in reqs+ assert "msgspec" in reqs+++def test_get_sandbox_requirements_no_duplicate_deps(tmp_path: Path) -> None:+ """Test that additional deps aren't duplicated if already present."""+ from marimo._cli.sandbox import get_sandbox_requirements++ script_path = tmp_path / "test.py"+ script_path.write_text(+ """# /// script+# dependencies = ["numpy", "pyzmq>=25.0"]+# ///+import marimo+"""+ )++ with patch("marimo._cli.sandbox.is_editable", return_value=False):+ reqs = get_sandbox_requirements(+ str(script_path),+ additional_deps=["pyzmq", "msgspec"],+ )++ # Should have only one pyzmq entry (uv resolves versions, so it may be ==X.Y.Z)+ pyzmq_entries = [r for r in reqs if "pyzmq" in r.lower()]+ assert len(pyzmq_entries) == 1+ assert "msgspec" in reqs+++def test_get_sandbox_requirements_none_filename() -> None:+ """Test get_sandbox_requirements with None filename."""+ from marimo._cli.sandbox import get_sandbox_requirements++ with patch("marimo._cli.sandbox.is_editable", return_value=False):+ reqs = get_sandbox_requirements(None, additional_deps=["pyzmq"])++ # Should have marimo and additional deps+ assert any("marimo" in r for r in reqs)+ assert "pyzmq" in reqs+++def test_cleanup_sandbox_dir_removes_directory(tmp_path: Path) -> None:+ """Test that cleanup_sandbox_dir removes the directory."""+ from marimo._cli.sandbox import cleanup_sandbox_dir++ sandbox_dir = tmp_path / "sandbox"+ sandbox_dir.mkdir()+ (sandbox_dir / "file.txt").write_text("test")++ cleanup_sandbox_dir(str(sandbox_dir))++ assert not sandbox_dir.exists()+++def test_cleanup_sandbox_dir_handles_none() -> None:+ """Test that cleanup_sandbox_dir handles None gracefully."""+ from marimo._cli.sandbox import cleanup_sandbox_dir++ cleanup_sandbox_dir(None) # Should not raise+++def test_cleanup_sandbox_dir_handles_nonexistent(tmp_path: Path) -> None:+ """Test that cleanup_sandbox_dir handles nonexistent directory."""+ from marimo._cli.sandbox import cleanup_sandbox_dir++ nonexistent = str(tmp_path / "does_not_exist")+ cleanup_sandbox_dir(nonexistent) # Should not raisediff --git a/tests/_server/api/endpoints/test_assets.py b/tests/_server/api/endpoints/test_assets.pyindex dc5be8b8f9..a1fc6a83ad 100644--- a/tests/_server/api/endpoints/test_assets.py+++ b/tests/_server/api/endpoints/test_assets.py@@ -295,3 +295,15 @@ def test_index_prefers_local_file_over_asset_url(client: TestClient) -> None:# Reset asset_urlclient.app.state.asset_url = None+++def test_index_includes_notebook_key_in_mount_config(+ client: TestClient,+) -> None:+ """Test that index response includes notebook in mount config."""+ response = client.get("/", headers=token_header())+ assert response.status_code == 200++ # Verify notebook key is present in mount config by checking HTML content+ # The mount config is injected as JSON in the HTML+ assert '"notebook":' in response.text or "'notebook':" in response.textdiff --git a/tests/_server/api/endpoints/ws/test_ws_formatter.py b/tests/_server/api/endpoints/ws/test_ws_formatter.pynew file mode 100644index 0000000000..64dc2a768a--- /dev/null+++ b/tests/_server/api/endpoints/ws/test_ws_formatter.py@@ -0,0 +1,148 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import json++from marimo._messaging.notification import (+ AlertNotification,+ KernelStartupErrorNotification,+)+from marimo._server.api.endpoints.ws.ws_formatter import (+ format_wire_message,+ serialize_notification_for_websocket,+)+++class TestFormatWireMessage:+ """Tests for format_wire_message function."""++ def test_basic_formatting(self) -> None:+ """Test basic wire message formatting."""+ op = "test-op"+ data = b'{"key": "value"}'+ result = format_wire_message(op, data)++ parsed = json.loads(result)+ assert parsed["op"] == "test-op"+ assert parsed["data"] == {"key": "value"}++ def test_with_nested_data(self) -> None:+ """Test formatting with nested JSON data."""+ op = "cell-op"+ data = b'{"cell_id": "abc123", "output": {"type": "text", "data": "hello"}}'+ result = format_wire_message(op, data)++ parsed = json.loads(result)+ assert parsed["op"] == "cell-op"+ assert parsed["data"]["cell_id"] == "abc123"+ assert parsed["data"]["output"]["type"] == "text"++ def test_with_special_characters_in_data(self) -> None:+ """Test formatting with special characters in data."""+ op = "alert"+ data = b'{"message": "Hello\\nWorld\\twith\\ttabs"}'+ result = format_wire_message(op, data)++ parsed = json.loads(result)+ assert parsed["op"] == "alert"+ assert parsed["data"]["message"] == "Hello\nWorld\twith\ttabs"++ def test_with_unicode_data(self) -> None:+ """Test formatting with unicode characters."""+ op = "notification"+ data = '{"text": "Hello 世界 🌍"}'.encode()+ result = format_wire_message(op, data)++ parsed = json.loads(result)+ assert parsed["op"] == "notification"+ assert parsed["data"]["text"] == "Hello 世界 🌍"++ def test_with_empty_object(self) -> None:+ """Test formatting with empty object data."""+ op = "empty"+ data = b"{}"+ result = format_wire_message(op, data)++ parsed = json.loads(result)+ assert parsed["op"] == "empty"+ assert parsed["data"] == {}+++class TestSerializeNotificationForWebsocket:+ """Tests for serialize_notification_for_websocket function."""++ def test_kernel_startup_error_notification(self) -> None:+ """Test serializing KernelStartupErrorNotification."""+ notification = KernelStartupErrorNotification(+ error="Failed to start kernel: module not found"+ )+ result = serialize_notification_for_websocket(notification)++ parsed = json.loads(result)+ assert parsed["op"] == "kernel-startup-error"+ assert (+ parsed["data"]["error"]+ == "Failed to start kernel: module not found"+ )++ def test_alert_notification(self) -> None:+ """Test serializing AlertNotification."""+ notification = AlertNotification(+ title="Test Alert",+ description="This is a test alert message",+ )+ result = serialize_notification_for_websocket(notification)++ parsed = json.loads(result)+ assert parsed["op"] == "alert"+ assert parsed["data"]["title"] == "Test Alert"+ assert parsed["data"]["description"] == "This is a test alert message"++ def test_alert_notification_with_variant(self) -> None:+ """Test serializing AlertNotification with danger variant."""+ notification = AlertNotification(+ title="Error",+ description="Something went wrong",+ variant="danger",+ )+ result = serialize_notification_for_websocket(notification)++ parsed = json.loads(result)+ assert parsed["op"] == "alert"+ assert parsed["data"]["variant"] == "danger"++ def test_produces_valid_json(self) -> None:+ """Test that output is always valid JSON."""+ notification = KernelStartupErrorNotification(+ error='Error with "quotes" and special chars: <>&'+ )+ result = serialize_notification_for_websocket(notification)++ # Should not raise+ parsed = json.loads(result)+ assert "op" in parsed+ assert "data" in parsed+++class TestIntegration:+ """Integration tests for the ws_formatter module."""++ def test_roundtrip_matches_expected_wire_format(self) -> None:+ """Test that the wire format matches what the frontend expects.++ The frontend expects messages in the format:+ {"op": "operation-name", "data": {...notification fields...}}+ """+ notification = KernelStartupErrorNotification(error="test error")+ result = serialize_notification_for_websocket(notification)++ parsed = json.loads(result)++ # Verify structure matches expected wire format+ assert set(parsed.keys()) == {"op", "data"}+ assert isinstance(parsed["op"], str)+ assert isinstance(parsed["data"], dict)++ # Verify op matches notification name+ assert parsed["op"] == notification.name+ assert parsed["op"] == "kernel-startup-error"diff --git a/tests/_session/extensions/test_extensions.py b/tests/_session/extensions/test_extensions.pyindex 746d447aa7..e264a405e2 100644--- a/tests/_session/extensions/test_extensions.py+++ b/tests/_session/extensions/test_extensions.py@@ -143,6 +143,14 @@ class TestNotificationListenerExtension:@pytest.fixturedef queue_manager(self):manager = Mock()+ # For original edit mode, stream_queue is None+ manager.stream_queue = None+ return manager++ @pytest.fixture+ def queue_manager_with_stream(self):+ manager = Mock()+ # For run mode and IPC mode, stream_queue is setmanager.stream_queue = asyncio.Queue()return manager@@ -168,29 +176,29 @@ class TestNotificationListenerExtension:assert extension.distributor is Nonedef test_uses_correct_distributor_type(- self, kernel_manager, queue_manager+ self, kernel_manager, queue_manager, queue_manager_with_stream) -> None:- """Test that correct distributor type is used based on mode."""+ """Test that correct distributor type is used based on stream_queue."""from marimo._utils.distributor import (ConnectionDistributor,QueueDistributor,)+ # When stream_queue is None, use ConnectionDistributor (edit mode)extension = NotificationListenerExtension(kernel_manager, queue_manager)-- # EDIT mode uses ConnectionDistributor- kernel_manager.mode = SessionMode.EDITdistributor = extension._create_distributor(kernel_manager, queue_manager)assert isinstance(distributor, ConnectionDistributor)- # RUN mode uses QueueDistributor- kernel_manager.mode = SessionMode.RUN- distributor = extension._create_distributor(- kernel_manager, queue_manager+ # When stream_queue is present, use QueueDistributor (run mode or IPC)+ extension2 = NotificationListenerExtension(+ kernel_manager, queue_manager_with_stream+ )+ distributor = extension2._create_distributor(+ kernel_manager, queue_manager_with_stream)assert isinstance(distributor, QueueDistributor)diff --git a/tests/_session/managers/__init__.py b/tests/_session/managers/__init__.pynew file mode 100644index 0000000000..fe2d2e388e--- /dev/null+++ b/tests/_session/managers/__init__.py@@ -0,0 +1 @@+# Copyright 2026 Marimo. All rights reserved.diff --git a/tests/_session/managers/test_ipc.py b/tests/_session/managers/test_ipc.pynew file mode 100644index 0000000000..5bbf8c5ca7--- /dev/null+++ b/tests/_session/managers/test_ipc.py@@ -0,0 +1,53 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import pytest++from marimo._dependencies.dependencies import DependencyManager++HAS_ZMQ = DependencyManager.zmq.has()++[email protected](not HAS_ZMQ, reason="pyzmq not installed")+class TestIPCQueueManagerImpl:+ def test_from_ipc_factory(self) -> None:+ """Test that IPCQueueManagerImpl.from_ipc() creates a valid instance."""+ from marimo._ipc import QueueManager as IPCQueueManager+ from marimo._session.managers.ipc import IPCQueueManagerImpl++ # Create the underlying IPC queue manager+ ipc_queue_manager, connection_info = IPCQueueManager.create()++ # Create wrapper using factory method+ wrapper = IPCQueueManagerImpl.from_ipc(ipc_queue_manager)++ # Verify wrapper has access to queues+ assert wrapper.control_queue is not None+ assert wrapper.completion_queue is not None+ assert wrapper.input_queue is not None+ assert wrapper.stream_queue is not None+ assert wrapper.set_ui_element_queue is not None++ # connection_info should be valid+ assert connection_info is not None++ # Clean up+ wrapper.close_queues()++ def test_from_ipc_equals_direct_init(self) -> None:+ """Test that from_ipc() and __init__() produce equivalent results."""+ from marimo._ipc import QueueManager as IPCQueueManager+ from marimo._session.managers.ipc import IPCQueueManagerImpl++ ipc_queue_manager, _ = IPCQueueManager.create()++ # Create using factory+ via_factory = IPCQueueManagerImpl.from_ipc(ipc_queue_manager)+ # Create using __init__ directly+ via_init = IPCQueueManagerImpl(ipc_queue_manager)++ # Both should reference the same underlying IPC manager+ assert via_factory._ipc is via_init._ipc++ # Clean up+ via_factory.close_queues()