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: include `playwright` when running sandboxed thumbnail generation (#8339)
Péter Gyarmati3973904ca079
diff --git a/marimo/_cli/export/thumbnail.py b/marimo/_cli/export/thumbnail.pyindex 178565bfe0..109f320f8e 100644--- a/marimo/_cli/export/thumbnail.py+++ b/marimo/_cli/export/thumbnail.py@@ -3,7 +3,9 @@ from __future__ import annotationsimport asyncioimport json+import osimport subprocess+import sysimport threadingfrom contextlib import AbstractContextManagerfrom functools import partial@@ -28,6 +30,8 @@ if TYPE_CHECKING:from collections.abc import Iterablefrom types import TracebackType+ from marimo._cli.sandbox import SandboxMode+_sandbox_message = ("Render notebooks in an isolated environment, with dependencies tracked "@@ -35,6 +39,20 @@ _sandbox_message = ("install automatically. Requires uv. Only applies when --execute is used.")_READINESS_WAIT_TIMEOUT_MS = 30_000+_sandbox_bootstrapped_env = "MARIMO_THUMBNAIL_SANDBOX_BOOTSTRAPPED"+_sandbox_mode_env = "MARIMO_THUMBNAIL_SANDBOX_MODE"+_thumbnail_sandbox_deps = ["playwright"]+++def _split_paths_and_args(+ name: str, args: tuple[str, ...]+) -> tuple[list[str], tuple[str, ...]]:+ paths = [name]+ for index, arg in enumerate(args):+ if arg == "--":+ return paths, args[index + 1 :]+ paths.append(arg)+ return paths, ()def _collect_notebooks(paths: Iterable[Path]) -> list[MarimoPath]:@@ -61,6 +79,67 @@ def _collect_notebooks(paths: Iterable[Path]) -> list[MarimoPath]:return [notebooks[k] for k in sorted(notebooks)]+def _is_multi_target(paths: list[Path]) -> bool:+ return len(paths) > 1 or any(path.is_dir() for path in paths)+++def _sandbox_mode_from_env() -> SandboxMode | None:+ from marimo._cli.sandbox import SandboxMode++ if os.environ.get(_sandbox_bootstrapped_env) != "1":+ return None++ mode = os.environ.get(_sandbox_mode_env)+ if mode == SandboxMode.SINGLE.value:+ return SandboxMode.SINGLE+ if mode == SandboxMode.MULTI.value:+ return SandboxMode.MULTI+ return None+++def _resolve_thumbnail_sandbox_mode(+ *,+ execute: bool,+ sandbox: bool | None,+ path_targets: list[Path],+ first_target: str,+) -> SandboxMode | None:+ from marimo._cli.sandbox import SandboxMode, resolve_sandbox_mode++ if not execute:+ return None++ env_mode = _sandbox_mode_from_env()+ if env_mode is not None:+ return env_mode++ if _is_multi_target(path_targets):+ if sandbox is None:+ return None+ return SandboxMode.MULTI if sandbox else None++ return resolve_sandbox_mode(sandbox=sandbox, name=first_target)+++def _bootstrap_thumbnail_sandbox(+ *,+ args: list[str],+ name: str,+ sandbox_mode: SandboxMode,+) -> None:+ from marimo._cli.sandbox import run_in_sandbox++ run_in_sandbox(+ args,+ name=name,+ additional_deps=_thumbnail_sandbox_deps,+ extra_env={+ _sandbox_bootstrapped_env: "1",+ _sandbox_mode_env: sandbox_mode.value,+ },+ )++async def _render_html(marimo_path: MarimoPath,*,@@ -276,8 +355,9 @@ async def _generate_thumbnails(execute: bool,notebook_args: tuple[str, ...],continue_on_error: bool,- sandbox: bool,+ sandbox_mode: SandboxMode | None,) -> None:+ from marimo._cli.sandbox import SandboxModefrom marimo._metadata.opengraph import default_opengraph_imagefailures: list[tuple[MarimoPath, Exception]] = []@@ -298,7 +378,9 @@ async def _generate_thumbnails() from Noneraise- if sandbox and not DependencyManager.which("uv"):+ 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"@@ -307,7 +389,7 @@ async def _generate_thumbnails(static_dir = marimo_package_path() / "_static"sandbox_pool: _SandboxVenvPool | None = (- _SandboxVenvPool() if sandbox else None+ _SandboxVenvPool() if use_per_notebook_sandbox else None)try:with _ThumbnailAssetServer(directory=static_dir) as server:@@ -507,6 +589,38 @@ def thumbnail(args: tuple[str, ...],) -> None:"""Generate thumbnails for one or more notebooks (or directories)."""+ paths, notebook_args = _split_paths_and_args(str(name), args)+ path_targets = [Path(p) for p in paths]+ notebooks = _collect_notebooks(path_targets)+ if not notebooks:+ raise click.ClickException("No marimo notebooks found.")+ if output is not None and len(notebooks) > 1:+ raise click.UsageError(+ "--output can only be used when generating thumbnail for a single notebook."+ )++ if not execute and sandbox:+ raise click.UsageError("--sandbox requires --execute.")++ sandbox_mode = _resolve_thumbnail_sandbox_mode(+ execute=execute,+ sandbox=sandbox,+ path_targets=path_targets,+ first_target=str(name),+ )++ if (+ execute+ and sandbox_mode is not None+ and _sandbox_mode_from_env() is None+ ):+ _bootstrap_thumbnail_sandbox(+ args=sys.argv[1:],+ name=str(name),+ sandbox_mode=sandbox_mode,+ )+ return+try:DependencyManager.playwright.require("for thumbnail generation")except ModuleNotFoundError as e:@@ -520,25 +634,6 @@ def thumbnail() from Noneraise- notebooks = _collect_notebooks([Path(name)])- if not notebooks:- raise click.ClickException("No marimo notebooks found.")- if output is not None and len(notebooks) > 1:- raise click.UsageError(- "--output can only be used when generating thumbnail for a single notebook."- )-- from marimo._cli.sandbox import resolve_sandbox_mode-- if not execute and sandbox:- raise click.UsageError("--sandbox requires --execute.")-- sandbox_mode = (- resolve_sandbox_mode(sandbox=sandbox, name=str(name))- if execute- else None- )-asyncio_run(_generate_thumbnails(notebooks=notebooks,@@ -550,8 +645,8 @@ def thumbnail(overwrite=overwrite,include_code=include_code,execute=execute,- notebook_args=args,+ notebook_args=notebook_args,continue_on_error=continue_on_error,- sandbox=sandbox_mode is not None,+ sandbox_mode=sandbox_mode,))diff --git a/marimo/_cli/sandbox.py b/marimo/_cli/sandbox.pyindex 9f47fc73d9..5556c1ea43 100644--- a/marimo/_cli/sandbox.py+++ b/marimo/_cli/sandbox.py@@ -411,6 +411,7 @@ def run_in_sandbox(name: Optional[str] = None,additional_features: Optional[list[DepFeatures]] = None,additional_deps: Optional[list[str]] = None,+ extra_env: Optional[dict[str, str]] = None,) -> int:"""Run marimo in a sandboxed uv environment.@@ -438,6 +439,8 @@ def run_in_sandbox(env = os.environ.copy()env["MARIMO_MANAGE_SCRIPT_METADATA"] = "true"+ if extra_env:+ env.update(extra_env)process = subprocess.Popen(uv_cmd, env=env)diff --git a/tests/_cli/test_cli_export_thumbnail.py b/tests/_cli/test_cli_export_thumbnail.pynew file mode 100644index 0000000000..448e88a377--- /dev/null+++ b/tests/_cli/test_cli_export_thumbnail.py@@ -0,0 +1,230 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import os+from typing import TYPE_CHECKING+from unittest.mock import AsyncMock, patch++from click.testing import CliRunner++import marimo._cli.export.thumbnail as thumbnail_module+from marimo._cli.sandbox import SandboxMode++if TYPE_CHECKING:+ from pathlib import Path+++def _write_notebook(path: Path) -> None:+ path.write_text(+ """+import marimo++app = marimo.App()++def _():+ return++if __name__ == "__main__":+ app.run()+""",+ encoding="utf-8",+ )+++def test_thumbnail_sandbox_single_bootstrap_adds_playwright(+ tmp_path: Path,+) -> None:+ notebook = tmp_path / "notebook.py"+ _write_notebook(notebook)+ runner = CliRunner()++ captured: dict[str, str | list[str] | None] = {}++ def _fake_run_in_sandbox(+ args: list[str],+ *,+ name: str | None = None,+ additional_features: list[str] | None = None,+ additional_deps: list[str] | None = None,+ extra_env: dict[str, str] | None = None,+ ) -> int:+ del args+ del additional_features+ captured["name"] = name+ captured["deps"] = additional_deps+ captured["mode"] = (extra_env or {}).get(+ thumbnail_module._sandbox_mode_env+ )+ captured["bootstrapped"] = (extra_env or {}).get(+ thumbnail_module._sandbox_bootstrapped_env+ )+ return 0++ with (+ patch(+ "marimo._cli.sandbox.run_in_sandbox",+ side_effect=_fake_run_in_sandbox,+ ) as run_in_sandbox,+ patch(+ "marimo._cli.sandbox.resolve_sandbox_mode",+ return_value=SandboxMode.SINGLE,+ ),+ patch.object(+ thumbnail_module.DependencyManager.playwright, "require"+ ) as playwright_require,+ ):+ result = runner.invoke(+ thumbnail_module.thumbnail,+ [str(notebook), "--execute", "--sandbox"],+ )++ assert result.exit_code == 0, result.output+ run_in_sandbox.assert_called_once()+ playwright_require.assert_not_called()+ assert captured["name"] == str(notebook)+ assert captured["deps"] == ["playwright"]+ assert captured["mode"] == SandboxMode.SINGLE.value+ assert captured["bootstrapped"] == "1"+ assert thumbnail_module._sandbox_bootstrapped_env not in os.environ+ assert thumbnail_module._sandbox_mode_env not in os.environ+++def test_thumbnail_sandbox_multi_bootstrap_sets_multi_mode(+ tmp_path: Path,+) -> None:+ first = tmp_path / "first.py"+ second = tmp_path / "second.py"+ _write_notebook(first)+ _write_notebook(second)+ runner = CliRunner()++ captured: dict[str, str | list[str] | None] = {}++ def _fake_run_in_sandbox(+ args: list[str],+ *,+ name: str | None = None,+ additional_features: list[str] | None = None,+ additional_deps: list[str] | None = None,+ extra_env: dict[str, str] | None = None,+ ) -> int:+ del args+ del additional_features+ captured["name"] = name+ captured["deps"] = additional_deps+ captured["mode"] = (extra_env or {}).get(+ thumbnail_module._sandbox_mode_env+ )+ return 0++ with (+ patch(+ "marimo._cli.sandbox.run_in_sandbox",+ side_effect=_fake_run_in_sandbox,+ ) as run_in_sandbox,+ patch("marimo._cli.sandbox.resolve_sandbox_mode") as resolve_mode,+ patch.object(+ thumbnail_module.DependencyManager.playwright, "require"+ ) as playwright_require,+ ):+ result = runner.invoke(+ thumbnail_module.thumbnail,+ [str(first), str(second), "--execute", "--sandbox"],+ )++ assert result.exit_code == 0, result.output+ run_in_sandbox.assert_called_once()+ resolve_mode.assert_not_called()+ playwright_require.assert_not_called()+ assert captured["name"] == str(first)+ assert captured["deps"] == ["playwright"]+ assert captured["mode"] == SandboxMode.MULTI.value+++def test_thumbnail_sandbox_requires_execute(tmp_path: Path) -> None:+ notebook = tmp_path / "notebook.py"+ _write_notebook(notebook)+ runner = CliRunner()++ result = runner.invoke(+ thumbnail_module.thumbnail,+ [str(notebook), "--sandbox"],+ )++ assert result.exit_code != 0+ assert "--sandbox requires --execute." in result.output+++def test_thumbnail_reentry_single_skips_bootstrap(+ tmp_path: Path,+ monkeypatch,+) -> None:+ notebook = tmp_path / "notebook.py"+ _write_notebook(notebook)+ runner = CliRunner()+ generate = AsyncMock()++ monkeypatch.setenv(thumbnail_module._sandbox_bootstrapped_env, "1")+ monkeypatch.setenv(+ thumbnail_module._sandbox_mode_env,+ SandboxMode.SINGLE.value,+ )++ with (+ patch("marimo._cli.sandbox.run_in_sandbox") as run_in_sandbox,+ patch("marimo._cli.sandbox.resolve_sandbox_mode") as resolve_mode,+ patch.object(+ thumbnail_module.DependencyManager.playwright, "require"+ ) as playwright_require,+ patch.object(thumbnail_module, "_generate_thumbnails", new=generate),+ ):+ result = runner.invoke(+ thumbnail_module.thumbnail,+ [str(notebook), "--execute"],+ )++ assert result.exit_code == 0, result.output+ run_in_sandbox.assert_not_called()+ resolve_mode.assert_not_called()+ playwright_require.assert_called_once_with("for thumbnail generation")+ generate.assert_called_once()+ assert generate.call_args.kwargs["sandbox_mode"] is SandboxMode.SINGLE+++def test_thumbnail_reentry_multi_skips_bootstrap(+ tmp_path: Path,+ monkeypatch,+) -> None:+ first = tmp_path / "first.py"+ second = tmp_path / "second.py"+ _write_notebook(first)+ _write_notebook(second)+ runner = CliRunner()+ generate = AsyncMock()++ monkeypatch.setenv(thumbnail_module._sandbox_bootstrapped_env, "1")+ monkeypatch.setenv(+ thumbnail_module._sandbox_mode_env,+ SandboxMode.MULTI.value,+ )++ with (+ patch("marimo._cli.sandbox.run_in_sandbox") as run_in_sandbox,+ patch("marimo._cli.sandbox.resolve_sandbox_mode") as resolve_mode,+ patch.object(+ thumbnail_module.DependencyManager.playwright, "require"+ ) as playwright_require,+ patch.object(thumbnail_module, "_generate_thumbnails", new=generate),+ ):+ result = runner.invoke(+ thumbnail_module.thumbnail,+ [str(first), str(second), "--execute"],+ )++ assert result.exit_code == 0, result.output+ run_in_sandbox.assert_not_called()+ resolve_mode.assert_not_called()+ playwright_require.assert_called_once_with("for thumbnail generation")+ generate.assert_called_once()+ assert generate.call_args.kwargs["sandbox_mode"] is SandboxMode.MULTI