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.

feat: dynamic gallery index refresh on `marimo run <folder> --watch` (#8460)

Péter Gyarmatia3bcf22e084a
diff --git a/docs/guides/apps.md b/docs/guides/apps.md
index 0d3ed5966c..5e06adc82b 100644
--- a/docs/guides/apps.md
+++ b/docs/guides/apps.md
@@ -32,6 +32,8 @@ marimo run notebook_a.py notebook_b.py folder/
This shows a page with one card per notebook. Cards can use notebook OpenGraph metadata for the title, description, and thumbnail image. Configure [OpenGraph previews](publishing/opengraph.md) and optionally generate images with [Thumbnails](publishing/thumbnails.md).
+If you run a single folder with watch mode (`marimo run folder/ --watch`), the gallery index is refreshed on subsequent workspace requests so file additions and deletions show up after refreshing the gallery page. See [Using your own editor](editor_features/watching.md) for watch behavior and security considerations.
+
## Layout
While editing a notebook with `marimo edit`, you can preview the notebook
diff --git a/docs/guides/editor_features/watching.md b/docs/guides/editor_features/watching.md
index cf320c483f..e945813efa 100644
--- a/docs/guides/editor_features/watching.md
+++ b/docs/guides/editor_features/watching.md
@@ -214,6 +214,15 @@ detects a change to the notebook file, the application will be refreshed. The
browser will trigger a page refresh to ensure your notebook starts from a fresh
state.
+For gallery mode (`marimo run <folder> --watch`), marimo also refreshes the
+folder index on each workspace request. This means added and removed notebooks
+appear after refreshing or revisiting the gallery page.
+
+!!! warn "Security note for watched folders"
+ In `marimo run <folder> --watch`, newly created notebooks in that folder
+ can appear in the gallery and execute code when opened. Only watch trusted
+ directories, and use authentication when exposing the server remotely.
+
## Watching for changes to other modules
marimo can also watch for changes to Python modules that your notebook imports,
diff --git a/docs/security.md b/docs/security.md
index b98c00d215..fc72bedb12 100644
--- a/docs/security.md
+++ b/docs/security.md
@@ -41,6 +41,7 @@ marimo behaves differently depending on how you run it:
- Notebooks run as web applications
- Content is treated as a trusted website (no sanitization)
- Token authentication can be configured via CLI flags or custom middleware
+- With `marimo run <folder> --watch`, newly created notebooks in the watched folder can appear in gallery mode without restarting the server
This distinction reflects the different threat models: editing is exploratory and may involve untrusted notebooks; deployed apps are intentional publications.
diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.py
index 79d90f7ff3..2bcdbfe8a9 100644
--- a/marimo/_cli/cli.py
+++ b/marimo/_cli/cli.py
@@ -37,7 +37,11 @@ from marimo._cli.utils import (
)
from marimo._config.settings import GLOBAL_SETTINGS
from marimo._lint import run_check
-from marimo._server.file_router import AppFileRouter, flatten_files
+from marimo._server.file_router import (
+ AppFileRouter,
+ LazyListOfFilesAppFileRouter,
+ flatten_files,
+)
from marimo._server.files.directory_scanner import DirectoryScanner
from marimo._server.models.home import MarimoFile
from marimo._server.start import start
@@ -862,6 +866,38 @@ def _collect_marimo_files(paths: list[str]) -> _CollectedRunFiles:
return _CollectedRunFiles(files=files, root_dir=root_dir)
+def _create_run_file_router(
+ validated_paths: list[str], *, watch: bool
+) -> AppFileRouter:
+ """Create the file router for `marimo run`.
+
+ For `--watch` with a single directory, use a lazy directory router so the
+ gallery index can reflect file additions/deletions on subsequent requests.
+ For all other invocation shapes, preserve static snapshot behavior.
+ """
+ if (
+ watch
+ and len(validated_paths) == 1
+ and Path(validated_paths[0]).is_dir()
+ ):
+ return LazyListOfFilesAppFileRouter(
+ validated_paths[0], include_markdown=True
+ )
+
+ has_directory = any(Path(path).is_dir() for path in validated_paths)
+ is_multi = has_directory or len(validated_paths) > 1
+ if is_multi:
+ marimo_files = _collect_marimo_files(validated_paths)
+ return AppFileRouter.from_files(
+ marimo_files.files,
+ directory=marimo_files.root_dir,
+ allow_single_file_key=False,
+ allow_dynamic=False,
+ )
+
+ return AppFileRouter.from_filename(MarimoPath(validated_paths[0]))
+
+
@main.command(
help="""Run a notebook as an app in read-only mode.
@@ -1125,18 +1161,7 @@ def run(
"Or: pip install pyzmq"
)
- if is_multi:
- marimo_files = _collect_marimo_files(validated_paths)
- file_router = AppFileRouter.from_files(
- marimo_files.files,
- directory=marimo_files.root_dir,
- allow_single_file_key=False,
- allow_dynamic=False,
- )
- else:
- file_router = AppFileRouter.from_filename(
- MarimoPath(validated_paths[0])
- )
+ file_router = _create_run_file_router(validated_paths, watch=watch)
start(
file_router=file_router,
diff --git a/marimo/_server/api/endpoints/home.py b/marimo/_server/api/endpoints/home.py
index 3ddf6c5377..d4c26e68f9 100644
--- a/marimo/_server/api/endpoints/home.py
+++ b/marimo/_server/api/endpoints/home.py
@@ -102,6 +102,12 @@ async def workspace_files(
)
from marimo._server.models.files import FileInfo
+ if session_manager.watch and isinstance(
+ session_manager.file_router, LazyListOfFilesAppFileRouter
+ ):
+ # In watched folder mode, refresh the index to include new/removed files since the previous request.
+ session_manager.file_router.mark_stale()
+
base_url = app_state.base_url
mode = session_manager.mode.value
diff --git a/marimo/_server/start.py b/marimo/_server/start.py
index e791895173..3a7528fb96 100644
--- a/marimo/_server/start.py
+++ b/marimo/_server/start.py
@@ -20,7 +20,10 @@ from marimo._runtime.commands import SerializedCLIArgs
from marimo._server.config import (
StarletteServerStateInit,
)
-from marimo._server.file_router import AppFileRouter
+from marimo._server.file_router import (
+ AppFileRouter,
+ LazyListOfFilesAppFileRouter,
+)
from marimo._server.lsp import CompositeLspServer, NoopLspServer
from marimo._server.main import create_starlette_app
from marimo._server.registry import LIFESPAN_REGISTRY
@@ -220,6 +223,18 @@ def start(
if watch and config_reader.is_auto_save_enabled:
LOGGER.warning("Enabling watch mode may interfere with auto-save.")
+ if (
+ mode == SessionMode.RUN
+ and watch
+ and isinstance(file_router, LazyListOfFilesAppFileRouter)
+ ):
+ LOGGER.warning(
+ "Using `marimo run <folder> --watch`: gallery files are "
+ "discovered dynamically. New notebooks created in this directory "
+ "may appear in the gallery and execute code when opened. Use "
+ "trusted directories and authentication controls."
+ )
+
if GLOBAL_SETTINGS.MANAGE_SCRIPT_METADATA:
config_reader = config_reader.with_overrides(
{
diff --git a/tests/_cli/test_cli.py b/tests/_cli/test_cli.py
index 74459653fa..d4dd14a513 100644
--- a/tests/_cli/test_cli.py
+++ b/tests/_cli/test_cli.py
@@ -25,8 +25,12 @@ import pytest
from marimo._ast import codegen
from marimo._ast.cell import CellConfig
-from marimo._cli.cli import _collect_marimo_files
+from marimo._cli.cli import _collect_marimo_files, _create_run_file_router
from marimo._dependencies.dependencies import DependencyManager
+from marimo._server.file_router import (
+ LazyListOfFilesAppFileRouter,
+ ListOfFilesAppFileRouter,
+)
from marimo._server.templates.templates import get_version
from marimo._utils.platform import is_windows
from marimo._utils.toml import read_toml
@@ -876,6 +880,48 @@ def test_collect_marimo_files_excludes_marimo_generated_markdown(
assert str(generated_md) not in paths
+def test_create_run_file_router_watch_single_directory_is_lazy(
+ tmp_path: Path,
+) -> None:
+ (tmp_path / "one.py").write_text(
+ "import marimo\napp = marimo.App()\n", encoding="utf-8"
+ )
+
+ router = _create_run_file_router([str(tmp_path)], watch=True)
+ assert isinstance(router, LazyListOfFilesAppFileRouter)
+ assert router.include_markdown is True
+
+
+def test_create_run_file_router_no_watch_single_directory_is_static(
+ tmp_path: Path,
+) -> None:
+ (tmp_path / "one.py").write_text(
+ "import marimo\napp = marimo.App()\n", encoding="utf-8"
+ )
+
+ router = _create_run_file_router([str(tmp_path)], watch=False)
+ assert isinstance(router, ListOfFilesAppFileRouter)
+
+
+def test_create_run_file_router_watch_mixed_paths_is_static(
+ tmp_path: Path,
+) -> None:
+ directory = tmp_path / "gallery"
+ directory.mkdir()
+ (directory / "one.py").write_text(
+ "import marimo\napp = marimo.App()\n", encoding="utf-8"
+ )
+ standalone = tmp_path / "standalone.py"
+ standalone.write_text(
+ "import marimo\napp = marimo.App()\n", encoding="utf-8"
+ )
+
+ router = _create_run_file_router(
+ [str(directory), str(standalone)], watch=True
+ )
+ assert isinstance(router, ListOfFilesAppFileRouter)
+
+
def test_cli_run_with_show_code(temp_marimo_file: str) -> None:
port = _get_port()
p = subprocess.Popen(
diff --git a/tests/_server/api/endpoints/test_home.py b/tests/_server/api/endpoints/test_home.py
index ae40377916..b3868a116e 100644
--- a/tests/_server/api/endpoints/test_home.py
+++ b/tests/_server/api/endpoints/test_home.py
@@ -143,6 +143,61 @@ def test_workspace_files_in_run_mode(client: TestClient) -> None:
assert files[0]["path"] == marimo_file.name
+@with_session(SESSION_ID)
+def test_workspace_files_run_mode_watch_directory_refreshes_add_remove(
+ client: TestClient,
+) -> None:
+ session_manager = get_session_manager(client)
+ session_manager.mode = SessionMode.RUN
+ session_manager.watch = True
+
+ with tempfile.TemporaryDirectory() as temp_dir:
+ file_one = Path(temp_dir) / "one.py"
+ file_one.write_text("import marimo\napp = marimo.App()")
+
+ session_manager.file_router = AppFileRouter.from_directory(temp_dir)
+
+ response_initial = client.post(
+ "/api/home/workspace_files",
+ headers=HEADERS,
+ json={"include_markdown": False},
+ )
+ body_initial = response_initial.json()
+ assert response_initial.status_code == 200
+ assert body_initial["root"] == temp_dir
+ assert {file["path"] for file in body_initial["files"]} == {
+ file_one.name
+ }
+
+ file_two = Path(temp_dir) / "two.py"
+ file_two.write_text("import marimo\napp = marimo.App()")
+
+ response_after_add = client.post(
+ "/api/home/workspace_files",
+ headers=HEADERS,
+ json={"include_markdown": False},
+ )
+ body_after_add = response_after_add.json()
+ assert response_after_add.status_code == 200
+ assert {file["path"] for file in body_after_add["files"]} == {
+ file_one.name,
+ file_two.name,
+ }
+
+ file_one.unlink()
+
+ response_after_remove = client.post(
+ "/api/home/workspace_files",
+ headers=HEADERS,
+ json={"include_markdown": False},
+ )
+ body_after_remove = response_after_remove.json()
+ assert response_after_remove.status_code == 200
+ assert {file["path"] for file in body_after_remove["files"]} == {
+ file_two.name
+ }
+
+
@with_session(SESSION_ID)
def test_workspace_files_empty_directory(client: TestClient) -> None:
session_manager = get_session_manager(client)