Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 27 additions & 19 deletions marimo/_server/api/lifespans.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,11 @@
from marimo._server.uvicorn_utils import close_uvicorn
from marimo._server.workspace import NEW_FILE
from marimo._session.model import SessionMode
from marimo._utils.asyncio_utils import cancel_and_wait, supervised_task
from marimo._utils.asyncio_utils import (
cancel_and_wait,
running_task,
supervised_task,
)
from marimo._utils.subprocess import cancel_pending_reaps

if TYPE_CHECKING:
Expand Down Expand Up @@ -159,26 +163,30 @@ async def background_connect_mcp_servers() -> MCPClient | None:
@contextlib.asynccontextmanager
async def open_browser(app: Starlette) -> AsyncIterator[None]:
state = AppState.from_app(app)
if not state.headless:
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.
if state.headless:
yield
return

url = _startup_url(state)
browser = state.config_manager.get_config().server.browser
server = state.server

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)

async def launch_when_listening() -> None:
# Uvicorn binds the listener after all ASGI startup hooks finish.
while not server.started: # noqa: ASYNC110 (Uvicorn exposes no readiness event)
await asyncio.sleep(0.02)
if not server.should_exit:
# Desktop browser discovery can block even during shutdown.
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, launch)
yield
async with running_task(launch_when_listening()):
yield


@contextlib.asynccontextmanager
Expand Down
29 changes: 29 additions & 0 deletions tests/_server/api/test_api_lifespans.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ async def run_lifespan() -> None:
async def test_browser_launch_does_not_block_event_loop_or_lifespan() -> None:
state = MagicMock()
state.headless = False
state.server.started = True
state.server.should_exit = False
state.config_manager.get_config.return_value = MarimoConfig()
loop = asyncio.get_running_loop()
started = asyncio.Event()
Expand Down Expand Up @@ -94,6 +96,33 @@ def blocked_launch(_browser: str, _url: str) -> None:
launch.assert_called_once_with("default", "http://localhost:2718")


async def test_browser_waits_until_server_is_listening() -> None:
state = MagicMock()
state.headless = False
state.server.started = False
state.server.should_exit = False
loop = asyncio.get_running_loop()
opened = asyncio.Event()

with (
patch.object(lifespans.AppState, "from_app", return_value=state),
patch.object(
lifespans, "_startup_url", return_value="http://localhost"
),
patch.object(
lifespans,
"open_url_in_browser",
side_effect=lambda *_: loop.call_soon_threadsafe(opened.set),
) as launch,
):
async with lifespans.open_browser(MagicMock()):
with pytest.raises(asyncio.TimeoutError):
await asyncio.wait_for(opened.wait(), timeout=0.1)
state.server.started = True
await asyncio.wait_for(opened.wait(), timeout=1)
launch.assert_called_once()


async def test_cleanup_mcp_task_disconnects_client() -> None:
mcp_client = MagicMock()
mcp_client.disconnect_from_all_servers = AsyncMock()
Expand Down
Loading