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
fix(sandbox): tidy missing-backend error, empty notebook, and double close (#10954)
Dylan Madisetti2cfe2b11bc2e
diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.pyindex 84bae8a51b..85c9b8e979 100644--- a/marimo/_cli/cli.py+++ b/marimo/_cli/cli.py@@ -476,7 +476,11 @@ def edit(name: str | None,args: tuple[str, ...],) -> None:- from marimo._cli.sandbox import ensure_server_environment, resolve_sandbox+ from marimo._cli.sandbox import (+ ensure_server_environment,+ require_sandbox_backend,+ resolve_sandbox,+ )stdin_notebook = Nonepass_on_stdin = token_password_file == "-"@@ -523,6 +527,19 @@ def edit(else:check_app_correctness(name)elif not is_dir:+ # A new notebook has no inline metadata, so the sandbox choice+ # comes from the flags alone. Check the backend first so a+ # missing uv/pixi does not leave an empty file behind.+ new_notebook_backend = resolve_sandbox(+ sandbox=sandbox, no_sandbox=no_sandbox, name=None+ )+ if new_notebook_backend is not None:+ from marimo._environments.errors import EnvironmentManagerError++ try:+ require_sandbox_backend(new_notebook_backend)+ except EnvironmentManagerError as error:+ raise MarimoCLIRuntimeError(str(error)) from error# write empty filetry:with open(name, "w", encoding="utf-8"):diff --git a/marimo/_cli/sandbox.py b/marimo/_cli/sandbox.pyindex a402969b93..bf2b4e4487 100644--- a/marimo/_cli/sandbox.py+++ b/marimo/_cli/sandbox.py@@ -411,9 +411,11 @@ def require_sandbox_backend(backend: SandboxBackend) -> None:if backend == "pixi"else "https://docs.astral.sh/uv/getting-started/installation/")+ # uv and pixi are standalone tools, not Python packages, so skip the+ # generic `pip install <package>` hint and point at their installers.raise MarimoCLIMissingDependencyError(f"{backend} must be installed to use {option}.",- backend,+ [],additional_tip=f"Install {backend} from {install_url}",) from ediff --git a/marimo/_server/api/endpoints/ws_endpoint.py b/marimo/_server/api/endpoints/ws_endpoint.pyindex 85b9750c5a..77f814004a 100644--- a/marimo/_server/api/endpoints/ws_endpoint.py+++ b/marimo/_server/api/endpoints/ws_endpoint.py@@ -298,6 +298,12 @@ class WebSocketHandler(SessionHandler):websocket in that state raises `AttributeError`. The connectionis cleaned up when the handler returns regardless."""+ if self.websocket.client_state is WebSocketState.DISCONNECTED:+ # The client already closed the transport (for example, it+ # navigated away while the kernel was still starting). Sending+ # another close would make uvicorn raise+ # "Unexpected ASGI message 'websocket.close'".+ returntry:await self.websocket.close(code, reason)except WebSocketDisconnect:diff --git a/tests/_cli/test_sandbox.py b/tests/_cli/test_sandbox.pyindex d8a2eaf4e1..f0b93e2d15 100644--- a/tests/_cli/test_sandbox.py+++ b/tests/_cli/test_sandbox.py@@ -32,7 +32,33 @@ def test_missing_sandbox_backend_reports_install_instructions(with pytest.raises(MarimoCLIMissingDependencyError) as error:run_in_sandbox(["edit", "--sandbox", "notebook.py"], backend=backend)- assert f"{backend} must be installed" in str(error.value)+ message = str(error.value)+ assert f"{backend} must be installed" in message+ assert f"Install {backend} from" in message+ # uv and pixi are standalone tools; a pip hint would be misleading.+ assert "pip install" not in message++[email protected]("backend", ["uv", "pixi"])+def test_missing_sandbox_backend_does_not_create_new_notebook(+ backend: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from click.testing import CliRunner++ from marimo._cli.cli import edit++ monkeypatch.delenv("UV", raising=False)+ monkeypatch.setenv("PATH", str(tmp_path))+ monkeypatch.chdir(tmp_path)+ notebook = tmp_path / "new_notebook.py"++ result = CliRunner().invoke(+ edit, [f"--sandbox={backend}", "--headless", str(notebook)]+ )++ assert result.exit_code != 0+ assert f"{backend} must be installed" in result.output+ assert not notebook.exists()def test_dependency_export_uses_notebook_directory(diff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.pyindex 570374dde1..567af19a5d 100644--- a/tests/_server/api/endpoints/test_ws.py+++ b/tests/_server/api/endpoints/test_ws.py@@ -8,7 +8,7 @@ from typing import TYPE_CHECKING, Anyfrom unittest.mock import AsyncMock, MagicMock, patchimport pytest-from starlette.websockets import WebSocketDisconnect+from starlette.websockets import WebSocketDisconnect, WebSocketStatefrom marimo._config.config import ExperimentalConfigfrom marimo._config.manager import UserConfigManager@@ -57,6 +57,36 @@ def test_ws(client: TestClient) -> None:assert_kernel_ready_response(data)[email protected]("client_state", list(WebSocketState))+async def test_safe_close_skips_a_client_that_already_disconnected(+ client_state: WebSocketState,+) -> None:+ websocket = MagicMock()+ websocket.close = AsyncMock()+ websocket.client_state = client_state+ handler = WebSocketHandler(+ websocket=websocket,+ manager=MagicMock(),+ params=ConnectionParams(+ session_id=SessionId("s1"),+ file_key="test.py",+ kiosk=False,+ auto_instantiate=False,+ rtc_enabled=False,+ ),+ mode=SessionMode.RUN,+ )++ await handler._safe_close(WebSocketCodes.NORMAL_CLOSE, "")++ if client_state is WebSocketState.DISCONNECTED:+ # Closing again would make uvicorn raise+ # "Unexpected ASGI message 'websocket.close'".+ websocket.close.assert_not_awaited()+ else:+ websocket.close.assert_awaited_once()++@pytest.mark.parametrize("failure", ["disconnect", "cancel"])async def test_failed_startup_progress_delivery_detaches_session(failure: str,