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
improvement: auto-run cells in watch mode, via config (#3753)
Myles Scolnick3b7b06cf2a64
diff --git a/docs/guides/editor_features/watching.md b/docs/guides/editor_features/watching.mdindex cc3c533bdc..de7ecaa99b 100644--- a/docs/guides/editor_features/watching.md+++ b/docs/guides/editor_features/watching.md@@ -18,10 +18,17 @@ will open your notebook in the browser and watch the underlying notebookfile for changes. When you make changes to the notebook file, they will bestreamed to the marimo editor in the browser.-Synced code will not be executed automatically, with cells marked as stale instead.+By default, synced code will not be executed automatically, with cells marked as stale instead.Run all stale cells with the marimo editor's "Run" button, or the [`runStale`hotkey](hotkeys.md), to see the new outputs.+If you want to run all affected cells automatically when you save, change the `runtime` config in your `pyproject.toml` file.++```toml+[tool.marimo.runtime]+watcher_on_save = "autorun"+```+!!! note "Cell signature and returns"Don't worry about maintaining the signatures of cells and their returnvalues; marimo will handle this for you.diff --git a/marimo/_ast/cell_manager.py b/marimo/_ast/cell_manager.pyindex f830f22dad..37b443bfe0 100644--- a/marimo/_ast/cell_manager.py+++ b/marimo/_ast/cell_manager.py@@ -328,6 +328,11 @@ class CellManager:"""return self._cell_data[cell_id]+ def get_cell_code(self, cell_id: CellId_t) -> Optional[str]:+ if cell_id not in self._cell_data:+ return None+ return self._cell_data[cell_id].code+def get_cell_id_by_code(self, code: str) -> Optional[CellId_t]:"""Find a cell ID by its code content.diff --git a/marimo/_ast/compiler.py b/marimo/_ast/compiler.pyindex 00729c6f96..4a66431cfa 100644--- a/marimo/_ast/compiler.py+++ b/marimo/_ast/compiler.py@@ -309,11 +309,17 @@ def cell_factory(# last statement of the function body, so we use the ast, which lets us# easily find the last statement of the function body;tree = ast.parse(function_code)- return_node = (- tree.body[0].body[-1] # type: ignore- if isinstance(tree.body[0].body[-1], ast.Return) # type: ignore- else None- )+ return_node: Optional[ast.Return]+ first_stmt = tree.body[0]+ # Handle case where first statement does not have a body+ if not hasattr(first_stmt, "body"):+ return_node = None+ else:+ return_node = (+ first_stmt.body[-1] # type: ignore+ if isinstance(first_stmt.body[-1], ast.Return) # type: ignore+ else None+ )end_line, return_offset = ((return_node.lineno - 1, return_node.col_offset)diff --git a/marimo/_config/config.py b/marimo/_config/config.pyindex 3b0a8a67b3..a078663269 100644--- a/marimo/_config/config.py+++ b/marimo/_config/config.py@@ -94,11 +94,14 @@ class RuntimeConfig(TypedDict):- `execution_type`: if `relaxed`, marimo will not clone cell declarations;if `strict` marimo will clone cell declarations by default, avoidinghidden potential state build up.+ - `watcher_on_save`: how to handle file changes when saving. `"lazy"` marks+ affected cells as stale, `"autorun"` automatically runs affected cells."""auto_instantiate: boolauto_reload: Literal["off", "lazy", "autorun"]on_cell_change: OnCellChangeType+ watcher_on_save: Literal["lazy", "autorun"]# TODO(akshayka): remove normal, migrate to compact@@ -291,6 +294,7 @@ DEFAULT_CONFIG: MarimoConfig = {"auto_instantiate": True,"auto_reload": "off","on_cell_change": "autorun",+ "watcher_on_save": "lazy",},"save": {"autosave": "after_delay",diff --git a/marimo/_server/export/__init__.py b/marimo/_server/export/__init__.pyindex 2957d96d7f..63c79c8193 100644--- a/marimo/_server/export/__init__.py+++ b/marimo/_server/export/__init__.py@@ -262,6 +262,7 @@ async def run_app_until_completion("on_cell_change": "autorun","auto_instantiate": True,"auto_reload": "off",+ "watcher_on_save": "lazy",}})diff --git a/marimo/_server/file_manager.py b/marimo/_server/file_manager.pyindex 6e38f14240..36ab19fece 100644--- a/marimo/_server/file_manager.py+++ b/marimo/_server/file_manager.py@@ -9,7 +9,7 @@ from typing import Any, Dict, Optionalfrom marimo import _loggersfrom marimo._ast import codegenfrom marimo._ast.app import App, InternalApp, _AppConfig-from marimo._ast.cell import CellConfig+from marimo._ast.cell import CellConfig, CellId_tfrom marimo._config.config import WidthTypefrom marimo._runtime.layout.layout import (LayoutConfig,@@ -40,12 +40,28 @@ class AppFileManager:manager.app = appreturn manager- def reload(self) -> None:- """Reload the app from the file."""+ def reload(self) -> set[CellId_t]:+ """+ Reload the app from the file.++ Return any new cell IDs that were added or code that was changed.+ """prev_cell_manager = self.app.cell_managerself.app = self._load_app(self.path)self.app.cell_manager.sort_cell_ids_by_similarity(prev_cell_manager)+ # Return the changes cell IDs+ prev_cell_ids = set(prev_cell_manager.cell_ids())+ changed_cell_ids: set[CellId_t] = set()+ for cell_id in self.app.cell_manager.cell_ids():+ if cell_id not in prev_cell_ids:+ changed_cell_ids.add(cell_id)+ new_code = self.app.cell_manager.get_cell_code(cell_id)+ prev_code = prev_cell_manager.get_cell_code(cell_id)+ if new_code != prev_code:+ changed_cell_ids.add(cell_id)+ return changed_cell_ids+def _is_same_path(self, filename: str) -> bool:if self.filename is None:return Falsediff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.pyindex 23cf3ce01f..b4f278bb92 100644--- a/marimo/_server/sessions.py+++ b/marimo/_server/sessions.py@@ -708,6 +708,7 @@ class SessionManager:def __init__(self,+ *,file_router: AppFileRouter,mode: SessionMode,development_mode: bool,@@ -825,7 +826,7 @@ class SessionManager:# Reload the file manager to get the latest codetry:- session.app_file_manager.reload()+ changed_cell_ids = session.app_file_manager.reload()except Exception as e:# If there are syntax errors, we just skip# and don't send the changes@@ -846,18 +847,43 @@ class SessionManager:UpdateCellIdsRequest(cell_ids=cell_ids),from_consumer_id=None,)++ # Check if we should auto-run cells based on config+ should_autorun = (+ self.user_config_manager.get_config()["runtime"][+ "watcher_on_save"+ ]+ == "autorun"+ )session.write_operation(UpdateCellCodes(cell_ids=cell_ids,codes=codes,- # The code is considered stale- # because it has not been run yet.- # In the future, we may add auto-run here.- code_is_stale=True,+ code_is_stale=not should_autorun,),from_consumer_id=None,)+ # Auto-run cells if configured+ if should_autorun:+ changed_cell_ids_list = list(changed_cell_ids)+ cell_ids_to_idx = {+ cell_id: idx for idx, cell_id in enumerate(cell_ids)+ }+ changed_codes = [+ codes[cell_ids_to_idx[cell_id]]+ for cell_id in changed_cell_ids_list+ ]++ session.put_control_request(+ ExecuteMultipleRequest(+ cell_ids=changed_cell_ids_list,+ codes=changed_codes,+ request=None,+ ),+ from_consumer_id=None,+ )+session._unsubscribe_file_watcher_ = on_file_changed # type: ignoreself.watcher_manager.add_callback(diff --git a/openapi/api.yaml b/openapi/api.yamlindex 6cd4ab8f08..d025b293aa 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -1222,10 +1222,16 @@ components:- lazy- autoruntype: string+ watcher_on_save:+ enum:+ - lazy+ - autorun+ type: stringrequired:- auto_instantiate- auto_reload- on_cell_change+ - watcher_on_savetype: objectsave:properties:@@ -2022,7 +2028,7 @@ components:type: objectinfo:title: marimo API- version: 0.10.19+ version: 0.11.2openapi: 3.1.0paths:/@file/{filename_and_length}:diff --git a/openapi/src/api.ts b/openapi/src/api.tsindex 396a46efc0..77554891c5 100644--- a/openapi/src/api.ts+++ b/openapi/src/api.ts@@ -2579,6 +2579,8 @@ export interface components {auto_reload: "off" | "lazy" | "autorun";/** @enum {string} */on_cell_change: "lazy" | "autorun";+ /** @enum {string} */+ watcher_on_save: "lazy" | "autorun";};save: {/** @enum {string} */diff --git a/pyproject.toml b/pyproject.tomlindex 0d49971a4e..bb4600f175 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -495,3 +495,6 @@ chat_sidebar = true[tool.marimo.display]dataframes = "rich"++[tool.marimo.runtime]+watcher_on_save = "autorun"diff --git a/tests/_ast/test_cell_manager.py b/tests/_ast/test_cell_manager.pyindex dd2eb40107..bca85742d7 100644--- a/tests/_ast/test_cell_manager.py+++ b/tests/_ast/test_cell_manager.py@@ -95,6 +95,13 @@ def test_get_cell_id_by_code(cell_manager: CellManager) -> None:assert cell_manager.get_cell_id_by_code("nonexistent") is None+def test_get_cell_code(cell_manager: CellManager) -> None:+ code = "print('hello')"+ cell_manager.register_cell("test_cell1", code, CellConfig())+ assert cell_manager.get_cell_code("test_cell1") == code+ assert cell_manager.get_cell_code("nonexistent") is None++def test_register_unparsable_cell(cell_manager: CellManager) -> None:code = """def unparsable():diff --git a/tests/_config/test_manager.py b/tests/_config/test_manager.pyindex d5955f3769..f190ed1ab9 100644--- a/tests/_config/test_manager.py+++ b/tests/_config/test_manager.py@@ -113,6 +113,7 @@ def test_get_config_with_override() -> None:"on_cell_change": "autorun","auto_instantiate": True,"auto_reload": "lazy",+ "watcher_on_save": "lazy",}}),@@ -125,6 +126,7 @@ def test_get_config_with_override() -> None:"on_cell_change": "autorun","auto_instantiate": True,"auto_reload": "lazy",+ "watcher_on_save": "lazy",}})diff --git a/tests/_server/api/endpoints/test_resume_session.py b/tests/_server/api/endpoints/test_resume_session.pyindex 9fbce076fc..b2a39b6e87 100644--- a/tests/_server/api/endpoints/test_resume_session.py+++ b/tests/_server/api/endpoints/test_resume_session.py@@ -2,9 +2,11 @@from __future__ import annotationsimport time+from contextlib import contextmanagerfrom dataclasses import asdictfrom typing import TYPE_CHECKING, Any, Optional+from marimo._config.manager import UserConfigManagerfrom marimo._messaging.ops import CellOp, KernelCapabilities, KernelReadyfrom marimo._server.sessions import Sessionfrom marimo._utils.parse_dataclass import parse_raw@@ -317,12 +319,13 @@ def test_resume_session_with_watch(client: TestClient) -> None:"op": "update-cell-codes","data": {"cell_ids": ["MJUe", "Hbol"],- "code_is_stale": True,+ "code_is_stale": False,"codes": ["x=10; x", "import marimo as mo"],},}# Resume session with new ID (simulates refresh)+ # watcher_on_save is 'autorun', so we should expect the cell to be runwith client.websocket_connect("/ws?session_id=456") as websocket:# First message is the kernel reconnecteddata = websocket.receive_json()@@ -337,32 +340,33 @@ def test_resume_session_with_watch(client: TestClient) -> None:while True:data = websocket.receive_json()messages.append(data)- if data["op"] == "update-cell-codes":+ if data["op"] == "update-cell-ids":break# 3 messages:# 1. banner# 2. update-cell-ids- # 3. update-cell-codes- assert len(messages) == 3+ assert len(messages) == 2assert messages[0]["op"] == "banner"assert messages[1] == {"op": "update-cell-ids","data": {"cell_ids": ["MJUe", "Hbol"]},}- assert messages[2] == {- "op": "update-cell-codes",- "data": {- "cell_ids": ["MJUe", "Hbol"],- "code_is_stale": True,- "codes": ["x=10; x", "import marimo as mo"],- },- }session = get_session(client, "456")assert sessionsession_view = session.session_view- assert session_view.last_executed_code == {}+ assert session_view.last_executed_code == {"MJUe": "x=10; x"}session_manager.watch = Falseclient.post("/api/kernel/shutdown", headers=HEADERS)+++@contextmanager+def without_autorun_on_save(config: UserConfigManager):+ prev_config = config.get_config()+ try:+ config.save_config({"runtime": {"watcher_on_save": "lazy"}})+ yield+ finally:+ config.save_config(prev_config)diff --git a/tests/_server/templates/snapshots/export1.txt b/tests/_server/templates/snapshots/export1.txtindex 1c9ad32320..bfd581f623 100644--- a/tests/_server/templates/snapshots/export1.txt+++ b/tests/_server/templates/snapshots/export1.txt@@ -55,7 +55,7 @@<marimo-filename hidden>notebook.py</marimo-filename><marimo-mode data-mode='read' hidden></marimo-mode><marimo-version data-version='0.0.0' hidden></marimo-version>- <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>+ <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config><marimo-app-config data-config='{"width": "compact"}' hidden></marimo-app-config><marimo-server-token data-token='token' hidden></marimo-server-token><title>notebook</title>diff --git a/tests/_server/templates/snapshots/export2.txt b/tests/_server/templates/snapshots/export2.txtindex 21e76164f7..725ae2d2ec 100644--- a/tests/_server/templates/snapshots/export2.txt+++ b/tests/_server/templates/snapshots/export2.txt@@ -55,7 +55,7 @@<marimo-filename hidden></marimo-filename><marimo-mode data-mode='read' hidden></marimo-mode><marimo-version data-version='0.0.0' hidden></marimo-version>- <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>+ <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config><marimo-app-config data-config='{"width": "compact"}' hidden></marimo-app-config><marimo-server-token data-token='token' hidden></marimo-server-token><title>marimo</title>diff --git a/tests/_server/templates/snapshots/export3.txt b/tests/_server/templates/snapshots/export3.txtindex bb2f00d7ab..6b025fc1bc 100644--- a/tests/_server/templates/snapshots/export3.txt+++ b/tests/_server/templates/snapshots/export3.txt@@ -55,7 +55,7 @@<marimo-filename hidden>notebook.py</marimo-filename><marimo-mode data-mode='read' hidden></marimo-mode><marimo-version data-version='0.0.0' hidden></marimo-version>- <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>+ <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config><marimo-app-config data-config='{"width": "compact"}' hidden></marimo-app-config><marimo-server-token data-token='token' hidden></marimo-server-token><title>notebook</title>diff --git a/tests/_server/templates/snapshots/export4.txt b/tests/_server/templates/snapshots/export4.txtindex cc12f97fce..a3044edc5d 100644--- a/tests/_server/templates/snapshots/export4.txt+++ b/tests/_server/templates/snapshots/export4.txt@@ -55,7 +55,7 @@<marimo-filename hidden>notebook.py</marimo-filename><marimo-mode data-mode='read' hidden></marimo-mode><marimo-version data-version='0.0.0' hidden></marimo-version>- <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>+ <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config><marimo-app-config data-config='{"css_file": "custom.css", "width": "compact"}' hidden></marimo-app-config><marimo-server-token data-token='token' hidden></marimo-server-token><title>notebook</title>diff --git a/tests/_server/templates/snapshots/export5.txt b/tests/_server/templates/snapshots/export5.txtindex ba7f3bfb95..db2ecddae3 100644--- a/tests/_server/templates/snapshots/export5.txt+++ b/tests/_server/templates/snapshots/export5.txt@@ -55,7 +55,7 @@<marimo-filename hidden>notebook.py</marimo-filename><marimo-mode data-mode='read' hidden></marimo-mode><marimo-version data-version='0.0.0' hidden></marimo-version>- <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config>+ <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "dataframes": "rich", "default_width": "medium", "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"overrides": {}, "preset": "default"}, "package_management": {"manager": "uv"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun", "watcher_on_save": "lazy"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default", "follow_symlink": false}, "snippets": {"custom_paths": [], "include_default_snippets": true}}' data-overrides='{"formatting": {"line_length": 100}}' hidden></marimo-user-config><marimo-app-config data-config='{"html_head_file": "head.html", "width": "compact"}' hidden></marimo-app-config><marimo-server-token data-token='token' hidden></marimo-server-token><title>notebook</title>diff --git a/tests/_server/test_file_manager.py b/tests/_server/test_file_manager.pyindex 685b51f2be..7d0ca4d212 100644--- a/tests/_server/test_file_manager.py+++ b/tests/_server/test_file_manager.py@@ -304,13 +304,13 @@ if __name__ == "__main__":f.write(modified_content)# Reload the file- manager.reload()+ changed_cell_ids = manager.reload()# The cell IDs should be reordered to match the original codereloaded_cell_ids = list(manager.app.cell_manager.cell_ids())assert len(reloaded_cell_ids) == len(original_cell_ids)assert reloaded_cell_ids == ["MJUe", "Hbol"]-+ assert changed_cell_ids == set()# Clean upos.remove(temp_file.name)@@ -358,13 +358,13 @@ if __name__ == "__main__":f.write(modified_content)# Reload the file- manager.reload()+ changed_cell_ids = manager.reload()# Check that the code was updatedreloaded_code = list(manager.app.cell_manager.codes())[0]assert "x = 42" in reloaded_codeassert "x = 1" not in reloaded_code-+ assert changed_cell_ids == {"Hbol"}# Clean upos.remove(temp_file.name)@@ -417,7 +417,7 @@ if __name__ == "__main__":f.write(modified_content)# Reload the file- manager.reload()+ changed_cell_ids = manager.reload()# Check that the new cell was addedcodes = list(manager.app.cell_manager.codes())@@ -426,6 +426,6 @@ if __name__ == "__main__":assert "x = 1" in codes[1]next_cell_ids = list(manager.app.cell_manager.cell_ids())assert next_cell_ids == ["MJUe", "Hbol"]-+ assert changed_cell_ids == {"MJUe"}# Clean upos.remove(temp_file.name)diff --git a/tests/_server/test_sessions.py b/tests/_server/test_sessions.pyindex df57a7c56c..fc8a2733a9 100644--- a/tests/_server/test_sessions.py+++ b/tests/_server/test_sessions.py@@ -20,6 +20,7 @@ from marimo._messaging.ops import UpdateCellCodesfrom marimo._runtime.requests import (AppMetadata,CreationRequest,+ ExecuteMultipleRequest,ExecutionRequest,SetUIElementValueRequest,)@@ -405,7 +406,8 @@ async def test_session_manager_file_watching() -> None:@mo.celldef __():- return 1+ 1+ return ()""")@@ -451,7 +453,8 @@ def __():@mo.celldef __():- return 2+ 2+ return ()""")@@ -490,7 +493,8 @@ def __():@mo.celldef __():- return 3+ 3+ return ()""")@@ -520,7 +524,8 @@ def __():@mo.celldef __():- return 4+ 4+ return ()""")@@ -614,6 +619,142 @@ def test_watch_mode_config_override() -> None:os.remove(tmp_path)+@save_and_restore_main+async def test_watch_mode_with_watcher_on_save_config() -> None:+ """Test that watch mode works correctly with watcher_on_save config."""+ # Create a temporary file+ with NamedTemporaryFile(delete=False, suffix=".py") as tmp_file:+ tmp_path = Path(tmp_file.name)+ # Write initial notebook content+ tmp_file.write(+ b"""import marimo as mo++def __():+ 1+ return ()+"""+ )++ try:+ # Create a config with watcher_on_save set to autorun+ config_reader = get_default_config_manager(current_path=None)+ config_reader_autorun = config_reader.with_overrides(+ {+ "runtime": {+ "watcher_on_save": "autorun",+ }+ }+ )++ # Create a session manager with file watching enabled+ file_router = AppFileRouter.from_filename(MarimoPath(str(tmp_path)))+ session_manager = SessionManager(+ file_router=file_router,+ mode=SessionMode.EDIT,+ development_mode=False,+ quiet=True,+ include_code=True,+ lsp_server=MagicMock(),+ user_config_manager=config_reader_autorun,+ cli_args={},+ auth_token=None,+ redirect_console_to_browser=False,+ ttl_seconds=None,+ watch=True,+ )++ # Create a mock session consumer+ session_consumer = MagicMock()+ session_consumer.connection_state.return_value = ConnectionState.OPEN+ operations: list[Any] = []+ session_consumer.write_operation = (+ lambda op, *_args: operations.append(op)+ )++ # Create a session+ session_manager.create_session(+ session_id="test",+ session_consumer=session_consumer,+ query_params={},+ file_key=str(tmp_path),+ )++ # Wait a bit and then modify the file+ await asyncio.sleep(0.2)+ with open(tmp_path, "w") as f: # noqa: ASYNC230+ f.write(+ """import marimo as mo++def __():+ 2+ return ()+"""+ )++ # Wait for the watcher to detect the change+ await asyncio.sleep(0.2)++ # Check that UpdateCellCodes was sent with code_is_stale=False (autorun)+ update_ops = [+ op for op in operations if isinstance(op, UpdateCellCodes)+ ]+ assert len(update_ops) == 1+ assert "2" in update_ops[0].codes[0]+ assert update_ops[0].code_is_stale is False++ # Verify that cells were queued for execution+ assert session_consumer.put_control_request.called+ last_call = session_consumer.put_control_request.call_args[0][0]+ assert isinstance(last_call, ExecuteMultipleRequest)++ # Now change config to lazy mode+ config_reader_lazy = config_reader.with_overrides(+ {+ "runtime": {+ "watcher_on_save": "lazy",+ }+ }+ )+ session_manager.user_config_manager = config_reader_lazy++ # Reset the mock+ session_consumer.put_control_request.reset_mock()++ # Modify the file again+ operations.clear()+ with open(tmp_path, "w") as f: # noqa: ASYNC230+ f.write(+ """import marimo as mo++def __():+ 3+ return ()+"""+ )++ # Wait for the watcher to detect the change+ await asyncio.sleep(0.2)++ # Check that UpdateCellCodes was sent with code_is_stale=True (lazy)+ update_ops = [+ op for op in operations if isinstance(op, UpdateCellCodes)+ ]+ assert len(update_ops) == 1+ assert "3" in update_ops[0].codes[0]+ assert update_ops[0].code_is_stale is True++ # Verify that no execution was queued+ assert not session_consumer.put_control_request.called++ finally:+ # Cleanup+ session_manager.shutdown()+ os.remove(tmp_path)++@save_and_restore_mainasync def test_session_manager_file_rename() -> None:"""Test that file renaming works correctly with file watching."""@@ -630,7 +771,8 @@ async def test_session_manager_file_rename() -> None:@mo.celldef __():- return 1+ 1+ return ()""")tmp_file2.write(b"import marimo as mo")@@ -700,7 +842,8 @@ def __():@mo.celldef __():- return 2+ 2+ return ()""")@@ -722,7 +865,8 @@ def __():@mo.celldef __():- return 3+ 3+ return ()""")