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(runtime): defer browser discovery until a cell uses webbrowser (#10887)
Kiran Gadhave8be967df1dae
diff --git a/marimo/_runtime/marimo_browser.py b/marimo/_runtime/marimo_browser.pyindex 776bbc1c7e..9dc521223f 100644--- a/marimo/_runtime/marimo_browser.py+++ b/marimo/_runtime/marimo_browser.py@@ -1,8 +1,6 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations-import webbrowser-from marimo._runtime.context import get_contextfrom marimo._runtime.context.types import ContextNotInitializedError@@ -75,19 +73,3 @@ def browser_open_fallback())return True---def build_browser_fallback() -> type[webbrowser.BaseBrowser]:- """- Dynamically create the class since BaseBrowser does not exist in- pyodide.- """-- # Construct like this to limit stack frames.- MarimoBrowser = type(- "MarimoBrowser",- (webbrowser.BaseBrowser,),- {"open": staticmethod(browser_open_fallback)},- )-- return MarimoBrowserdiff --git a/marimo/_runtime/patches.py b/marimo/_runtime/patches.pyindex 1803ed0c1f..2713c96852 100644--- a/marimo/_runtime/patches.py+++ b/marimo/_runtime/patches.py@@ -34,23 +34,33 @@ def patch_pdb(debugger: marimo_pdb.MarimoPdb) -> None:def patch_webbrowser() -> None:+ """Fall back to notebook output when `webbrowser.open()` fails."""import webbrowser- try:- _ = webbrowser.get()- # pyodide doesn't have a webbrowser.get() method- # (nor a webbrowser.Error, so careful)- except AttributeError:+ # Pyodide ships a stub module without browser controllers.+ if not hasattr(webbrowser, "get"):webbrowser.open = marimo_browser.browser_open_fallback- except webbrowser.Error:- MarimoBrowser = marimo_browser.build_browser_fallback()- webbrowser.register(- "marimo-output",- None,- MarimoBrowser(),- preferred=True,+ return++ if getattr(webbrowser.open, "_marimo_patched", False):+ return++ original_open = webbrowser.open++ # Discovery can block on a stalled desktop, so defer it until use.+ @functools.wraps(original_open)+ def open_with_fallback(+ url: str, new: int = 0, autoraise: bool = True+ ) -> bool:+ if original_open(url, new=new, autoraise=autoraise):+ return True+ return marimo_browser.browser_open_fallback(+ url, new=new, autoraise=autoraise)+ open_with_fallback._marimo_patched = True # type: ignore[attr-defined]+ webbrowser.open = open_with_fallback+def patch_sys_module(module: types.ModuleType) -> None:sys.modules[module.__name__] = modulediff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 486b4f45d6..0d49f08ff2 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -650,9 +650,9 @@ class Kernel:import getpassgetpass.getpass = getpass_override- # Webbrowser may not be set (e.g. docker container) or stubbed/broken- # (e.g. in pyodide). Set default to just inject an iframe of the- # expected page to output.+ # Route webbrowser.open() to an iframe in the cell output when the+ # browser cannot launch or the module is a stub (Pyodide).+ # Browser discovery runs on first use, never at startup.patches.patch_webbrowser()# micropip only patched in non-pyodide environments.if not is_pyodide():diff --git a/marimo/_server/api/lifespans.py b/marimo/_server/api/lifespans.pyindex f118aae05e..f6b90980ca 100644--- a/marimo/_server/api/lifespans.py+++ b/marimo/_server/api/lifespans.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport asyncioimport contextlib+import threadingfrom typing import TYPE_CHECKING, Anyfrom marimo import _loggers@@ -162,11 +163,21 @@ async def open_browser(app: Starlette) -> AsyncIterator[None]:url = _startup_url(state)user_config = state.config_manager.get_config()browser = user_config["server"]["browser"]++ def open_and_log() -> None:+ try:+ open_url_in_browser(browser, url)+ except Exception as e:+ LOGGER.warning("Failed to open the browser: %s", e)++ def launch() -> None:+ # Browser discovery can block for a long time on a stalled+ # desktop (seen in WSL). Keep it off the event loop.+ threading.Thread(target=open_and_log, daemon=True).start()+# Wait 20ms for the server to start and then open the browser, but this# function must complete- asyncio.get_running_loop().call_later(- 0.02, open_url_in_browser, browser, url- )+ asyncio.get_running_loop().call_later(0.02, launch)yielddiff --git a/marimo/_server/api/utils.py b/marimo/_server/api/utils.pyindex fc639de065..f764a731e8 100644--- a/marimo/_server/api/utils.py+++ b/marimo/_server/api/utils.py@@ -1,7 +1,6 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations-import osimport subprocessimport sysimport webbrowser@@ -233,19 +232,13 @@ def open_url_in_browser(browser: str, url: str) -> None:Open a browser to the given URL."""if which("xdg-open") is not None and browser == "default":- if (- sys.platform == "win32"- or sys.platform == "cygwin"- or sys.implementation.name == "graalpy"- ):- preexec_fn = None- else:- preexec_fn = os.setpgrpsubprocess.Popen(["xdg-open", url],- # don't forward signals: ctrl-c shouldn't kill the browser- # TODO: test/workaround on windows- preexec_fn=preexec_fn,+ # Keep Ctrl-C from reaching the browser.+ start_new_session=(+ sys.platform not in {"win32", "cygwin"}+ and sys.implementation.name != "graalpy"+ ),stdout=subprocess.DEVNULL,stderr=subprocess.STDOUT,)diff --git a/tests/_runtime/test_patches.py b/tests/_runtime/test_patches.pyindex 6c2cb56b8f..13e011cd91 100644--- a/tests/_runtime/test_patches.py+++ b/tests/_runtime/test_patches.py@@ -1,19 +1,27 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations+import inspectimport io+import sys+import threading+import time+import webbrowserfrom contextlib import nullcontextfrom typing import TYPE_CHECKINGfrom unittest.mock import patchimport pytest+from marimo._runtime import marimo_browserfrom marimo._runtime._wasm._patches import WasmPatchSetfrom marimo._runtime._wasm._polars import patch_polars_for_wasmfrom marimo._runtime.capture import capture_stderr+from marimo._runtime.patches import patch_webbrowserfrom marimo._runtime.runtime import Kernelfrom marimo._utils.platform import is_pyodide-from tests._messaging.mocks import MockStream+from tests._runtime._helpers.session import mocked_kernel_session+from tests._runtime._helpers.streams import MockStreamfrom tests.conftest import ExecReqProvider, mock_pyodideif TYPE_CHECKING:@@ -149,65 +157,6 @@ class TestMicropip:TestMicropip._assert_micropip_warning_printed(buf.getvalue())-async def test_webbrowser_injection(- mocked_kernel: Kernel, exec_req: ExecReqProvider-):- await mocked_kernel.k.run(- [- exec_req.get("""- import webbrowser- MarimoBrowser = __marimo__._runtime.marimo_browser.build_browser_fallback()- webbrowser.register(- "marimo-output", None, MarimoBrowser(), preferred=True- )- """),- ]- )- await mocked_kernel.k.run(- [- cell := exec_req.get("webbrowser.open('https://marimo.io');"),- ]- )- assert "webbrowser" in mocked_kernel.k.globals- outputs: list[str] = []- stream = MockStream(mocked_kernel.stream)- for msg in stream.operations:- if msg["op"] == "cell-op" and msg["output"] is not None:- outputs.append(msg["output"]["data"])-- assert "<iframe" in outputs[-1]---async def test_webbrowser_easter_egg(- mocked_kernel: Kernel, exec_req: ExecReqProvider-):- await mocked_kernel.k.run(- [- exec_req.get("""- import webbrowser- MarimoBrowser = __marimo__._runtime.marimo_browser.build_browser_fallback()- webbrowser.register(- "marimo-output", None, MarimoBrowser(), preferred=True- )- """),- ]- )- await mocked_kernel.k.run(- [- cell := exec_req.get("import antigravity;"),- ]- )- assert "antigravity" in mocked_kernel.k.globals- outputs: list[str] = []- stream = MockStream(mocked_kernel.stream)- for msg in stream.operations:- if msg["op"] == "cell-op" and msg["output"] is not None:- outputs.append(msg["output"]["data"])-- assert "<iframe" not in outputs[-1]- assert "<img" in outputs[-1]--@pytest.mark.requires("polars")@mock_pyodide()def test_polars_write_json_patch(tmp_path: Path):@@ -510,3 +459,230 @@ class TestPolarsIoWasmPatch:assert exc_info.value.name == "pyarrow"finally:unpatch()+++def _reset_webbrowser(monkeypatch: pytest.MonkeyPatch) -> None:+ # CPython caches discovery per process. Start every test cold, and+ # restore the real module functions on teardown.+ monkeypatch.setattr(webbrowser, "_tryorder", None)+ monkeypatch.setattr(webbrowser, "_browsers", {})+ monkeypatch.setattr(webbrowser, "open", inspect.unwrap(webbrowser.open))+++def _discovery_finds_nothing() -> None:+ # Same end state as CPython when no browser is runnable.+ webbrowser._tryorder = []+++def _cell_outputs(stream: MockStream) -> list[str]:+ return [+ msg["output"]["data"]+ for msg in stream.raw_operations+ if msg["op"] == "cell-op" and msg["output"] is not None+ ]+++class TestWebbrowserStartup:+ @staticmethod+ def test_kernel_start_does_not_probe(+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ _reset_webbrowser(monkeypatch)+ probes: list[int] = []++ def counting_discovery() -> None:+ probes.append(1)+ webbrowser._tryorder = []++ monkeypatch.setattr(+ webbrowser, "register_standard_browsers", counting_discovery+ )++ with mocked_kernel_session():+ assert probes == []++ @staticmethod+ @pytest.mark.parametrize("discovered", [False, True])+ @pytest.mark.parametrize("method", ["open", "open_new", "open_new_tab"])+ async def test_no_browser_renders_iframe(+ monkeypatch: pytest.MonkeyPatch,+ exec_req: ExecReqProvider,+ method: str,+ discovered: bool,+ ) -> None:+ _reset_webbrowser(monkeypatch)+ monkeypatch.setattr(+ webbrowser, "register_standard_browsers", _discovery_finds_nothing+ )+ if discovered:+ _discovery_finds_nothing()++ with mocked_kernel_session() as tk:+ await tk.kernel.run(+ [+ exec_req.get(+ # The trailing semicolon suppresses the True return+ # value, so the iframe stays the cell output.+ f"import webbrowser; webbrowser.{method}('https://marimo.io');"+ )+ ]+ )+ outputs = _cell_outputs(tk.stream)++ assert "<iframe" in outputs[-1]++ @staticmethod+ async def test_no_browser_antigravity_renders_image(+ monkeypatch: pytest.MonkeyPatch, exec_req: ExecReqProvider+ ) -> None:+ _reset_webbrowser(monkeypatch)+ monkeypatch.setattr(+ webbrowser, "register_standard_browsers", _discovery_finds_nothing+ )+ # antigravity opens the browser only on first import per process.+ # Drop any cached module so the cell import runs the side effect.+ monkeypatch.delitem(sys.modules, "antigravity", raising=False)++ with mocked_kernel_session() as tk:+ await tk.kernel.run([exec_req.get("import antigravity")])+ outputs = _cell_outputs(tk.stream)++ assert "<img" in outputs[-1]+ assert "<iframe" not in outputs[-1]++ @staticmethod+ @pytest.mark.parametrize("launch_succeeds", [False, True])+ async def test_real_browser_falls_back_only_when_launch_fails(+ monkeypatch: pytest.MonkeyPatch,+ exec_req: ExecReqProvider,+ launch_succeeds: bool,+ ) -> None:+ _reset_webbrowser(monkeypatch)+ opened: list[tuple[str, int, bool]] = []++ class FakeBrowser(webbrowser.BaseBrowser):+ def open(+ self, url: str, new: int = 0, autoraise: bool = True+ ) -> bool:+ opened.append((url, new, autoraise))+ return launch_succeeds++ def discovery_finds_fake() -> None:+ # CPython resets the order before it registers what it found.+ webbrowser._tryorder = []+ webbrowser.register("fake", None, FakeBrowser())++ monkeypatch.setattr(+ webbrowser, "register_standard_browsers", discovery_finds_fake+ )++ with mocked_kernel_session() as tk:+ await tk.kernel.run(+ [+ exec_req.get(+ "import webbrowser; "+ "webbrowser.open('https://marimo.io', new=2, autoraise=False);"+ )+ ]+ )+ outputs = _cell_outputs(tk.stream)++ assert opened == [("https://marimo.io", 2, False)]+ assert any("<iframe" in output for output in outputs) is (+ not launch_succeeds+ )++ @staticmethod+ def test_get_keeps_standard_behavior(+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ _reset_webbrowser(monkeypatch)+ monkeypatch.setattr(+ webbrowser, "register_standard_browsers", _discovery_finds_nothing+ )++ patch_webbrowser()++ with pytest.raises(webbrowser.Error):+ webbrowser.get()++ @staticmethod+ def test_no_browser_without_cell_returns_false(+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ _reset_webbrowser(monkeypatch)+ monkeypatch.setattr(+ webbrowser, "register_standard_browsers", _discovery_finds_nothing+ )++ patch_webbrowser()++ assert webbrowser.open("https://marimo.io") is False++ @staticmethod+ def test_pyodide_stub_replaces_open(+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ _reset_webbrowser(monkeypatch)+ monkeypatch.delattr(webbrowser, "get")++ patch_webbrowser()++ assert webbrowser.open is marimo_browser.browser_open_fallback++ @staticmethod+ def test_active_discovery_does_not_block_or_win(+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ _reset_webbrowser(monkeypatch)+ monkeypatch.setattr(+ webbrowser, "register_standard_browsers", _discovery_finds_nothing+ )++ class FakeBrowser(webbrowser.BaseBrowser):+ def open(+ self, url: str, new: int = 0, autoraise: bool = True+ ) -> bool:+ del url, new, autoraise+ return True++ discovery_started = threading.Event()+ release_discovery = threading.Event()++ def stalled_discovery() -> None:+ # Mimic CPython mid-probe: the lock is held and _tryorder is+ # already the transient empty list.+ with webbrowser._lock:+ webbrowser._tryorder = []+ discovery_started.set()+ release_discovery.wait(timeout=5)+ webbrowser.register("real", None, FakeBrowser())++ discovery = threading.Thread(target=stalled_discovery)+ discovery.start()+ assert discovery_started.wait(timeout=5)++ try:+ start = time.monotonic()+ patch_webbrowser()+ elapsed = time.monotonic() - start+ finally:+ release_discovery.set()+ discovery.join(timeout=5)++ assert elapsed < 1.0+ assert webbrowser._tryorder == ["real"]+ assert "marimo-output" not in webbrowser._browsers++ @staticmethod+ def test_patch_is_idempotent(monkeypatch: pytest.MonkeyPatch) -> None:+ _reset_webbrowser(monkeypatch)+ monkeypatch.setattr(+ webbrowser, "register_standard_browsers", _discovery_finds_nothing+ )++ patch_webbrowser()+ first = webbrowser.open+ patch_webbrowser()++ assert webbrowser.open is firstdiff --git a/tests/_server/api/test_api_lifespans.py b/tests/_server/api/test_api_lifespans.pyindex e34307a3c1..915155b20c 100644--- a/tests/_server/api/test_api_lifespans.py+++ b/tests/_server/api/test_api_lifespans.py@@ -1,6 +1,8 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations+import asyncio+import threadingfrom unittest.mock import AsyncMock, MagicMock, patchimport pytest@@ -9,6 +11,47 @@ from marimo._server.api import lifespansfrom marimo._session.model import SessionMode+async def test_browser_launch_does_not_block_event_loop_or_lifespan() -> None:+ state = MagicMock()+ state.headless = False+ state.config_manager.get_config.return_value = {+ "server": {"browser": "default"}+ }+ loop = asyncio.get_running_loop()+ started = asyncio.Event()+ finished = asyncio.Event()+ release = threading.Event()+ threads: list[threading.Thread] = []++ def blocked_launch(_browser: str, _url: str) -> None:+ threads.append(threading.current_thread())+ loop.call_soon_threadsafe(started.set)+ release.wait(timeout=5)+ loop.call_soon_threadsafe(finished.set)++ with (+ patch.object(lifespans.AppState, "from_app", return_value=state),+ patch.object(+ lifespans, "_startup_url", return_value="http://localhost:2718"+ ),+ patch.object(+ lifespans, "open_url_in_browser", side_effect=blocked_launch+ ) as launch,+ ):+ try:+ async with lifespans.open_browser(MagicMock()):+ await asyncio.wait_for(started.wait(), timeout=1)+ assert not finished.is_set()+ assert threads[0].daemon+ assert not finished.is_set()+ finally:+ release.set()+ await asyncio.wait_for(finished.wait(), timeout=1)+ threads[0].join(timeout=1)++ launch.assert_called_once_with("default", "http://localhost:2718")++async def test_cleanup_mcp_task_disconnects_client() -> None:mcp_client = MagicMock()mcp_client.disconnect_from_all_servers = AsyncMock()diff --git a/tests/_server/api/test_api_utils.py b/tests/_server/api/test_api_utils.pyindex 57aee7298e..ad08d2f49f 100644--- a/tests/_server/api/test_api_utils.py+++ b/tests/_server/api/test_api_utils.py@@ -2,6 +2,7 @@from __future__ import annotationsimport asyncio+import subprocessimport threadingfrom types import SimpleNamespacefrom typing import TYPE_CHECKING, cast@@ -18,6 +19,7 @@ from starlette.testclient import TestClientfrom marimo._server.api.utils import (get_code_mode_credentials,install_packages_on_server,+ open_url_in_browser,parse_multipart_request,)@@ -32,6 +34,40 @@ class _SampleForm(msgspec.Struct):count: int+ ("platform", "implementation", "start_new_session"),+ [+ ("linux", "cpython", True),+ ("darwin", "cpython", True),+ ("win32", "cpython", False),+ ("cygwin", "cpython", False),+ ("linux", "graalpy", False),+ ],+)+def test_open_browser_detaches_without_preexec_callback(+ platform: str, implementation: str, start_new_session: bool+) -> None:+ with (+ patch("marimo._server.api.utils.which", return_value="/bin/xdg-open"),+ patch(+ "marimo._server.api.utils.sys",+ SimpleNamespace(+ platform=platform,+ implementation=SimpleNamespace(name=implementation),+ ),+ ),+ patch("marimo._server.api.utils.subprocess.Popen") as popen,+ ):+ open_url_in_browser("default", "http://localhost:2718")++ popen.assert_called_once_with(+ ["xdg-open", "http://localhost:2718"],+ start_new_session=start_new_session,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.STDOUT,+ )++def _build_app(captured: dict[str, object]) -> TestClient:async def endpoint(request: Request) -> JSONResponse:async with parse_multipart_request(request, _SampleForm) as parsed: