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.

refactor: add load_notebook helper, simplify AppFileRouter (#9438)

Myles Scolnick6783a8de4a2e
diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.py
index 5103065800..44e56838ba 100644
--- a/marimo/_cli/development/commands.py
+++ b/marimo/_cli/development/commands.py
@@ -758,20 +758,16 @@ def preview(file_path: Path, port: int, host: str, headless: bool) -> None:
# Run the notebook to get actual outputs
click.echo(f"Running notebook {file_path.name}...")
from marimo._server.export import run_app_until_completion
- from marimo._server.file_router import AppFileRouter
from marimo._server.utils import asyncio_run
+ from marimo._session.notebook import load_notebook
from marimo._session.state.serialize import (
serialize_notebook,
serialize_session_view,
)
from marimo._utils.code import hash_code
- from marimo._utils.marimo_path import MarimoPath
# Create file manager for the notebook
- file_router = AppFileRouter.from_filename(MarimoPath(file_path))
- file_key = file_router.get_unique_file_key()
- assert file_key is not None
- file_manager = file_router.get_file_manager(file_key)
+ file_manager = load_notebook(file_path)
# Run the notebook to completion and get session view
session_view, did_error = asyncio_run(
diff --git a/marimo/_cli/export/session.py b/marimo/_cli/export/session.py
index e3f111dd12..65e4f353af 100644
--- a/marimo/_cli/export/session.py
+++ b/marimo/_cli/export/session.py
@@ -26,8 +26,8 @@ from marimo._server.export._session_cache import (
serialize_session_snapshot,
write_session_snapshot,
)
-from marimo._server.file_router import AppFileRouter
from marimo._server.utils import asyncio_run
+from marimo._session.notebook import load_notebook
from marimo._session.state.serialize import get_session_cache_file
from marimo._utils.marimo_path import MarimoPath
@@ -65,14 +65,7 @@ async def _export_session_snapshot(
if venv_python is None:
cli_args = parse_args(notebook_args) if notebook_args else {}
- file_router = AppFileRouter.from_filename(marimo_path)
- file_key = file_router.get_unique_file_key()
- if file_key is None:
- raise RuntimeError(
- "Expected a unique file key when exporting a single "
- f"notebook: {marimo_path.absolute_name}"
- )
- file_manager = file_router.get_file_manager(file_key)
+ file_manager = load_notebook(marimo_path.absolute_name)
session_view, did_error = await run_app_until_completion(
file_manager,
@@ -109,19 +102,15 @@ import sys
from marimo._cli.parse_args import parse_args
from marimo._server.export import run_app_until_completion
-from marimo._server.file_router import AppFileRouter
from marimo._server.export._session_cache import serialize_session_snapshot
+from marimo._session.notebook import load_notebook
from marimo._utils.marimo_path import MarimoPath
payload = json.loads(sys.argv[1])
path = MarimoPath(payload["path"])
args = payload.get("args") or []
-file_router = AppFileRouter.from_filename(path)
-file_key = file_router.get_unique_file_key()
-if file_key is None:
- raise RuntimeError("Expected a unique file key for session export.")
-file_manager = file_router.get_file_manager(file_key)
+file_manager = load_notebook(path.absolute_name)
cli_args = parse_args(tuple(args)) if args else {}
session_view, did_error = asyncio.run(
diff --git a/marimo/_islands/_island_generator.py b/marimo/_islands/_island_generator.py
index acbacc17d3..d6bc6de86c 100644
--- a/marimo/_islands/_island_generator.py
+++ b/marimo/_islands/_island_generator.py
@@ -14,9 +14,8 @@ from marimo._ast.cell import Cell, CellConfig
from marimo._ast.compiler import compile_cell
from marimo._messaging.cell_output import CellOutput
from marimo._output.utils import uri_encode_component
-from marimo._session.notebook import AppFileManager
+from marimo._session.notebook import AppFileManager, load_notebook
from marimo._types.ids import CellId_t
-from marimo._utils.marimo_path import MarimoPath
from marimo._version import __version__
if sys.platform == "win32": # handling for windows
@@ -265,13 +264,7 @@ class MarimoIslandGenerator:
- filename (str): Marimo .py filename to convert to reactive HTML.
- display_code (bool): Whether to display the code in HTML snippets.
"""
- from marimo._server.file_router import AppFileRouter
-
- path = MarimoPath(filename)
- file_router = AppFileRouter.from_filename(path)
- file_key = file_router.get_unique_file_key()
- assert file_key is not None
- file_manager = file_router.get_file_manager(file_key)
+ file_manager = load_notebook(filename)
generator = MarimoIslandGenerator()
stubs = []
diff --git a/marimo/_server/api/endpoints/home.py b/marimo/_server/api/endpoints/home.py
index d4c26e68f9..48caf3321e 100644
--- a/marimo/_server/api/endpoints/home.py
+++ b/marimo/_server/api/endpoints/home.py
@@ -14,8 +14,6 @@ from marimo import _loggers
from marimo._server.api.deps import AppState
from marimo._server.api.utils import parse_request
from marimo._server.file_router import (
- LazyListOfFilesAppFileRouter,
- ListOfFilesAppFileRouter,
count_files,
flatten_files,
)
@@ -102,9 +100,7 @@ async def workspace_files(
)
from marimo._server.models.files import FileInfo
- if session_manager.watch and isinstance(
- session_manager.file_router, LazyListOfFilesAppFileRouter
- ):
+ if session_manager.watch:
# In watched folder mode, refresh the index to include new/removed files since the previous request.
session_manager.file_router.mark_stale()
@@ -164,16 +160,13 @@ async def workspace_files(
file_count=file_count,
)
- # Maybe enable markdown
- root = ""
- if isinstance(session_manager.file_router, LazyListOfFilesAppFileRouter):
- # Mark stale in case new files are added
- session_manager.file_router.mark_stale()
- # Toggle markdown
- session_manager.file_router = (
- session_manager.file_router.toggle_markdown(body.include_markdown)
- )
- root = session_manager.file_router.directory
+ # Mark stale (no-op for routers without cached listings) and toggle
+ # markdown inclusion (no-op-returns-self for non-directory routers).
+ session_manager.file_router.mark_stale()
+ session_manager.file_router = session_manager.file_router.toggle_markdown(
+ body.include_markdown
+ )
+ root = session_manager.file_router.directory or ""
# Run file scanning in thread pool to avoid blocking the server
files = await asyncio.to_thread(lambda: session_manager.file_router.files)
@@ -294,19 +287,13 @@ async def tutorial(
atexit.register(temp_dir.cleanup)
- # Register the temp directory with the file router so it can be accessed
- # This is needed for directory-based routers to allow temp tutorial files
+ # Register the temp file/directory with the router so it can be accessed.
+ # Each method is a no-op on routers that don't support that capability.
app_state = AppState(request)
- if isinstance(
- app_state.session_manager.file_router, LazyListOfFilesAppFileRouter
- ):
- app_state.session_manager.file_router.register_temp_dir(temp_dir.name)
- elif isinstance(
- app_state.session_manager.file_router, ListOfFilesAppFileRouter
- ):
- app_state.session_manager.file_router.register_allowed_file(
- path.absolute_name
- )
+ app_state.session_manager.file_router.register_temp_dir(temp_dir.name)
+ app_state.session_manager.file_router.register_allowed_file(
+ path.absolute_name
+ )
return MarimoFile(
name=os.path.basename(path.absolute_name),
diff --git a/marimo/_server/export/__init__.py b/marimo/_server/export/__init__.py
index 0d3a76a337..752265264d 100644
--- a/marimo/_server/export/__init__.py
+++ b/marimo/_server/export/__init__.py
@@ -33,14 +33,13 @@ from marimo._runtime.patches import extract_docstring_from_header
from marimo._schemas.serialization import NotebookSerialization
from marimo._server.export._status import emit_pdf_export_status
from marimo._server.export.exporter import Exporter
-from marimo._server.file_router import AppFileRouter
from marimo._server.models.export import (
ExportAsHTMLRequest,
ExportPDFPreset,
)
from marimo._server.models.models import InstantiateNotebookRequest
from marimo._session.model import ConnectionState, SessionMode
-from marimo._session.notebook import AppFileManager
+from marimo._session.notebook import AppFileManager, load_notebook
from marimo._types.ids import ConsumerId
from marimo._utils.marimo_path import MarimoPath
@@ -185,11 +184,7 @@ def export_as_wasm(
def notebook_uses_slides_layout(filepath: MarimoPath) -> bool:
"""Return whether a notebook declares the slides layout."""
try:
- file_router = AppFileRouter.from_filename(filepath)
- file_key = file_router.get_unique_file_key()
- if file_key is None:
- return False
- file_manager = file_router.get_file_manager(file_key)
+ file_manager = load_notebook(filepath.absolute_name)
layout_config = file_manager.read_layout_config()
return layout_config is not None and layout_config.type == "slides"
except Exception as e:
@@ -207,10 +202,7 @@ async def run_app_then_export_as_ipynb(
cli_args: SerializedCLIArgs,
argv: list[str] | None,
) -> ExportResult:
- file_router = AppFileRouter.from_filename(filepath)
- file_key = file_router.get_unique_file_key()
- assert file_key is not None
- file_manager = file_router.get_file_manager(file_key)
+ file_manager = load_notebook(filepath.absolute_name)
with patch_html_for_non_interactive_output():
# Use quiet=True to suppress runtime stdout/stderr since outputs
@@ -246,10 +238,7 @@ async def run_app_then_export_as_pdf(
rasterization_options: PDFRasterizationOptions | None = None,
status_callback: PDFExportStatusCallback | None = None,
) -> tuple[bytes | None, bool]:
- file_router = AppFileRouter.from_filename(filepath)
- file_key = file_router.get_unique_file_key()
- assert file_key is not None
- file_manager = file_router.get_file_manager(file_key)
+ file_manager = load_notebook(filepath.absolute_name)
session_view: SessionView | None = None
png_fallbacks: Mapping[CellId_t, str] | None = None
@@ -334,11 +323,7 @@ async def run_app_then_export_as_html(
*,
asset_url: str | None = None,
) -> ExportResult:
- # Create a file router and file manager
- file_router = AppFileRouter.from_filename(path)
- file_key = file_router.get_unique_file_key()
- assert file_key is not None
- file_manager = file_router.get_file_manager(file_key)
+ file_manager = load_notebook(path.absolute_name)
# Inline the layout file, if it exists
file_manager.app.inline_layout_file()
@@ -379,14 +364,7 @@ async def export_as_html_without_execution(
"""Export a notebook to HTML without executing its cells."""
from marimo._session.state.session_view import SessionView
- file_router = AppFileRouter.from_filename(path)
- file_key = file_router.get_unique_file_key()
- if file_key is None:
- raise RuntimeError(
- "Expected a unique file key when exporting a single notebook: "
- f"{path.absolute_name}"
- )
- file_manager = file_router.get_file_manager(file_key)
+ file_manager = load_notebook(path.absolute_name)
# Inline the layout file, if it exists.
file_manager.app.inline_layout_file()
diff --git a/marimo/_server/export/_session_cache.py b/marimo/_server/export/_session_cache.py
index 0babcf1775..437ed2cb09 100644
--- a/marimo/_server/export/_session_cache.py
+++ b/marimo/_server/export/_session_cache.py
@@ -6,7 +6,7 @@ from collections import Counter
from pathlib import Path
from typing import TYPE_CHECKING, Any, cast
-from marimo._server.file_router import AppFileRouter
+from marimo._session.notebook import load_notebook
from marimo._session.state.serialize import (
get_session_cache_file,
serialize_session_view,
@@ -41,14 +41,7 @@ def _hash_code_for_session_compare(code: str | None) -> str | None:
def current_notebook_code_hashes(
notebook: MarimoPath,
) -> tuple[str | None, ...]:
- file_router = AppFileRouter.from_filename(notebook)
- file_key = file_router.get_unique_file_key()
- if file_key is None:
- raise RuntimeError(
- "Expected a unique file key when checking staleness for "
- f"{notebook.absolute_name}"
- )
- file_manager = file_router.get_file_manager(file_key)
+ file_manager = load_notebook(notebook.absolute_name)
return tuple(
_hash_code_for_session_compare(cell_data.code)
for cell_data in file_manager.app.cell_manager.cell_data()
diff --git a/marimo/_server/file_router.py b/marimo/_server/file_router.py
index 60996b5656..f7ef402da9 100644
--- a/marimo/_server/file_router.py
+++ b/marimo/_server/file_router.py
@@ -90,44 +90,24 @@ class AppFileRouter(abc.ABC):
assert key is not None, "Expected a single file"
return self.get_file_manager(key, defaults)
+ @abc.abstractmethod
def get_file_manager(
self,
key: MarimoFileKey,
defaults: AppDefaults | None = None,
) -> AppFileManager:
- """
- Given a key, return an AppFileManager.
- """
- defaults = defaults or AppDefaults()
-
- if key.startswith(AppFileRouter.NEW_FILE):
- return AppFileManager(None, defaults=defaults)
-
- if os.path.exists(key):
- return AppFileManager(key, defaults=defaults)
-
- raise HTTPException(
- status_code=HTTPStatus.NOT_FOUND,
- detail=f"File {key} not found",
- )
+ """Given a key, return an ``AppFileManager``."""
+ @abc.abstractmethod
def resolve_file_path(self, key: MarimoFileKey) -> str | None:
"""Resolve a file key to an absolute file path, without loading the app.
- This is useful for endpoints that need file-backed resources (e.g. thumbnails)
- without the overhead of parsing/loading a notebook.
+ This is useful for endpoints that need file-backed resources (e.g.
+ thumbnails) without the overhead of parsing/loading a notebook.
- Returns:
- Absolute file path if resolvable, otherwise None (e.g. new file).
+ Returns the absolute file path if resolvable, otherwise ``None`` (for
+ the new-file sentinel).
"""
- if key.startswith(AppFileRouter.NEW_FILE):
- return None
- if os.path.exists(key):
- return key
- raise HTTPException(
- status_code=HTTPStatus.NOT_FOUND,
- detail=f"File {key} not found",
- )
@abc.abstractmethod
def get_unique_file_key(self) -> MarimoFileKey | None:
@@ -148,6 +128,44 @@ class AppFileRouter(abc.ABC):
Get all files in a recursive tree.
"""
+ # Optional capabilities — subclasses override only if they support them.
+
+ def register_allowed_file(self, filepath: str) -> None:
+ """Allow a file path that wasn't part of the original collection.
+
+ No-op by default; routers that maintain a fixed allowlist override.
+ """
+ del filepath
+
+ def register_temp_dir(self, temp_dir: str) -> None:
+ """Register a temp directory as allowed for file access.
+
+ No-op by default; only directory-backed routers override.
+ """
+ del temp_dir
+
+ def is_file_in_allowed_temp_dir(self, filepath: str) -> bool:
+ """Whether a file lives inside an allowed temp directory.
+
+ Returns ``False`` by default; only directory-backed routers override.
+ """
+ del filepath
+ return False
+
+ def mark_stale(self) -> None: # noqa: B027 — intentional no-op default
+ """Invalidate any cached listing.
+
+ No-op by default; lazy directory routers override.
+ """
+
+ def toggle_markdown(self, include_markdown: bool) -> AppFileRouter:
+ """Return a router with markdown inclusion toggled.
+
+ No-op by default — returns ``self``. Lazy directory routers override.
+ """
+ del include_markdown
+ return self
+
class NewFileAppFileRouter(AppFileRouter):
def get_unique_file_key(self) -> MarimoFileKey | None:
@@ -160,6 +178,34 @@ class NewFileAppFileRouter(AppFileRouter):
def files(self) -> list[FileInfo]:
return []
+ def get_file_manager(
+ self,
+ key: MarimoFileKey,
+ defaults: AppDefaults | None = None,
+ ) -> AppFileManager:
+ defaults = defaults or AppDefaults()
+ if key.startswith(AppFileRouter.NEW_FILE):
+ return AppFileManager(None, defaults=defaults)
+ # Fall back to loading any existing path. This is used by callers
+ # (and tests) that bootstrap with ``new_file()`` but then create
+ # sessions for concrete files.
+ if os.path.exists(key):
+ return AppFileManager(key, defaults=defaults)
+ raise HTTPException(
+ status_code=HTTPStatus.NOT_FOUND,
+ detail=f"File {key} not found",
+ )
+
+ def resolve_file_path(self, key: MarimoFileKey) -> str | None:
+ if key.startswith(AppFileRouter.NEW_FILE):
+ return None
+ if os.path.exists(key):
+ return key
+ raise HTTPException(
+ status_code=HTTPStatus.NOT_FOUND,
+ detail=f"File {key} not found",
+ )
+
class ListOfFilesAppFileRouter(AppFileRouter):
def __init__(
diff --git a/marimo/_server/session_manager.py b/marimo/_server/session_manager.py
index 400fb611f9..8ccfa66190 100644
--- a/marimo/_server/session_manager.py
+++ b/marimo/_server/session_manager.py
@@ -22,7 +22,6 @@ from marimo._runtime.commands import (
from marimo._server.app_defaults import AppDefaults
from marimo._server.file_router import (
AppFileRouter,
- ListOfFilesAppFileRouter,
MarimoFileKey,
flatten_files,
)
@@ -162,10 +161,8 @@ class SessionManager:
def app_manager(self, key: MarimoFileKey) -> AppFileManager:
"""Get the app manager for the given key."""
defaults = AppDefaults.from_config_manager(self._config_manager)
- if (
- self.mode is SessionMode.EDIT
- and isinstance(self.file_router, ListOfFilesAppFileRouter)
- and not key.startswith(AppFileRouter.NEW_FILE)
+ if self.mode is SessionMode.EDIT and not key.startswith(
+ AppFileRouter.NEW_FILE
):
self.file_router.register_allowed_file(key)
return self.file_router.get_file_manager(key, defaults)
@@ -188,10 +185,8 @@ class SessionManager:
# Get app file manager
defaults = AppDefaults.from_config_manager(self._config_manager)
- if (
- self.mode is SessionMode.EDIT
- and isinstance(self.file_router, ListOfFilesAppFileRouter)
- and not file_key.startswith(AppFileRouter.NEW_FILE)
+ if self.mode is SessionMode.EDIT and not file_key.startswith(
+ AppFileRouter.NEW_FILE
):
self.file_router.register_allowed_file(file_key)
app_file_manager = self.file_router.get_file_manager(
diff --git a/marimo/_session/notebook/__init__.py b/marimo/_session/notebook/__init__.py
index edb4212f11..21f7e15626 100644
--- a/marimo/_session/notebook/__init__.py
+++ b/marimo/_session/notebook/__init__.py
@@ -8,6 +8,10 @@ from marimo._session.notebook.file_manager import (
read_css_file,
read_html_head_file,
)
+from marimo._session.notebook.loader import (
+ load_notebook,
+ new_notebook,
+)
from marimo._session.notebook.serializer import (
MarkdownNotebookSerializer,
NotebookSerializer,
@@ -25,6 +29,8 @@ __all__ = [
"NotebookSerializer",
"PythonNotebookSerializer",
"StorageInterface",
+ "load_notebook",
+ "new_notebook",
"read_css_file",
"read_html_head_file",
]
diff --git a/marimo/_session/notebook/loader.py b/marimo/_session/notebook/loader.py
new file mode 100644
index 0000000000..2868d96411
--- /dev/null
+++ b/marimo/_session/notebook/loader.py
@@ -0,0 +1,35 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from marimo._session.notebook.file_manager import AppFileManager
+from marimo._utils.marimo_path import MarimoPath
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+ from marimo._server.app_defaults import AppDefaults
+
+
+def load_notebook(
+ path: str | Path,
+ *,
+ defaults: AppDefaults | None = None,
+) -> AppFileManager:
+ """Load a notebook from a path into an ``AppFileManager``.
+
+ The path is validated as a marimo source file (``.py`` / ``.md`` / ``.qmd``)
+ and resolved to an absolute path before being handed to the file manager,
+ so a later ``chdir`` cannot change which file the manager points at.
+ """
+ marimo_path = MarimoPath(path)
+ return AppFileManager(marimo_path.absolute_name, defaults=defaults)
+
+
+def new_notebook(
+ *,
+ defaults: AppDefaults | None = None,
+) -> AppFileManager:
+ """Create an unbacked ``AppFileManager`` for an untitled notebook."""
+ return AppFileManager(None, defaults=defaults)
diff --git a/tests/_session/notebook/test_loader.py b/tests/_session/notebook/test_loader.py
new file mode 100644
index 0000000000..c8effca487
--- /dev/null
+++ b/tests/_session/notebook/test_loader.py
@@ -0,0 +1,79 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import os
+from typing import TYPE_CHECKING
+
+import pytest
+
+from marimo._session.notebook import (
+ AppFileManager,
+ load_notebook,
+ new_notebook,
+)
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+_NOTEBOOK_SOURCE = """
+import marimo
+
+app = marimo.App()
+
+
+def __():
+ x = 1
+ return (x,)
+"""
+
+
+def _write_notebook(path: Path) -> Path:
+ path.write_text(_NOTEBOOK_SOURCE)
+ return path
+
+
+def test_load_notebook_from_string_path(tmp_path: Path) -> None:
+ nb = _write_notebook(tmp_path / "nb.py")
+ fm = load_notebook(str(nb))
+ assert isinstance(fm, AppFileManager)
+ assert fm.path == str(nb.absolute())
+
+
+def test_load_notebook_from_path_object(tmp_path: Path) -> None:
+ nb = _write_notebook(tmp_path / "nb.py")
+ fm = load_notebook(nb)
+ assert fm.path == str(nb.absolute())
+
+
+def test_load_notebook_resolves_relative_path(tmp_path: Path) -> None:
+ nb = _write_notebook(tmp_path / "nb.py")
+ original_cwd = os.getcwd()
+ try:
+ os.chdir(tmp_path)
+ fm = load_notebook("nb.py")
+ finally:
+ os.chdir(original_cwd)
+ assert fm.path == str(nb.absolute())
+
+
+def test_load_notebook_rejects_non_notebook_extension(tmp_path: Path) -> None:
+ bogus = tmp_path / "not_a_notebook.txt"
+ bogus.write_text("hello")
+ with pytest.raises(ValueError):
+ load_notebook(bogus)
+
+
+def test_load_notebook_loads_cells(tmp_path: Path) -> None:
+ nb = _write_notebook(tmp_path / "nb.py")
+ fm = load_notebook(nb)
+ cells = list(fm.app.cell_manager.cell_data())
+ assert len(cells) == 1
+ assert "x = 1" in cells[0].code
+
+
+def test_new_notebook_returns_unbacked_manager() -> None:
+ fm = new_notebook()
+ assert isinstance(fm, AppFileManager)
+ assert fm.path is None
+ assert fm.filename is None