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: CLI error UX improvements (#8375)

Péter Gyarmatia9365cf53c3f
diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.py
index 2bcdbfe8a9..7c96e1b7dc 100644
--- a/marimo/_cli/cli.py
+++ b/marimo/_cli/cli.py
@@ -21,10 +21,15 @@ from marimo._cli.config.commands import config
from marimo._cli.convert.commands import convert
from marimo._cli.development.commands import development
from marimo._cli.envinfo import get_system_info
+from marimo._cli.errors import (
+ MarimoCLIMissingDependencyError,
+ MarimoCLIRuntimeError,
+)
from marimo._cli.export.commands import export
from marimo._cli.files.file_path import validate_name
from marimo._cli.help_formatter import ColoredGroup
from marimo._cli.parse_args import parse_args
+from marimo._cli.parser_ux import show_compact_usage_error
from marimo._cli.print import bright_green, light_blue, red
from marimo._cli.run_docker import (
prompt_run_in_docker_container,
@@ -58,17 +63,7 @@ from marimo._version import __version__
def helpful_usage_error(self: Any, file: Any = None) -> None:
- if file is None:
- file = click.get_text_stream("stderr")
- color = None
- click.echo(
- red("Error") + f": {self.format_message()}\n",
- file=file,
- color=color,
- )
- if self.ctx is not None:
- color = self.ctx.color
- click.echo(self.ctx.get_help(), file=file, color=color)
+ show_compact_usage_error(self, file=file)
click.exceptions.UsageError.show = helpful_usage_error # type: ignore
@@ -465,10 +460,6 @@ def edit(
return
GLOBAL_SETTINGS.PROFILE_DIR = profile_dir
- if not skip_update_check and os.getenv("MARIMO_SKIP_UPDATE_CHECK") != "1":
- GLOBAL_SETTINGS.CHECK_STATUS_UPDATE = True
- # Check for version updates
- check_for_updates(print_latest_version)
if name is not None:
# Validate name, or download from URL
@@ -521,10 +512,9 @@ def edit(
from marimo._dependencies.dependencies import DependencyManager
if not DependencyManager.zmq.has():
- raise click.ClickException(
- "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"
+ raise MarimoCLIMissingDependencyError(
+ "pyzmq is required when running the marimo edit server on a directory with --sandbox.",
+ "marimo[sandbox]",
)
# Enable script metadata management for sandboxed notebooks
@@ -537,16 +527,26 @@ def edit(
shm_available, shm_error = check_shared_memory_available()
if not shm_available:
- _loggers.marimo_logger().error(
- f"marimo failed to start: marimo edit requires shared memory support for multiprocessing.\n\n"
+ shm_mount_example = "--shm-size=256m or -v /dev/shm:/dev/shm"
+ docker_shm_line = " ".join(
+ [
+ " - If running in Docker, ensure /dev/shm is mounted with sufficient size",
+ f"(e.g., {shm_mount_example})",
+ ]
+ )
+ raise MarimoCLIRuntimeError(
+ "marimo edit requires shared memory support for multiprocessing.\n\n"
f"{shm_error}\n\n"
"Possible solutions:\n"
- " - If running in Docker, ensure /dev/shm is mounted with sufficient size\n"
- " (e.g., --shm-size=256m or -v /dev/shm:/dev/shm)\n"
+ f"{docker_shm_line}\n"
" - If /dev/shm is full, clear unused shared memory segments\n"
" - Use 'marimo run' instead if you only need to view notebooks"
)
- sys.exit(1)
+
+ if not skip_update_check and os.getenv("MARIMO_SKIP_UPDATE_CHECK") != "1":
+ GLOBAL_SETTINGS.CHECK_STATUS_UPDATE = True
+ # Check for version updates after preflight checks pass.
+ check_for_updates(print_latest_version)
start(
file_router=AppFileRouter.infer(name),
@@ -1155,10 +1155,9 @@ def run(
from marimo._dependencies.dependencies import DependencyManager
if not DependencyManager.zmq.has():
- raise click.ClickException(
- "pyzmq is required when running a gallery with --sandbox.\n"
- "Install it with: pip install 'marimo[sandbox]'\n"
- "Or: pip install pyzmq"
+ raise MarimoCLIMissingDependencyError(
+ "pyzmq is required when running a gallery with --sandbox.",
+ "marimo[sandbox]",
)
file_router = _create_run_file_router(validated_paths, watch=watch)
@@ -1326,7 +1325,7 @@ def env() -> None:
def shell_completion() -> None:
shell = os.environ.get("SHELL", "")
if not shell:
- raise click.UsageError(
+ raise MarimoCLIRuntimeError(
"Could not determine shell. Please set $SHELL environment variable.",
)
@@ -1351,10 +1350,9 @@ def shell_completion() -> None:
if shell_name not in commands:
supported = ", ".join(commands.keys())
- raise click.UsageError(
+ raise MarimoCLIRuntimeError(
f"Unsupported shell: {shell_name} (from $SHELL). Supported shells: {supported}",
)
- return
cmd, rc_file = commands[shell_name]
click.secho("Run this command to enable completions:", fg="green")
diff --git a/marimo/_cli/convert/commands.py b/marimo/_cli/convert/commands.py
index 1f5be5c302..7bb2fa81c7 100644
--- a/marimo/_cli/convert/commands.py
+++ b/marimo/_cli/convert/commands.py
@@ -7,12 +7,20 @@ from typing import Optional
import click
from marimo._cli.convert.utils import load_external_file
+from marimo._cli.errors import MarimoCLIMissingDependencyError
from marimo._cli.print import echo
from marimo._cli.utils import prompt_to_overwrite
from marimo._convert.converters import MarimoConvert
from marimo._utils.paths import maybe_make_dirs
+def _build_rerun_command(filename: str, output: Path | None) -> str:
+ command = f"marimo convert {filename}"
+ if output is not None:
+ command = f"{command} -o {output}"
+ return command
+
+
@click.argument("filename", required=True)
@click.option(
"-o",
@@ -115,21 +123,21 @@ def convert(
e.__cause__
and getattr(e.__cause__, "name", None) == "jupytext"
):
- from marimo._cli.print import green
-
- raise click.ClickException(
- f"{e}\n\n"
- f" {green('Tip:')} If you're using uv, run:\n\n"
- f" uvx --with=jupytext marimo convert {filename}"
+ rerun_command = _build_rerun_command(filename, output)
+ raise MarimoCLIMissingDependencyError(
+ str(e),
+ "jupytext",
+ followup_commands=rerun_command,
+ followup_label="Then rerun:",
) from e
raise
if output:
- output_path = Path(output)
+ output_path = output
if prompt_to_overwrite(output_path):
# Make dirs if needed
- maybe_make_dirs(output)
- Path(output).write_text(notebook, encoding="utf-8")
+ maybe_make_dirs(output_path)
+ output_path.write_text(notebook, encoding="utf-8")
echo(f"Converted notebook saved to {output}")
else:
echo(notebook)
diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.py
index f6abf3ad87..5c89498bae 100644
--- a/marimo/_cli/development/commands.py
+++ b/marimo/_cli/development/commands.py
@@ -10,6 +10,10 @@ from typing import TYPE_CHECKING, Any
import click
+from marimo._cli.errors import (
+ MarimoCLIMissingDependencyError,
+ MarimoCLIRuntimeError,
+)
from marimo._cli.help_formatter import ColoredCommand, ColoredGroup
from marimo._data.models import DataType
from marimo._messaging.errors import Error as MarimoError
@@ -415,8 +419,12 @@ def inline_packages(name: Path) -> None:
# Validate uv is installed
if not DependencyManager.which("uv"):
- raise click.UsageError(
- "uv is not installed. See https://docs.astral.sh/uv/getting-started/installation/"
+ raise MarimoCLIMissingDependencyError(
+ "uv is not installed.",
+ "uv",
+ additional_tip=(
+ "See https://docs.astral.sh/uv/getting-started/installation/"
+ ),
)
# Validate the file exists
@@ -666,8 +674,7 @@ def preview(file_path: Path, port: int, host: str, headless: bool) -> None:
uvicorn.run(app, host=host, port=port, log_level="error")
except Exception as e:
- click.echo(f"Error creating preview: {e}", err=True)
- raise click.Abort() from e
+ raise MarimoCLIRuntimeError(f"Error creating preview: {e}") from e
development.add_command(inline_packages)
diff --git a/marimo/_cli/errors.py b/marimo/_cli/errors.py
new file mode 100644
index 0000000000..e8f7e35927
--- /dev/null
+++ b/marimo/_cli/errors.py
@@ -0,0 +1,112 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import Any
+
+import click
+
+from marimo._cli.install_hints import get_install_commands
+from marimo._cli.print import bold, green, muted, red
+
+
+class MarimoCLIError(click.ClickException):
+ """Base class for marimo CLI errors."""
+
+ def show(self, file: Any = None) -> None:
+ if file is None:
+ file = click.get_text_stream("stderr")
+
+ ctx = getattr(self, "ctx", None)
+ color = ctx.color if ctx is not None else None
+ click.echo(
+ f"{red('Error', bold=True)}: {self.format_message()}",
+ file=file,
+ color=color,
+ )
+
+
+class MarimoCLIRuntimeError(MarimoCLIError):
+ """Raised for runtime or environment setup failures."""
+
+
+class MarimoCLIMissingDependencyError(MarimoCLIError):
+ """Raised when a required dependency is unavailable."""
+
+ def __init__(
+ self,
+ message: str,
+ packages: str | list[str] | tuple[str, ...],
+ *,
+ additional_tip: str | None = None,
+ followup_commands: str | list[str] | tuple[str, ...] | None = None,
+ followup_label: str = "Then run:",
+ ) -> None:
+ """Build a dependency error message with install and follow-up hints."""
+ package_spec: str | list[str]
+ if isinstance(packages, str):
+ package_spec = packages
+ else:
+ package_spec = list(packages)
+
+ commands = get_install_commands(package_spec)
+ lines = [message]
+
+ if commands:
+ primary_install = commands[0]
+ lines.extend(
+ [
+ "",
+ f" {green('Tip:')} Install with:",
+ "",
+ f" {primary_install}",
+ ]
+ )
+ if len(commands) > 1:
+ pip_install = commands[1]
+ lines.extend(
+ [
+ "",
+ f" {muted('Or with pip:')}",
+ "",
+ f" {pip_install}",
+ ]
+ )
+
+ followup: list[str]
+ if followup_commands is None:
+ followup = []
+ elif isinstance(followup_commands, str):
+ command = followup_commands.strip()
+ followup = [command] if command else []
+ else:
+ followup = [
+ command.strip()
+ for command in followup_commands
+ if command.strip()
+ ]
+
+ if followup:
+ primary_followup = followup[0]
+ lines.extend(
+ [
+ "",
+ f" {green('Tip:')} {followup_label.strip()}",
+ "",
+ f" {bold(primary_followup)}",
+ ]
+ )
+ if len(followup) > 1:
+ fallback_followup = followup[1]
+ lines.extend(
+ [
+ "",
+ f" {muted('Or with fallback:')}",
+ "",
+ f" {bold(fallback_followup)}",
+ ]
+ )
+
+ if additional_tip:
+ lines.extend(["", f" {additional_tip.strip()}"])
+
+ super().__init__("\n".join(lines))
diff --git a/marimo/_cli/export/commands.py b/marimo/_cli/export/commands.py
index 7a525aeaf8..49e41693ff 100644
--- a/marimo/_cli/export/commands.py
+++ b/marimo/_cli/export/commands.py
@@ -7,9 +7,11 @@ from typing import Callable, Literal, Optional
import click
+from marimo._cli.errors import MarimoCLIMissingDependencyError
from marimo._cli.export.cloudflare import create_cloudflare_files
from marimo._cli.export.thumbnail import thumbnail
from marimo._cli.help_formatter import ColoredCommand, ColoredGroup
+from marimo._cli.install_hints import get_playwright_chromium_setup_commands
from marimo._cli.parse_args import parse_args
from marimo._cli.print import (
echo,
@@ -486,9 +488,13 @@ def ipynb(
)
return
- DependencyManager.nbformat.require(
- why="to convert marimo notebooks to ipynb"
- )
+ try:
+ DependencyManager.nbformat.require(
+ why="to convert marimo notebooks to ipynb"
+ )
+ except ModuleNotFoundError as e:
+ package = getattr(e, "name", None) or "nbformat"
+ raise MarimoCLIMissingDependencyError(str(e), package) from None
def export_callback(file_path: MarimoPath) -> ExportResult:
if include_outputs:
@@ -617,14 +623,15 @@ def pdf(
DependencyManager.nbconvert,
)
except ManyModulesNotFoundError as e:
- from marimo._cli.print import bold
-
- pkgs = " ".join(e.package_names)
- raise click.ClickException(
- f"{e}\n\n"
- f" {green('Tip:')} Install with:\n\n"
- f" pip install {pkgs}\n\n"
- f" or rerun with {bold(f'marimo export pdf {name} --output {output} --sandbox')} (requires uv)"
+ sandbox_rerun_command = (
+ f"marimo export pdf {name} --output {output} --sandbox"
+ )
+ raise MarimoCLIMissingDependencyError(
+ str(e),
+ e.package_names,
+ followup_commands=sandbox_rerun_command,
+ followup_label="Alternative:",
+ additional_tip="Requires uv.",
) from None
cli_args = parse_args(args) if include_outputs else {}
@@ -645,12 +652,10 @@ def pdf(
)
except ModuleNotFoundError as e:
if getattr(e, "name", None) == "playwright":
- raise click.ClickException(
- "Playwright is required for WebPDF export.\n\n"
- f" {green('Tip:')} Install webpdf dependencies with:\n\n"
- " pip install 'nbconvert[webpdf]'\n\n"
- " and install Chromium with:\n\n"
- " python -m playwright install chromium"
+ raise MarimoCLIMissingDependencyError(
+ "Playwright is required for WebPDF export.",
+ "nbconvert[webpdf]",
+ followup_commands=get_playwright_chromium_setup_commands(),
) from None
raise
except Exception as e:
diff --git a/marimo/_cli/export/thumbnail.py b/marimo/_cli/export/thumbnail.py
index 109f320f8e..22a2148eb7 100644
--- a/marimo/_cli/export/thumbnail.py
+++ b/marimo/_cli/export/thumbnail.py
@@ -15,6 +15,8 @@ from typing import TYPE_CHECKING, Any, Optional
import click
+from marimo._cli.errors import MarimoCLIMissingDependencyError
+from marimo._cli.install_hints import get_playwright_chromium_setup_commands
from marimo._cli.parse_args import parse_args
from marimo._cli.print import echo, green, red, yellow
from marimo._dependencies.dependencies import DependencyManager
@@ -369,21 +371,20 @@ async def _generate_thumbnails(
)
except ModuleNotFoundError as e:
if getattr(e, "name", None) == "playwright":
- raise click.ClickException(
- "Playwright is required to generate thumbnails.\n\n"
- " Tip: Install dependencies with:\n\n"
- " pip install 'nbconvert[webpdf]'\n\n"
- " and install Chromium with:\n\n"
- " python -m playwright install chromium"
+ raise MarimoCLIMissingDependencyError(
+ "Playwright is required to generate thumbnails.",
+ "nbconvert[webpdf]",
+ followup_commands=get_playwright_chromium_setup_commands(),
) from None
raise
use_per_notebook_sandbox = sandbox_mode is SandboxMode.MULTI
if use_per_notebook_sandbox and not DependencyManager.which("uv"):
- raise click.ClickException(
- "uv is required for --sandbox thumbnail generation.\n\n"
- " Tip: Install uv from https://github.com/astral-sh/uv"
+ raise MarimoCLIMissingDependencyError(
+ "uv is required for --sandbox thumbnail generation.",
+ "uv",
+ additional_tip="Install uv from https://github.com/astral-sh/uv",
)
static_dir = marimo_package_path() / "_static"
@@ -625,12 +626,10 @@ def thumbnail(
DependencyManager.playwright.require("for thumbnail generation")
except ModuleNotFoundError as e:
if getattr(e, "name", None) == "playwright":
- raise click.ClickException(
- "Playwright is required for thumbnail generation.\n\n"
- " Tip: Install with:\n\n"
- " python -m pip install playwright\n\n"
- " and install Chromium with:\n\n"
- " python -m playwright install chromium"
+ raise MarimoCLIMissingDependencyError(
+ "Playwright is required for thumbnail generation.",
+ "playwright",
+ followup_commands=get_playwright_chromium_setup_commands(),
) from None
raise
diff --git a/marimo/_cli/help_formatter.py b/marimo/_cli/help_formatter.py
index 0e3df3312a..22653512b8 100644
--- a/marimo/_cli/help_formatter.py
+++ b/marimo/_cli/help_formatter.py
@@ -9,13 +9,65 @@
from __future__ import annotations
import click
+from click.utils import make_str
from marimo._cli.print import bright_green, light_blue
+from marimo._cli.suggestions import suggest_commands, suggest_short_options
+
+
+def _split_option_token(token: str) -> tuple[str, str]:
+ """Split option-like tokens without depending on click's private parser."""
+ first = token[:1]
+ if first.isalnum():
+ return "", token
+ if token[1:2] == first:
+ return token[:2], token[2:]
+ return first, token[1:]
+
+
+def _collect_short_options(
+ command: click.Command, ctx: click.Context
+) -> list[str]:
+ """Collect all short flag names (e.g. -p) declared on a command."""
+ options: set[str] = set()
+ for param in command.get_params(ctx):
+ if not isinstance(param, click.Option):
+ continue
+ for option in [*param.opts, *param.secondary_opts]:
+ if option.startswith("-") and not option.startswith("--"):
+ options.add(option)
+ return sorted(options)
+
+
+def _augment_short_option_error(
+ command: click.Command,
+ ctx: click.Context,
+ error: click.NoSuchOption,
+) -> None:
+ """Populate click's possibilities for misspelled short flags."""
+ if error.possibilities:
+ return
+ if not error.option_name.startswith("-") or error.option_name.startswith(
+ "--"
+ ):
+ return
+
+ short_options = _collect_short_options(command, ctx)
+ suggestions = suggest_short_options(error.option_name, short_options)
+ if suggestions:
+ error.possibilities = suggestions
class ColoredCommand(click.Command):
"""Click Command with colored help output (cargo-style)."""
+ def parse_args(self, ctx: click.Context, args: list[str]) -> list[str]:
+ try:
+ return super().parse_args(ctx, args)
+ except click.NoSuchOption as error:
+ _augment_short_option_error(self, ctx, error)
+ raise
+
def format_usage(
self, ctx: click.Context, formatter: click.HelpFormatter
) -> None:
@@ -46,6 +98,51 @@ class ColoredGroup(click.Group):
command_class = ColoredCommand
+ def parse_args(self, ctx: click.Context, args: list[str]) -> list[str]:
+ try:
+ return super().parse_args(ctx, args)
+ except click.NoSuchOption as error:
+ _augment_short_option_error(self, ctx, error)
+ raise
+
+ def resolve_command(
+ self, ctx: click.Context, args: list[str]
+ ) -> tuple[str | None, click.Command | None, list[str]]:
+ """Resolve subcommands and emit close-match suggestions on typos."""
+ cmd_name = make_str(args[0])
+ original_cmd_name = cmd_name
+
+ cmd = self.get_command(ctx, cmd_name)
+ if cmd is None and ctx.token_normalize_func is not None:
+ cmd_name = ctx.token_normalize_func(cmd_name)
+ cmd = self.get_command(ctx, cmd_name)
+
+ if cmd is None and not ctx.resilient_parsing:
+ if _split_option_token(cmd_name)[0]:
+ self.parse_args(ctx, args)
+
+ command_names: list[str] = []
+ for name in self.list_commands(ctx):
+ command = self.get_command(ctx, name)
+ if command is None or command.hidden:
+ continue
+ command_names.append(name)
+ suggestions = suggest_commands(original_cmd_name, command_names)
+ if len(suggestions) == 1:
+ ctx.fail(
+ f"unrecognized command {original_cmd_name!r}\n\n"
+ f" tip: a similar command exists: {suggestions[0]!r}"
+ )
+ if len(suggestions) > 1:
+ joined = ", ".join(repr(item) for item in suggestions)
+ ctx.fail(
+ f"unrecognized command {original_cmd_name!r}\n\n"
+ f" tip: some similar commands exist: {joined}"
+ )
+ ctx.fail(f"unrecognized command {original_cmd_name!r}")
+
+ return cmd_name if cmd else None, cmd, args[1:]
+
def format_usage(
self, ctx: click.Context, formatter: click.HelpFormatter
) -> None:
diff --git a/marimo/_cli/install_hints.py b/marimo/_cli/install_hints.py
new file mode 100644
index 0000000000..c929358a78
--- /dev/null
+++ b/marimo/_cli/install_hints.py
@@ -0,0 +1,182 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import os
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Final
+
+from marimo._config.packages import PackageManagerKind, infer_package_manager
+from marimo._utils.platform import is_windows
+
+
+@dataclass(frozen=True)
+class CommandRule:
+ manager: PackageManagerKind
+ context: str
+ template: str
+
+
+_INSTALL_COMMAND_RULES: Final[tuple[CommandRule, ...]] = (
+ CommandRule("uv", "project", "uv add {packages}"),
+ CommandRule("uv", "any", "uv pip install {packages}"),
+ CommandRule("pixi", "any", "pixi add {packages}"),
+ CommandRule("poetry", "any", "poetry add {packages}"),
+ CommandRule("rye", "any", "rye add {packages}"),
+ CommandRule("pip", "any", "python -m pip install {packages}"),
+)
+
+_POST_INSTALL_COMMAND_RULES: Final[tuple[CommandRule, ...]] = (
+ CommandRule("uv", "project", "uv run {command}"),
+ CommandRule("pixi", "any", "pixi run {command}"),
+ CommandRule("poetry", "any", "poetry run {command}"),
+ CommandRule("rye", "any", "rye run {command}"),
+ CommandRule("pip", "any", "{module_fallback}"),
+)
+
+_UPGRADE_COMMAND_RULES: Final[tuple[CommandRule, ...]] = (
+ CommandRule("uv", "project", "uv add --upgrade {packages}"),
+ CommandRule("uv", "any", "uv pip install --upgrade {packages}"),
+ CommandRule("pixi", "any", "pixi upgrade {packages}"),
+ CommandRule("poetry", "any", "poetry update --no-interaction {packages}"),
+ CommandRule("rye", "any", "rye sync --update {packages}"),
+ CommandRule("pip", "any", "python -m pip install --upgrade {packages}"),
+)
+
+
+def _is_uv_project_context() -> bool:
+ """Return whether the current environment matches a uv project venv."""
+ uv_project_environment = os.environ.get("UV_PROJECT_ENVIRONMENT")
+ virtual_env = os.environ.get("VIRTUAL_ENV")
+ if uv_project_environment and uv_project_environment == virtual_env:
+ return True
+
+ cwd = Path.cwd()
+ for path in (cwd, *cwd.parents):
+ if (path / "pyproject.toml").exists() and (path / "uv.lock").exists():
+ return True
+ return False
+
+
+def _normalize_packages(packages: str | list[str] | tuple[str, ...]) -> str:
+ if isinstance(packages, str):
+ package_tokens = packages.split()
+ else:
+ package_tokens = [
+ package.strip() for package in packages if package.strip()
+ ]
+ return " ".join(
+ _quote_package_token(package) for package in package_tokens
+ )
+
+
+def _quote_package_token(package: str) -> str:
+ if "[" not in package and "]" not in package:
+ return package
+ if is_windows():
+ return package
+ escaped = package.replace("'", "'\"'\"'")
+ return f"'{escaped}'"
+
+
+def _normalize_command(command: str) -> str:
+ return command.strip()
+
+
+def _resolve_manager_context() -> tuple[PackageManagerKind, str]:
+ """Infer package manager and whether uv should use project-local commands."""
+ manager = infer_package_manager()
+ context = (
+ "project" if manager == "uv" and _is_uv_project_context() else "any"
+ )
+ return manager, context
+
+
+def _resolve_template(
+ rules: tuple[CommandRule, ...],
+ manager: PackageManagerKind,
+ *,
+ context: str,
+) -> str | None:
+ """Select the first command template matching manager and context."""
+ for rule in rules:
+ if rule.manager != manager:
+ continue
+ if rule.context not in ("any", context):
+ continue
+ return rule.template
+ return None
+
+
+def _build_primary_and_fallback(
+ *,
+ rules: tuple[CommandRule, ...],
+ format_args: dict[str, str],
+) -> list[str]:
+ """Build primary and pip-fallback commands from declarative templates."""
+ manager, context = _resolve_manager_context()
+ template = _resolve_template(rules, manager, context=context)
+ fallback_template = _resolve_template(rules, "pip", context="any")
+ assert fallback_template is not None
+
+ primary_command = (
+ template.format(**format_args)
+ if template is not None
+ else fallback_template.format(**format_args)
+ )
+ pip_fallback_command = fallback_template.format(**format_args)
+
+ if primary_command == pip_fallback_command:
+ return [primary_command]
+ return [primary_command, pip_fallback_command]
+
+
+def get_install_commands(
+ packages: str | list[str] | tuple[str, ...],
+) -> list[str]:
+ package_text = _normalize_packages(packages)
+ if not package_text:
+ return []
+ return _build_primary_and_fallback(
+ rules=_INSTALL_COMMAND_RULES,
+ format_args={"packages": package_text},
+ )
+
+
+def get_post_install_commands(
+ command: str, *, module_fallback: str | None = None
+) -> list[str]:
+ command_text = _normalize_command(command)
+ if not command_text:
+ return []
+
+ fallback = _normalize_command(module_fallback or command_text)
+ if not fallback:
+ return []
+
+ return _build_primary_and_fallback(
+ rules=_POST_INSTALL_COMMAND_RULES,
+ format_args={
+ "command": command_text,
+ "module_fallback": fallback,
+ },
+ )
+
+
+def get_upgrade_commands(
+ packages: str | list[str] | tuple[str, ...],
+) -> list[str]:
+ package_text = _normalize_packages(packages)
+ if not package_text:
+ return []
+ return _build_primary_and_fallback(
+ rules=_UPGRADE_COMMAND_RULES,
+ format_args={"packages": package_text},
+ )
+
+
+def get_playwright_chromium_setup_commands() -> list[str]:
+ return get_post_install_commands(
+ "playwright install chromium",
+ module_fallback="python -m playwright install chromium",
+ )
diff --git a/marimo/_cli/parser_ux.py b/marimo/_cli/parser_ux.py
new file mode 100644
index 0000000000..b0913a0b0d
--- /dev/null
+++ b/marimo/_cli/parser_ux.py
@@ -0,0 +1,73 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import Any
+
+import click
+
+from marimo._cli.print import red
+
+
+def _normalize_usage_message(message: str) -> str:
+ """Normalize usage text for concise lowercase error output."""
+ message = message.strip()
+ if message.endswith("."):
+ message = message[:-1]
+ if message and message[0].isupper():
+ return message[0].lower() + message[1:]
+ return message
+
+
+def _format_suggestion_tip(suggestions: list[str]) -> str:
+ suggestions = sorted(suggestions)
+ if len(suggestions) == 1:
+ return f" tip: a similar argument exists: {suggestions[0]!r}"
+ joined = ", ".join(repr(item) for item in suggestions)
+ return f" tip: some similar arguments exist: {joined}"
+
+
+def _format_no_such_option(error: click.NoSuchOption) -> list[str]:
+ lines = [
+ f"{red('error')}: unexpected argument {error.option_name!r} found"
+ ]
+ if error.possibilities:
+ lines.extend(["", _format_suggestion_tip(list(error.possibilities))])
+ return lines
+
+
+def _format_generic_usage_error(error: click.UsageError) -> list[str]:
+ message_lines = error.format_message().splitlines()
+ if not message_lines:
+ return [f"{red('error')}: usage error"]
+
+ first = _normalize_usage_message(message_lines[0])
+ return [f"{red('error')}: {first}", *message_lines[1:]]
+
+
+def _format_usage_error(error: click.UsageError) -> list[str]:
+ if isinstance(error, click.NoSuchOption):
+ return _format_no_such_option(error)
+ return _format_generic_usage_error(error)
+
+
+def show_compact_usage_error(
+ error: click.UsageError, file: Any = None
+) -> None:
+ """Print compact parser errors without the full command help block."""
+ if file is None:
+ file = click.get_text_stream("stderr")
+
+ color = error.ctx.color if error.ctx is not None else None
+ for line in _format_usage_error(error):
+ click.echo(line, file=file, color=color)
+
+ if error.ctx is not None:
+ click.echo(file=file, color=color)
+ click.echo(error.ctx.get_usage(), file=file, color=color)
+ click.echo(file=file, color=color)
+
+ click.echo(
+ "For more information, try '--help'.",
+ file=file,
+ color=color,
+ )
diff --git a/marimo/_cli/run_docker.py b/marimo/_cli/run_docker.py
index 898f5c3043..d0e9cf29ff 100644
--- a/marimo/_cli/run_docker.py
+++ b/marimo/_cli/run_docker.py
@@ -9,6 +9,7 @@ import click
from click import echo
from marimo import _loggers
+from marimo._cli.errors import MarimoCLIRuntimeError
from marimo._cli.print import green, muted, red
from marimo._config.settings import GLOBAL_SETTINGS
from marimo._utils.url import is_url
@@ -107,45 +108,44 @@ def run_in_docker(
port = 8080
if not _check_docker_installed():
- echo_red(
+ raise MarimoCLIRuntimeError(
"Docker is not installed. Please install Docker and try again."
)
- sys.exit(1)
if not _check_docker_running():
- echo_red(
+ raise MarimoCLIRuntimeError(
"Docker daemon is not running. Please start Docker and try again."
)
- sys.exit(1)
# Check if the port is already in use
existing_container = _check_port_in_use(port)
if existing_container:
- echo_red(
- f"Port {port} is already in use by container {existing_container}"
+ stop_command = muted(f"docker stop {existing_container}")
+ raise MarimoCLIRuntimeError(
+ f"Port {port} is already in use by container {existing_container}.\n"
+ "To remove the existing container, run:\n"
+ f" {stop_command}\n"
+ "Then try running this command again."
)
- echo("To remove the existing container, run:")
- echo(muted(f" docker stop {existing_container}"))
- echo("Then try running this command again.")
- sys.exit(1)
# Define the container image and command
image = "ghcr.io/astral-sh/uv:0.9.25-python3.14-bookworm"
- container_command = [
- "uvx",
- "marimo",
- "-d" if debug else "",
- mode,
- "--sandbox",
- "--no-token",
- "-p",
- f"{port}",
- "--host",
- host,
- file_path if file_path is not None else "",
- ]
- # Remove empty strings from command
- container_command = [arg for arg in container_command if arg]
+ container_command = ["uvx", "marimo"]
+ if debug:
+ container_command.append("-d")
+ container_command.extend(
+ [
+ mode,
+ "--sandbox",
+ "--no-token",
+ "-p",
+ f"{port}",
+ "--host",
+ host,
+ ]
+ )
+ if file_path is not None:
+ container_command.append(file_path)
# Construct the docker run command
docker_command = [
@@ -189,8 +189,9 @@ def run_in_docker(
except KeyboardInterrupt:
echo("Received keyboard interrupt.")
except subprocess.CalledProcessError as e:
- echo_red(f"Failed to start Docker container: {e}")
- sys.exit(1)
+ raise MarimoCLIRuntimeError(
+ f"Failed to start Docker container: {e}"
+ ) from e
finally:
echo("Stopping and removing container...")
try:
diff --git a/marimo/_cli/sandbox.py b/marimo/_cli/sandbox.py
index 5556c1ea43..34f4bde66d 100644
--- a/marimo/_cli/sandbox.py
+++ b/marimo/_cli/sandbox.py
@@ -16,6 +16,7 @@ from typing import Literal, Optional
import click
from marimo import _loggers
+from marimo._cli.errors import MarimoCLIMissingDependencyError
from marimo._cli.print import bold, echo, green, muted
from marimo._config.settings import GLOBAL_SETTINGS
from marimo._dependencies.dependencies import DependencyManager
@@ -424,7 +425,11 @@ def run_in_sandbox(
"""
# If we fall back to the plain "uv" path, ensure it's actually on the system
if find_uv_bin() == "uv" and not DependencyManager.which("uv"):
- raise click.UsageError("uv must be installed to use --sandbox")
+ raise MarimoCLIMissingDependencyError(
+ "uv must be installed to use --sandbox.",
+ "uv",
+ additional_tip="Install uv from https://github.com/astral-sh/uv",
+ )
# Ensure marimo and python version are in the script metadata before running
_ensure_marimo_in_script_metadata(name)
diff --git a/marimo/_cli/suggestions.py b/marimo/_cli/suggestions.py
new file mode 100644
index 0000000000..dd5b6d323e
--- /dev/null
+++ b/marimo/_cli/suggestions.py
@@ -0,0 +1,97 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from difflib import get_close_matches
+from typing import TYPE_CHECKING
+
+from marimo._utils.edit_distance import edit_distance
+
+if TYPE_CHECKING:
+ from collections.abc import Iterable
+
+
+def _dedupe(items: Iterable[str]) -> list[str]:
+ return list(dict.fromkeys(items))
+
+
+def _lower_map(candidates: Iterable[str]) -> dict[str, str]:
+ lowered: dict[str, str] = {}
+ for candidate in candidates:
+ lowered.setdefault(candidate.lower(), candidate)
+ return lowered
+
+
+def suggest_commands(token: str, candidates: Iterable[str]) -> list[str]:
+ """Suggest close command names using difflib then Levenshtein fallback."""
+ lowered = _lower_map(candidates)
+ if not lowered:
+ return []
+
+ token_lower = token.lower()
+ if token_lower in lowered:
+ return [lowered[token_lower]]
+
+ close = get_close_matches(
+ token_lower,
+ list(lowered.keys()),
+ n=3,
+ cutoff=0.6,
+ )
+ if close:
+ return [lowered[item] for item in close]
+
+ ranked = sorted(
+ (
+ (edit_distance(token_lower, key), value)
+ for key, value in lowered.items()
+ ),
+ key=lambda item: (item[0], item[1]),
+ )
+ if not ranked:
+ return []
+
+ min_distance = ranked[0][0]
+ if min_distance > 2:
+ return []
+
+ closest_values = [
+ value for distance, value in ranked if distance == min_distance
+ ]
+ return closest_values[:3]
+
+
+def suggest_short_options(token: str, candidates: Iterable[str]) -> list[str]:
+ """Suggest a single short-flag correction when the typo is unambiguous."""
+ if not token.startswith("-") or token.startswith("--"):
+ return []
+
+ short_candidates = _dedupe(
+ option
+ for option in candidates
+ if option.startswith("-") and not option.startswith("--")
+ )
+ if not short_candidates:
+ return []
+
+ token_lower = token.lower()
+ exact = [opt for opt in short_candidates if opt.lower() == token_lower]
+ if exact:
+ return [exact[0]]
+
+ ranked = sorted(
+ (edit_distance(token, candidate), candidate)
+ for candidate in short_candidates
+ )
+ best_distance = ranked[0][0]
+ if best_distance > 1:
+ return []
+
+ best = [
+ candidate
+ for distance, candidate in ranked
+ if distance == best_distance
+ ]
+ if len(best) != 1:
+ return []
+
+ return best
diff --git a/marimo/_cli/upgrade.py b/marimo/_cli/upgrade.py
index e0f37e5d77..0098e7a5e5 100644
--- a/marimo/_cli/upgrade.py
+++ b/marimo/_cli/upgrade.py
@@ -9,6 +9,7 @@ from typing import Any, Callable, cast
import marimo._utils.requests as requests
from marimo import _loggers
+from marimo._cli.install_hints import get_upgrade_commands
from marimo._cli.print import echo, green, orange
from marimo._config.cli_state import (
MarimoCLIState,
@@ -26,8 +27,14 @@ LOGGER = _loggers.marimo_logger()
def print_latest_version(current_version: str, state: MarimoCLIState) -> None:
message = f"Update available {current_version} → {state.latest_version}"
echo(orange(message))
- install_cmd = "uv add" if _is_in_uv() else "pip install"
- echo(f"Run {green(f'{install_cmd} --upgrade marimo')} to upgrade.")
+ upgrade_commands = get_upgrade_commands("marimo")
+ if upgrade_commands:
+ if len(upgrade_commands) == 1:
+ echo(f"Run {green(upgrade_commands[0])} to upgrade.")
+ else:
+ primary_command = green(upgrade_commands[0])
+ fallback_command = green(upgrade_commands[1])
+ echo(f"Run {primary_command} or {fallback_command} to upgrade.")
if state.notices:
echo()
@@ -38,15 +45,6 @@ def print_latest_version(current_version: str, state: MarimoCLIState) -> None:
echo()
-def _is_in_uv() -> bool:
- try:
- import psutil
- except Exception:
- # No warning, since this is just used for cosmetics.
- return False
- return psutil.Process(os.getppid()).name() == "uv"
-
-
@server_tracer.start_as_current_span("check_for_updates")
def check_for_updates(
on_update: Callable[[str, MarimoCLIState], None],
diff --git a/marimo/_convert/script.py b/marimo/_convert/script.py
index 727b6f1250..34672c9aa7 100644
--- a/marimo/_convert/script.py
+++ b/marimo/_convert/script.py
@@ -17,9 +17,9 @@ def convert_from_ir_to_script(ir: NotebookSerialization) -> str:
if not cell:
continue
if cell._is_coroutine:
- from click import UsageError
+ from click import ClickException
- raise UsageError(
+ raise ClickException(
"Cannot export a notebook with async code to a flat script"
)
diff --git a/marimo/_mcp/server/main.py b/marimo/_mcp/server/main.py
index 0dd26625ad..23f90090e5 100644
--- a/marimo/_mcp/server/main.py
+++ b/marimo/_mcp/server/main.py
@@ -12,6 +12,7 @@ from typing import TYPE_CHECKING
from marimo._ai._tools.base import ToolContext
from marimo._ai._tools.tools_registry import SUPPORTED_BACKEND_AND_MCP_TOOLS
+from marimo._cli.errors import MarimoCLIMissingDependencyError
from marimo._dependencies.dependencies import DependencyManager
from marimo._loggers import marimo_logger
@@ -35,10 +36,10 @@ def setup_mcp_server(app: Starlette) -> None:
StreamableHTTPSessionManager: MCP session manager
"""
if not DependencyManager.mcp.has():
- from click import ClickException
-
- msg = "MCP dependencies not available. Install with `pip install marimo[mcp]` or `uv add marimo[mcp]`"
- raise ClickException(msg)
+ raise MarimoCLIMissingDependencyError(
+ "MCP dependencies not available.",
+ "marimo[mcp]",
+ )
from mcp.server.fastmcp import FastMCP
from starlette.middleware.base import BaseHTTPMiddleware
diff --git a/marimo/_utils/edit_distance.py b/marimo/_utils/edit_distance.py
new file mode 100644
index 0000000000..a3367f0c7f
--- /dev/null
+++ b/marimo/_utils/edit_distance.py
@@ -0,0 +1,30 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+
+def edit_distance(left: str, right: str) -> int:
+ """Return the Levenshtein edit distance between two strings."""
+ if left == right:
+ return 0
+ if not left:
+ return len(right)
+ if not right:
+ return len(left)
+
+ previous_row = list(range(len(right) + 1))
+ for left_index, left_char in enumerate(left, start=1):
+ current_row = [left_index]
+ for right_index, right_char in enumerate(right, start=1):
+ if left_char == right_char:
+ current_row.append(previous_row[right_index - 1])
+ else:
+ current_row.append(
+ 1
+ + min(
+ previous_row[right_index],
+ current_row[right_index - 1],
+ previous_row[right_index - 1],
+ )
+ )
+ previous_row = current_row
+ return previous_row[-1]
diff --git a/tests/_cli/test_cli.py b/tests/_cli/test_cli.py
index d4dd14a513..03e24b92fd 100644
--- a/tests/_cli/test_cli.py
+++ b/tests/_cli/test_cli.py
@@ -20,6 +20,7 @@ import urllib.error
import urllib.request
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Optional
+from unittest.mock import patch
import pytest
@@ -39,6 +40,7 @@ if TYPE_CHECKING:
from collections.abc import Iterator
HAS_UV = DependencyManager.which("uv")
+HAS_ZMQ = DependencyManager.zmq.has()
DIR_PATH = os.path.dirname(os.path.realpath(__file__))
@@ -301,6 +303,173 @@ def test_cli_help_colored_output() -> None:
print_module._style = original_style
+def test_cli_unknown_command_uses_compact_error() -> None:
+ from click.testing import CliRunner
+
+ from marimo._cli.cli import main
+
+ runner = CliRunner()
+ result = runner.invoke(main, ["xport"])
+ assert result.exit_code == 2
+ assert "error: unrecognized command 'xport'" in result.output
+ assert "tip: a similar command exists: 'export'" in result.output
+ assert "Usage: main [OPTIONS] COMMAND [ARGS]..." in result.output
+ assert "For more information, try '--help'." in result.output
+ assert "Commands:" not in result.output
+
+
+def test_cli_nested_unknown_command_uses_compact_error() -> None:
+ from click.testing import CliRunner
+
+ from marimo._cli.cli import main
+
+ runner = CliRunner()
+ result = runner.invoke(main, ["export", "hxml"])
+ assert result.exit_code == 2
+ assert "error: unrecognized command 'hxml'" in result.output
+ assert "tip: a similar command exists: 'html'" in result.output
+ assert "Usage: main export [OPTIONS] COMMAND [ARGS]..." in result.output
+ assert "For more information, try '--help'." in result.output
+ assert "Commands:" not in result.output
+
+
+def test_cli_long_option_typo_uses_compact_error() -> None:
+ from click.testing import CliRunner
+
+ from marimo._cli.cli import main
+
+ runner = CliRunner()
+ result = runner.invoke(main, ["edit", "--hedlss"])
+ assert result.exit_code == 2
+ assert "error: unexpected argument '--hedlss' found" in result.output
+ assert "tip: some similar arguments exist:" in result.output
+ assert "'--headless'" in result.output
+ assert "Usage: main edit [OPTIONS] [NAME] [ARGS]..." in result.output
+ assert "For more information, try '--help'." in result.output
+ assert "Options:" not in result.output
+
+
+def test_cli_short_option_typo_suggests_case_variant() -> None:
+ from click.testing import CliRunner
+
+ from marimo._cli.cli import main
+
+ runner = CliRunner()
+ result = runner.invoke(main, ["run", "-P", "notebook.py"])
+ assert result.exit_code == 2
+ assert "error: unexpected argument '-P' found" in result.output
+ assert "tip: a similar argument exists: '-p'" in result.output
+ assert "Usage: main run [OPTIONS] NAME [ARGS]..." in result.output
+
+
+def test_cli_short_option_typo_without_clear_match_has_no_tip() -> None:
+ from click.testing import CliRunner
+
+ from marimo._cli.cli import main
+
+ runner = CliRunner()
+ result = runner.invoke(main, ["run", "-Z", "notebook.py"])
+ assert result.exit_code == 2
+ assert "error: unexpected argument '-Z' found" in result.output
+ assert "tip: a similar argument exists:" not in result.output
+ assert "Usage: main run [OPTIONS] NAME [ARGS]..." in result.output
+
+
+def test_cli_missing_argument_uses_compact_error() -> None:
+ from click.testing import CliRunner
+
+ from marimo._cli.cli import main
+
+ runner = CliRunner()
+ result = runner.invoke(main, ["run"])
+ assert result.exit_code == 2
+ assert "error: missing argument 'NAME'" in result.output
+ assert "Usage: main run [OPTIONS] NAME [ARGS]..." in result.output
+ assert "For more information, try '--help'." in result.output
+ assert "Options:" not in result.output
+
+
+def test_cli_edit_sandbox_missing_zmq_skips_update_check() -> None:
+ from click.testing import CliRunner
+
+ from marimo._cli.cli import main
+
+ runner = CliRunner()
+ captured_packages: dict[str, str | list[str]] = {}
+
+ def _capture_install_commands(
+ packages: str | list[str] | tuple[str, ...],
+ ) -> list[str]:
+ captured_packages["value"] = (
+ packages if isinstance(packages, str) else list(packages)
+ )
+ return ["python -m pip install 'marimo[sandbox]'"]
+
+ with (
+ patch(
+ "marimo._cli.cli.prompt_run_in_docker_container",
+ return_value=False,
+ ),
+ patch(
+ "marimo._dependencies.dependencies.DependencyManager.zmq.has",
+ return_value=False,
+ ),
+ patch(
+ "marimo._cli.errors.get_install_commands",
+ side_effect=_capture_install_commands,
+ ),
+ patch("marimo._cli.cli.check_for_updates") as mock_check_for_updates,
+ ):
+ result = runner.invoke(main, ["edit", "--sandbox"])
+
+ assert result.exit_code == 1
+ mock_check_for_updates.assert_not_called()
+ assert captured_packages["value"] == "marimo[sandbox]"
+ assert (
+ "pyzmq is required when running the marimo edit server on a directory with --sandbox."
+ in result.output
+ )
+ assert "python -m pip install 'marimo[sandbox]'" in result.output
+ assert "'marimo[sandbox]' pyzmq" not in result.output
+
+
+def test_cli_edit_checks_for_updates_after_preflight() -> None:
+ from click.testing import CliRunner
+
+ from marimo._cli.cli import main
+
+ runner = CliRunner()
+ events: list[str] = []
+
+ with (
+ runner.isolated_filesystem(),
+ patch.dict(os.environ, {"MARIMO_SKIP_UPDATE_CHECK": "0"}),
+ patch(
+ "marimo._cli.cli.prompt_run_in_docker_container",
+ return_value=False,
+ ),
+ patch(
+ "marimo._utils.platform.check_shared_memory_available",
+ return_value=(True, None),
+ ),
+ patch(
+ "marimo._cli.cli.check_for_updates",
+ side_effect=lambda *_args, **_kwargs: events.append("update"),
+ ),
+ patch(
+ "marimo._cli.cli.start",
+ side_effect=lambda *_args, **_kwargs: events.append("start"),
+ ),
+ ):
+ result = runner.invoke(
+ main,
+ ["edit", "notebook.py", "--headless", "--no-token"],
+ )
+
+ assert result.exit_code == 0
+ assert events == ["update", "start"]
+
+
def test_cli_edit_none() -> None:
# smoke test: makes sure CLI starts and has basic things we expect
# helpful for catching issues related to
@@ -704,7 +873,10 @@ def test_cli_run_directory_gallery() -> None:
_check_contents(p, b'"mode": "gallery"', contents)
[email protected](not HAS_UV, reason="uv is required for sandbox tests")
+ not (HAS_UV and HAS_ZMQ),
+ reason="uv and pyzmq are required for multi-sandbox tests",
+)
def test_cli_run_directory_gallery_with_sandbox() -> None:
"""Test that gallery mode works with --sandbox flag."""
directory = tempfile.TemporaryDirectory()
@@ -736,7 +908,7 @@ def test_cli_run_directory_gallery_rejects_check() -> None:
output = result.stderr + result.stdout
assert result.returncode != 0
assert (
- "--check is only supported when running a single notebook file."
+ "--check is only supported when running a single notebook file"
in output
)
@@ -787,7 +959,10 @@ def test_cli_run_multiple_files_gallery() -> None:
_check_contents(p, b'"mode": "gallery"', contents)
[email protected](not HAS_UV, reason="uv is required for sandbox tests")
+ not (HAS_UV and HAS_ZMQ),
+ reason="uv and pyzmq are required for multi-sandbox tests",
+)
def test_cli_run_directory_gallery_sandbox_can_open_file() -> None:
"""Test that individual notebooks can be opened from gallery in sandbox mode."""
directory = tempfile.TemporaryDirectory()
@@ -817,7 +992,10 @@ def test_cli_run_directory_gallery_sandbox_can_open_file() -> None:
p.kill()
[email protected](not HAS_UV, reason="uv is required for sandbox tests")
+ not (HAS_UV and HAS_ZMQ),
+ reason="uv and pyzmq are required for multi-sandbox tests",
+)
def test_cli_run_multiple_files_gallery_sandbox() -> None:
"""Test gallery mode with multiple explicit files and --sandbox."""
directory = tempfile.TemporaryDirectory()
@@ -1106,7 +1284,10 @@ def test_cli_sandbox_edit_new_file() -> None:
_check_contents(p, b"edit", contents)
[email protected](not HAS_UV, reason="uv is required for sandbox tests")
+ not (HAS_UV and HAS_ZMQ),
+ reason="uv and pyzmq are required for multi-sandbox tests",
+)
def test_cli_edit_sandbox_multi_notebook() -> None:
# With IPC-based kernel, sandbox now works with multi-notebook servers
port = _get_port()
@@ -1132,7 +1313,10 @@ def test_cli_edit_sandbox_multi_notebook() -> None:
_check_contents(p, b'"serverToken": ', contents)
[email protected](not HAS_UV, reason="uv is required for sandbox tests")
+ not (HAS_UV and HAS_ZMQ),
+ reason="uv and pyzmq are required for multi-sandbox tests",
+)
def test_cli_edit_directory_sandbox() -> None:
# With IPC-based kernel, sandbox now works with directories
port = _get_port()
@@ -1473,7 +1657,10 @@ def test_cli_with_custom_pyproject_config(tmp_path: Path) -> None:
# Test sandbox with config for vscode compatibility
[email protected](not HAS_UV, reason="uv is required for sandbox tests")
+ not (HAS_UV and HAS_ZMQ),
+ reason="uv and pyzmq are required for multi-sandbox tests",
+)
def test_cli_with_custom_pyproject_config_no_file(tmp_path: Path) -> None:
# Create a custom pyproject.toml with special marimo config
pyproject_path = tmp_path / "pyproject.toml"
@@ -1560,9 +1747,9 @@ def test_cli_with_custom_pyproject_config_no_file(tmp_path: Path) -> None:
reason="win32 only",
),
),
- # invalid shell values, rc of 0, data only on stderr
- ("bogus", 2, False, True),
- ("", 2, False, True), # usage error displayed
+ # invalid shell values, rc of 1, data only on stderr
+ ("bogus", 1, False, True),
+ ("", 1, False, True),
],
)
def test_shell_completion(
@@ -1600,9 +1787,10 @@ def test_cli_run_docker_remote_url():
)
# Should fail with missing docker
+ stdout, stderr = p.communicate(timeout=5)
assert p.returncode != 0
- assert p.stdout is not None
- assert "Docker is not installed" in p.stdout.read().decode()
+ output = stdout.decode() + stderr.decode()
+ assert "Docker is not installed" in output
def test_cli_edit_trusted(temp_marimo_file: str) -> None:
@@ -1641,9 +1829,10 @@ def test_cli_edit_no_trusted(temp_marimo_file: str) -> None:
)
# Should fail with missing docker
+ stdout, stderr = p.communicate(timeout=5)
assert p.returncode != 0
- assert p.stdout is not None
- assert "Docker is not installed" in p.stdout.read().decode()
+ output = stdout.decode() + stderr.decode()
+ assert "Docker is not installed" in output
def test_cli_run_trusted(temp_marimo_file: str) -> None:
@@ -1681,9 +1870,10 @@ def test_cli_run_no_trusted(temp_marimo_file: str) -> None:
)
# Should fail with missing docker
+ stdout, stderr = p.communicate(timeout=5)
assert p.returncode != 0
- assert p.stdout is not None
- assert "Docker is not installed" in p.stdout.read().decode()
+ output = stdout.decode() + stderr.decode()
+ assert "Docker is not installed" in output
def test_cli_edit_with_convert(
diff --git a/tests/_cli/test_cli_convert.py b/tests/_cli/test_cli_convert.py
index 39c3736724..1a87d7ea36 100644
--- a/tests/_cli/test_cli_convert.py
+++ b/tests/_cli/test_cli_convert.py
@@ -167,7 +167,7 @@ print('Hello from Markdown!')
text=True,
)
assert p.returncode != 0
- assert "File must be an .ipynb, .md, or .py file" in p.stderr
+ assert "file must be an .ipynb, .md, or .py file" in p.stderr
@staticmethod
def test_convert_remote_ipynb(http_server: MockHTTPServer) -> None:
@@ -255,7 +255,7 @@ print('Hello from Remote Markdown!')
text=True,
)
assert p.returncode != 0
- assert "File must be an .ipynb, .md, or .py file" in p.stderr
+ assert "file must be an .ipynb, .md, or .py file" in p.stderr
@staticmethod
def test_convert_nonexistent_remote_file(
diff --git a/tests/_cli/test_cli_errors.py b/tests/_cli/test_cli_errors.py
new file mode 100644
index 0000000000..f92303e332
--- /dev/null
+++ b/tests/_cli/test_cli_errors.py
@@ -0,0 +1,76 @@
+# Copyright 2026 Marimo. All rights reserved.
+# NB. test_cli_errors.py because test_errors.py name causes pycache errors
+# with pytest.
+from __future__ import annotations
+
+from io import StringIO
+from pathlib import Path
+from unittest.mock import patch
+
+from marimo._cli.errors import MarimoCLIError, MarimoCLIMissingDependencyError
+
+
+def test_missing_dependency_error_renders_followup_commands() -> None:
+ with patch(
+ "marimo._cli.errors.get_install_commands",
+ return_value=[
+ "poetry add nbconvert[webpdf]",
+ "python -m pip install nbconvert[webpdf]",
+ ],
+ ):
+ error = MarimoCLIMissingDependencyError(
+ "Playwright is required for WebPDF export.",
+ "nbconvert[webpdf]",
+ followup_commands=[
+ "poetry run playwright install chromium",
+ "python -m playwright install chromium",
+ ],
+ )
+
+ message = str(error)
+ assert "Tip: Install with:" in message
+ assert "poetry add nbconvert[webpdf]" in message
+ assert "Or with pip:" in message
+ assert "Then run:" in message
+ assert "poetry run playwright install chromium" in message
+ assert "Or with fallback:" in message
+ assert "python -m playwright install chromium" in message
+
+
+def test_missing_dependency_error_preserves_additional_tip() -> None:
+ with patch(
+ "marimo._cli.errors.get_install_commands",
+ return_value=["python -m pip install uv"],
+ ):
+ error = MarimoCLIMissingDependencyError(
+ "uv must be installed to use --sandbox.",
+ "uv",
+ additional_tip="Install uv from https://github.com/astral-sh/uv",
+ )
+
+ message = str(error)
+ assert "python -m pip install uv" in message
+ assert "Install uv from https://github.com/astral-sh/uv" in message
+
+
+def test_chromium_setup_command_not_hardcoded_in_export_callsites() -> None:
+ repo_root = Path(__file__).resolve().parents[2]
+ export_commands = (
+ repo_root / "marimo" / "_cli" / "export" / "commands.py"
+ ).read_text(encoding="utf-8")
+ export_thumbnail = (
+ repo_root / "marimo" / "_cli" / "export" / "thumbnail.py"
+ ).read_text(encoding="utf-8")
+ assert "python -m playwright install chromium" not in export_commands
+ assert "python -m playwright install chromium" not in export_thumbnail
+
+
+def test_marimo_cli_error_show_formats_error_prefix() -> None:
+ error = MarimoCLIError("boom")
+ output = StringIO()
+
+ with patch("marimo._cli.errors.red", return_value="<error>") as mock_red:
+ error.show(file=output)
+
+ mock_red.assert_called_once_with("Error", bold=True)
+ assert output.getvalue() == "<error>: boom\n"
diff --git a/tests/_cli/test_cli_export.py b/tests/_cli/test_cli_export.py
index 57e2617f27..b98a0cc572 100644
--- a/tests/_cli/test_cli_export.py
+++ b/tests/_cli/test_cli_export.py
@@ -328,9 +328,8 @@ class TestExportHTML:
line = p.stderr.readline().decode()
if line:
assert (
- "Cannot use --watch without providing "
- + "an output file with --output."
- in line
+ "cannot use --watch without providing an output file "
+ "with --output" in line
)
break
@@ -470,7 +469,7 @@ class TestExportScript:
@staticmethod
def test_export_script_async(temp_async_marimo_file: str) -> None:
p = _run_export("script", temp_async_marimo_file)
- assert p.returncode == 2, p.stderr.decode()
+ assert p.returncode == 1, p.stderr.decode()
assert (
"Cannot export a notebook with async code to a flat script"
in p.stderr.decode()
@@ -567,9 +566,8 @@ class TestExportScript:
line = p.stderr.readline().decode()
if line:
assert (
- "Cannot use --watch without providing "
- + "an output file with --output."
- in line
+ "cannot use --watch without providing an output file "
+ "with --output" in line
)
break
@@ -672,9 +670,8 @@ class TestExportMarkdown:
line = p.stderr.readline().decode()
if line:
assert (
- "Cannot use --watch without providing "
- + "an output file with --output."
- in line
+ "cannot use --watch without providing an output file "
+ "with --output" in line
)
break
diff --git a/tests/_cli/test_cli_export_thumbnail.py b/tests/_cli/test_cli_export_thumbnail.py
index 448e88a377..7ffaf18560 100644
--- a/tests/_cli/test_cli_export_thumbnail.py
+++ b/tests/_cli/test_cli_export_thumbnail.py
@@ -153,7 +153,7 @@ def test_thumbnail_sandbox_requires_execute(tmp_path: Path) -> None:
)
assert result.exit_code != 0
- assert "--sandbox requires --execute." in result.output
+ assert "--sandbox requires --execute" in result.output
def test_thumbnail_reentry_single_skips_bootstrap(
diff --git a/tests/_cli/test_install_hints.py b/tests/_cli/test_install_hints.py
new file mode 100644
index 0000000000..73d88c1477
--- /dev/null
+++ b/tests/_cli/test_install_hints.py
@@ -0,0 +1,218 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from unittest.mock import patch
+
+from marimo._cli.install_hints import (
+ get_install_commands,
+ get_playwright_chromium_setup_commands,
+ get_post_install_commands,
+ get_upgrade_commands,
+)
+
+
+def test_install_commands_uv_project() -> None:
+ with (
+ patch(
+ "marimo._cli.install_hints.infer_package_manager",
+ return_value="uv",
+ ),
+ patch(
+ "marimo._cli.install_hints._is_uv_project_context",
+ return_value=True,
+ ),
+ ):
+ assert get_install_commands("rich") == [
+ "uv add rich",
+ "python -m pip install rich",
+ ]
+
+
+def test_install_commands_uv_non_project() -> None:
+ with (
+ patch(
+ "marimo._cli.install_hints.infer_package_manager",
+ return_value="uv",
+ ),
+ patch(
+ "marimo._cli.install_hints._is_uv_project_context",
+ return_value=False,
+ ),
+ ):
+ assert get_install_commands("rich") == [
+ "uv pip install rich",
+ "python -m pip install rich",
+ ]
+
+
+def test_install_commands_for_pixi() -> None:
+ with patch(
+ "marimo._cli.install_hints.infer_package_manager",
+ return_value="pixi",
+ ):
+ assert get_install_commands("nbconvert playwright") == [
+ "pixi add nbconvert playwright",
+ "python -m pip install nbconvert playwright",
+ ]
+
+
+def test_install_commands_for_pip_only() -> None:
+ with patch(
+ "marimo._cli.install_hints.infer_package_manager",
+ return_value="pip",
+ ):
+ assert get_install_commands(["nbformat"]) == [
+ "python -m pip install nbformat"
+ ]
+
+
+def test_post_install_commands_uv_project() -> None:
+ with (
+ patch(
+ "marimo._cli.install_hints.infer_package_manager",
+ return_value="uv",
+ ),
+ patch(
+ "marimo._cli.install_hints._is_uv_project_context",
+ return_value=True,
+ ),
+ ):
+ assert get_post_install_commands(
+ "playwright install chromium",
+ module_fallback="python -m playwright install chromium",
+ ) == [
+ "uv run playwright install chromium",
+ "python -m playwright install chromium",
+ ]
+
+
+def test_post_install_commands_uv_non_project() -> None:
+ with (
+ patch(
+ "marimo._cli.install_hints.infer_package_manager",
+ return_value="uv",
+ ),
+ patch(
+ "marimo._cli.install_hints._is_uv_project_context",
+ return_value=False,
+ ),
+ ):
+ assert get_post_install_commands(
+ "playwright install chromium",
+ module_fallback="python -m playwright install chromium",
+ ) == ["python -m playwright install chromium"]
+
+
+def test_post_install_commands_poetry() -> None:
+ with patch(
+ "marimo._cli.install_hints.infer_package_manager",
+ return_value="poetry",
+ ):
+ assert get_post_install_commands(
+ "playwright install chromium",
+ module_fallback="python -m playwright install chromium",
+ ) == [
+ "poetry run playwright install chromium",
+ "python -m playwright install chromium",
+ ]
+
+
+def test_upgrade_commands_uv_project() -> None:
+ with (
+ patch(
+ "marimo._cli.install_hints.infer_package_manager",
+ return_value="uv",
+ ),
+ patch(
+ "marimo._cli.install_hints._is_uv_project_context",
+ return_value=True,
+ ),
+ ):
+ assert get_upgrade_commands("marimo") == [
+ "uv add --upgrade marimo",
+ "python -m pip install --upgrade marimo",
+ ]
+
+
+def test_upgrade_commands_uv_non_project() -> None:
+ with (
+ patch(
+ "marimo._cli.install_hints.infer_package_manager",
+ return_value="uv",
+ ),
+ patch(
+ "marimo._cli.install_hints._is_uv_project_context",
+ return_value=False,
+ ),
+ ):
+ assert get_upgrade_commands("marimo") == [
+ "uv pip install --upgrade marimo",
+ "python -m pip install --upgrade marimo",
+ ]
+
+
+def test_upgrade_commands_for_pixi() -> None:
+ with patch(
+ "marimo._cli.install_hints.infer_package_manager",
+ return_value="pixi",
+ ):
+ assert get_upgrade_commands("marimo") == [
+ "pixi upgrade marimo",
+ "python -m pip install --upgrade marimo",
+ ]
+
+
+def test_upgrade_commands_for_pip_only() -> None:
+ with patch(
+ "marimo._cli.install_hints.infer_package_manager",
+ return_value="pip",
+ ):
+ assert get_upgrade_commands(["marimo"]) == [
+ "python -m pip install --upgrade marimo"
+ ]
+
+
+def test_playwright_chromium_setup_commands() -> None:
+ with patch(
+ "marimo._cli.install_hints.infer_package_manager",
+ return_value="pip",
+ ):
+ assert get_playwright_chromium_setup_commands() == [
+ "python -m playwright install chromium"
+ ]
+
+
+def test_install_commands_quotes_extras_on_posix() -> None:
+ with (
+ patch(
+ "marimo._cli.install_hints.infer_package_manager",
+ return_value="uv",
+ ),
+ patch(
+ "marimo._cli.install_hints._is_uv_project_context",
+ return_value=True,
+ ),
+ patch("marimo._cli.install_hints.is_windows", return_value=False),
+ ):
+ assert get_install_commands(["marimo[sandbox]", "pyzmq"]) == [
+ "uv add 'marimo[sandbox]' pyzmq",
+ "python -m pip install 'marimo[sandbox]' pyzmq",
+ ]
+
+
+def test_install_commands_does_not_quote_extras_on_windows() -> None:
+ with (
+ patch(
+ "marimo._cli.install_hints.infer_package_manager",
+ return_value="uv",
+ ),
+ patch(
+ "marimo._cli.install_hints._is_uv_project_context",
+ return_value=True,
+ ),
+ patch("marimo._cli.install_hints.is_windows", return_value=True),
+ ):
+ assert get_install_commands(["marimo[sandbox]", "pyzmq"]) == [
+ "uv add marimo[sandbox] pyzmq",
+ "python -m pip install marimo[sandbox] pyzmq",
+ ]
diff --git a/tests/_cli/test_suggestions.py b/tests/_cli/test_suggestions.py
new file mode 100644
index 0000000000..a627d736da
--- /dev/null
+++ b/tests/_cli/test_suggestions.py
@@ -0,0 +1,24 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from marimo._cli.suggestions import suggest_commands, suggest_short_options
+
+
+def test_suggest_commands_close_match() -> None:
+ candidates = ["edit", "export", "run", "tutorial"]
+ assert suggest_commands("xport", candidates) == ["export"]
+
+
+def test_suggest_commands_case_insensitive_exact() -> None:
+ candidates = ["edit", "export", "run"]
+ assert suggest_commands("EXPORT", candidates) == ["export"]
+
+
+def test_suggest_short_option_case_variant() -> None:
+ candidates = ["-p", "-h", "-q"]
+ assert suggest_short_options("-P", candidates) == ["-p"]
+
+
+def test_suggest_short_option_ambiguous_returns_empty() -> None:
+ candidates = ["-p", "-q", "-d", "-h"]
+ assert suggest_short_options("-Z", candidates) == []
diff --git a/tests/_cli/test_upgrade.py b/tests/_cli/test_upgrade.py
index ff008c09cf..93073d6f8f 100644
--- a/tests/_cli/test_upgrade.py
+++ b/tests/_cli/test_upgrade.py
@@ -41,6 +41,43 @@ def test_check_for_updates(
)
+@patch("marimo._cli.upgrade.get_upgrade_commands")
+@patch("marimo._cli.upgrade.echo")
+def test_print_latest_version_uses_manager_aware_commands(
+ mock_echo: Any, mock_get_upgrade_commands: Any
+) -> None:
+ state = MarimoCLIState(
+ latest_version="0.1.2", last_checked_at="2020-01-01"
+ )
+ mock_get_upgrade_commands.return_value = [
+ "pixi upgrade marimo",
+ "python -m pip install --upgrade marimo",
+ ]
+
+ print_latest_version("0.1.0", state)
+
+ assert any(
+ "pixi upgrade marimo" in call[0][0]
+ for call in mock_echo.call_args_list
+ )
+ assert any(
+ "python -m pip install --upgrade marimo" in call[0][0]
+ for call in mock_echo.call_args_list
+ )
+ assert any(
+ (
+ "Run pixi upgrade marimo or "
+ "python -m pip install --upgrade marimo to upgrade."
+ )
+ in call[0][0]
+ for call in mock_echo.call_args_list
+ )
+ assert not any(
+ call.args and str(call.args[0]).startswith("Or run ")
+ for call in mock_echo.call_args_list
+ )
+
+
@patch("marimo._cli.upgrade._fetch_data_from_url")
def test_update_with_latest_version(mock_fetch_data_from_url: Any) -> None:
# Mocks
diff --git a/tests/_utils/test_edit_distance.py b/tests/_utils/test_edit_distance.py
new file mode 100644
index 0000000000..c02f9ef49f
--- /dev/null
+++ b/tests/_utils/test_edit_distance.py
@@ -0,0 +1,9 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from marimo._utils.edit_distance import edit_distance
+
+
+def test_edit_distance() -> None:
+ assert edit_distance("kitten", "sitting") == 3
+ assert edit_distance("export", "export") == 0