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.

fix: running sandbox link in home is broken when launched under subdir (#7764)

Dylan Madisettifae7c9b8b67b
diff --git a/marimo/_server/api/endpoints/home.py b/marimo/_server/api/endpoints/home.py
index 807d99e7dd..b42c8ec3c4 100644
--- a/marimo/_server/api/endpoints/home.py
+++ b/marimo/_server/api/endpoints/home.py
@@ -117,6 +117,10 @@ async def workspace_files(
def _get_active_sessions(app_state: AppState) -> list[MarimoFile]:
+ """Get list of active sessions with prettified paths."""
+ # Get directory from file router for path relativization
+ base_dir = app_state.session_manager.file_router.directory
+
files: list[MarimoFile] = []
for session_id, session in app_state.session_manager.sessions.items():
state = session.connection_state()
@@ -126,7 +130,9 @@ def _get_active_sessions(app_state: AppState) -> list[MarimoFile]:
files.append(
MarimoFile(
name=(basename or "new notebook"),
- path=(pretty_path(filename) if filename else session_id),
+ path=pretty_path(filename, base_dir)
+ if filename
+ else session_id,
last_modified=0,
session_id=session_id,
initialization_id=session.initialization_id,
diff --git a/marimo/_utils/paths.py b/marimo/_utils/paths.py
index 58327c1c28..d98a27041c 100644
--- a/marimo/_utils/paths.py
+++ b/marimo/_utils/paths.py
@@ -19,21 +19,28 @@ def marimo_package_path() -> Path:
return Path(str(import_files("marimo")))
-def pretty_path(filename: str) -> str:
+def pretty_path(filename: str, base_dir: Path | str | None = None) -> str:
"""
- If it's an absolute path, shorten to relative path if
- we don't go outside the current directory.
- Otherwise, return the filename as is.
+ Make a path "pretty" by converting to relative if possible.
+
+ Args:
+ filename: The path to prettify
+ base_dir: If provided, compute relative to this directory first.
+ Falls back to CWD-relative if file is outside base_dir.
+
+ Returns:
+ A shorter, more readable path when possible.
"""
- if os.path.isabs(filename):
- try:
- relpath = os.path.relpath(filename)
- except ValueError:
- # Windows: relpath doesn't work if filename is on a different drive
- # than current drive
- return filename
- if not relpath.startswith(".."):
- return relpath
+ if not filename:
+ return filename
+
+ file_path = Path(filename)
+
+ if base_dir is not None and file_path.is_relative_to(base_dir):
+ return str(file_path.relative_to(base_dir))
+ if file_path.is_absolute() and file_path.is_relative_to(Path.cwd()):
+ return str(file_path.relative_to(Path.cwd()))
+
return filename
diff --git a/tests/_server/api/endpoints/test_home.py b/tests/_server/api/endpoints/test_home.py
index 075695a453..503cecc001 100644
--- a/tests/_server/api/endpoints/test_home.py
+++ b/tests/_server/api/endpoints/test_home.py
@@ -1,7 +1,10 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+import inspect
+import os
import sys
+import tempfile
from typing import TYPE_CHECKING
import pytest
@@ -142,3 +145,205 @@ def test_tutorial_file_accessible_after_open(client: TestClient) -> None:
file_manager = session_manager.app_manager(tutorial_path)
assert file_manager is not None
assert file_manager.path == tutorial_path
+
+
+@with_session(SESSION_ID)
+def test_running_notebooks_returns_relative_paths(client: TestClient) -> None:
+ """Test that running_notebooks returns paths relative to file router directory.
+
+ This is a regression test for the bug where `marimo edit subdirectory`
+ would return paths like `subdirectory/notebook.py` instead of `notebook.py`.
+ """
+ from marimo._server.file_router import LazyListOfFilesAppFileRouter
+
+ session_manager = get_session_manager(client)
+
+ # Create a temp directory structure: /tmp/xxx/subdir/notebook.py
+ with tempfile.TemporaryDirectory() as tmp_base:
+ subdir = os.path.join(tmp_base, "subdir")
+ os.makedirs(subdir)
+
+ # Create a notebook file in the subdirectory
+ notebook_path = os.path.join(subdir, "notebook.py")
+ content = inspect.cleandoc(
+ """
+ import marimo
+ app = marimo.App()
+
+ @app.cell
+ def __():
+ return
+
+ if __name__ == "__main__":
+ app.run()
+ """
+ )
+ with open(notebook_path, "w") as f:
+ f.write(content)
+
+ # Create a file router pointing to the subdirectory
+ # This simulates `marimo edit subdir`
+ file_router = LazyListOfFilesAppFileRouter(
+ subdir, include_markdown=False
+ )
+
+ # Replace the session manager's file router
+ original_file_router = session_manager.file_router
+ session_manager.file_router = file_router
+
+ # Update the session's filename to the absolute path of the notebook
+ session = session_manager.get_session(SESSION_ID)
+ assert session is not None
+ original_filename = session.app_file_manager.filename
+ session.app_file_manager.filename = notebook_path
+
+ try:
+ response = client.post(
+ "/api/home/running_notebooks",
+ headers=HEADERS,
+ )
+ body = response.json()
+ files = body["files"]
+
+ assert len(files) == 1
+ # The path should be relative to the subdirectory, not the CWD
+ # i.e., "notebook.py" not "subdir/notebook.py"
+ assert files[0]["path"] == "notebook.py"
+ assert files[0]["name"] == "notebook.py"
+ finally:
+ # Restore original state
+ session_manager.file_router = original_file_router
+ session.app_file_manager.filename = original_filename
+
+
[email protected](sys.platform == "win32", reason="Failing on Windows CI")
+@with_session(SESSION_ID, auto_shutdown=False)
+def test_shutdown_session_returns_relative_paths(client: TestClient) -> None:
+ """Test that shutdown_session returns paths relative to file router directory."""
+ from marimo._server.file_router import LazyListOfFilesAppFileRouter
+
+ session_manager = get_session_manager(client)
+
+ # Create a second session to test shutdown returns correct paths
+ # for remaining sessions
+ with tempfile.TemporaryDirectory() as tmp_base:
+ subdir = os.path.join(tmp_base, "subdir")
+ os.makedirs(subdir)
+
+ notebook_path = os.path.join(subdir, "notebook.py")
+ content = inspect.cleandoc(
+ """
+ import marimo
+ app = marimo.App()
+
+ @app.cell
+ def __():
+ return
+
+ if __name__ == "__main__":
+ app.run()
+ """
+ )
+ with open(notebook_path, "w") as f:
+ f.write(content)
+
+ file_router = LazyListOfFilesAppFileRouter(
+ subdir, include_markdown=False
+ )
+
+ original_file_router = session_manager.file_router
+ session_manager.file_router = file_router
+
+ session = session_manager.get_session(SESSION_ID)
+ assert session is not None
+ original_filename = session.app_file_manager.filename
+ session.app_file_manager.filename = notebook_path
+
+ try:
+ # Shutdown the session - response should have empty files
+ # since we're shutting down the only session
+ response = client.post(
+ "/api/home/shutdown_session",
+ headers=HEADERS,
+ json={"sessionId": SESSION_ID},
+ )
+ assert response.status_code == 200
+ # After shutdown, no sessions remain
+ assert response.json() == {"files": []}
+ finally:
+ session_manager.file_router = original_file_router
+ # Note: session is already shut down, so we don't restore filename
+
+
+def test_running_notebooks_handles_files_outside_directory(
+ client: TestClient,
+) -> None:
+ """Test that files outside the directory still get pretty_path treatment."""
+ from marimo._server.file_router import LazyListOfFilesAppFileRouter
+
+ session_manager = get_session_manager(client)
+ auth_token = session_manager.auth_token
+ headers = token_header(auth_token)
+
+ # Connect a session
+ with client.websocket_connect(
+ f"/ws?session_id={SESSION_ID}", headers=headers
+ ) as websocket:
+ data = websocket.receive_text()
+ assert data
+
+ # Create two separate temp directories
+ with tempfile.TemporaryDirectory() as router_dir:
+ with tempfile.TemporaryDirectory() as file_dir:
+ # Create a notebook in file_dir (outside router_dir)
+ notebook_path = os.path.join(file_dir, "outside.py")
+ content = inspect.cleandoc(
+ """
+ import marimo
+ app = marimo.App()
+
+ @app.cell
+ def __():
+ return
+
+ if __name__ == "__main__":
+ app.run()
+ """
+ )
+ with open(notebook_path, "w") as f:
+ f.write(content)
+
+ # Set up file router pointing to router_dir
+ file_router = LazyListOfFilesAppFileRouter(
+ router_dir, include_markdown=False
+ )
+
+ original_file_router = session_manager.file_router
+ session_manager.file_router = file_router
+
+ session = session_manager.get_session(SESSION_ID)
+ assert session is not None
+ original_filename = session.app_file_manager.filename
+ session.app_file_manager.filename = notebook_path
+
+ try:
+ response = client.post(
+ "/api/home/running_notebooks",
+ headers=HEADERS,
+ )
+ body = response.json()
+ files = body["files"]
+
+ assert len(files) == 1
+ # File is outside directory, so it should use pretty_path
+ # which returns the path as-is or relative to CWD
+ # The important thing is it doesn't crash
+ assert files[0]["name"] == "outside.py"
+ # Path should contain the filename (exact path depends on CWD)
+ assert "outside.py" in files[0]["path"]
+ finally:
+ session_manager.file_router = original_file_router
+ session.app_file_manager.filename = original_filename
+
+ # Shutdown to clean up
+ client.post("/api/kernel/shutdown", headers=headers)
diff --git a/tests/_utils/test_paths.py b/tests/_utils/test_paths.py
index cc4e5ce244..046c8004b4 100644
--- a/tests/_utils/test_paths.py
+++ b/tests/_utils/test_paths.py
@@ -1,12 +1,13 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+import os
import tempfile
from pathlib import Path
import pytest
-from marimo._utils.paths import normalize_path
+from marimo._utils.paths import normalize_path, pretty_path
def test_normalize_path_makes_absolute() -> None:
@@ -79,3 +80,94 @@ def test_normalize_path_does_not_resolve_symlinks() -> None:
# They should be different
assert normalized != resolved
+
+
+class TestPrettyPath:
+ """Tests for pretty_path function."""
+
+ def test_empty_filename_returns_empty(self) -> None:
+ """Test that empty string returns empty string."""
+ assert pretty_path("") == ""
+
+ def test_relative_path_unchanged(self) -> None:
+ """Test that relative paths are returned unchanged."""
+ assert pretty_path("foo/bar.py") == "foo/bar.py"
+
+ def test_absolute_path_inside_cwd_becomes_relative(self) -> None:
+ """Test that absolute paths inside CWD become relative."""
+ cwd = Path.cwd()
+ abs_path = str(cwd / "subdir" / "file.py")
+ result = pretty_path(abs_path)
+ # Should be relative to CWD
+ assert result == os.path.join("subdir", "file.py")
+
+ def test_absolute_path_outside_cwd_stays_absolute(self) -> None:
+ """Test that absolute paths outside CWD stay absolute."""
+ with tempfile.TemporaryDirectory() as tmp:
+ # This is outside CWD
+ abs_path = os.path.join(tmp, "file.py")
+ result = pretty_path(abs_path)
+ # Should stay absolute or have .. prefix (depending on location)
+ # Either way, it should contain the filename
+ assert "file.py" in result
+
+ def test_base_dir_makes_path_relative_to_it(self) -> None:
+ """Test that base_dir parameter makes paths relative to that dir."""
+ with tempfile.TemporaryDirectory() as tmp:
+ subdir = os.path.join(tmp, "subdir")
+ os.makedirs(subdir)
+ notebook = os.path.join(subdir, "notebook.py")
+ Path(notebook).touch()
+
+ # With base_dir pointing to subdir, should return just filename
+ result = pretty_path(notebook, base_dir=subdir)
+ assert result == "notebook.py"
+
+ def test_base_dir_with_nested_path(self) -> None:
+ """Test base_dir with nested subdirectories."""
+ with tempfile.TemporaryDirectory() as tmp:
+ nested = os.path.join(tmp, "a", "b", "c")
+ os.makedirs(nested)
+ notebook = os.path.join(nested, "notebook.py")
+ Path(notebook).touch()
+
+ # With base_dir pointing to parent, should return relative path
+ result = pretty_path(notebook, base_dir=tmp)
+ expected = os.path.join("a", "b", "c", "notebook.py")
+ assert result == expected
+
+ def test_base_dir_file_outside_falls_back_to_cwd_relative(self) -> None:
+ """Test that files outside base_dir fall back to CWD-relative."""
+ with tempfile.TemporaryDirectory() as base:
+ with tempfile.TemporaryDirectory() as other:
+ # File is in 'other', not in 'base'
+ file_path = os.path.join(other, "outside.py")
+ Path(file_path).touch()
+
+ result = pretty_path(file_path, base_dir=base)
+ # Should contain the filename (exact path depends on CWD)
+ assert "outside.py" in result
+
+ def test_base_dir_accepts_path_object(self) -> None:
+ """Test that base_dir accepts Path objects."""
+ with tempfile.TemporaryDirectory() as tmp:
+ subdir = Path(tmp) / "subdir"
+ subdir.mkdir()
+ notebook = subdir / "notebook.py"
+ notebook.touch()
+
+ # Should work with Path object
+ result = pretty_path(str(notebook), base_dir=subdir)
+ assert result == "notebook.py"
+
+ def test_base_dir_accepts_string(self) -> None:
+ """Test that base_dir accepts string paths."""
+ with tempfile.TemporaryDirectory() as tmp:
+ subdir = os.path.join(tmp, "subdir")
+ os.makedirs(subdir)
+ notebook = os.path.join(subdir, "notebook.py")
+ Path(notebook).touch()
+
+ # Should work with string
+ result = pretty_path(notebook, base_dir=subdir)
+ assert result == "notebook.py"