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: forward cell names and configs on external file reload (#8421) (#8433)

Myles Scolnick9e033d365b24
diff --git a/Makefile b/Makefile
index be56c4ec74..7acf0ff501 100644
--- a/Makefile
+++ b/Makefile
@@ -104,7 +104,7 @@ fe-typecheck:
.PHONY: fe-codegen
# 🔄 Generate frontend API
fe-codegen:
- uv run ./marimo development openapi > packages/openapi/api.yaml
+ uv run --python=3.12 ./marimo development openapi > packages/openapi/api.yaml
pnpm run codegen
pnpm format packages/openapi/
diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.ts
index 4e5957ff4f..413e7f7227 100644
--- a/frontend/src/core/cells/__tests__/cells.test.ts
+++ b/frontend/src/core/cells/__tests__/cells.test.ts
@@ -1439,6 +1439,68 @@ describe("cell reducer", () => {
expect(state.cellData["5" as CellId]).not.toBeUndefined();
});
+ it("can set cell codes with names and configs", () => {
+ const newIds = ["3", "4"] as CellId[];
+ actions.setCellIds({ cellIds: newIds });
+ actions.setCellCodes({
+ codes: ["code1", "code2"],
+ ids: newIds,
+ codeIsStale: false,
+ names: ["setup_cell", "analysis"],
+ configs: [
+ { hide_code: true, disabled: false, column: null },
+ { hide_code: false, disabled: true, column: null },
+ ],
+ });
+
+ expect(state.cellData["3" as CellId].name).toBe("setup_cell");
+ expect(state.cellData["3" as CellId].config.hide_code).toBe(true);
+ expect(state.cellData["3" as CellId].config.disabled).toBe(false);
+
+ expect(state.cellData["4" as CellId].name).toBe("analysis");
+ expect(state.cellData["4" as CellId].config.hide_code).toBe(false);
+ expect(state.cellData["4" as CellId].config.disabled).toBe(true);
+ });
+
+ it("can set cell codes without names/configs (backward compat)", () => {
+ const newIds = ["3"] as CellId[];
+ actions.setCellIds({ cellIds: newIds });
+ actions.setCellCodes({
+ codes: ["code1"],
+ ids: newIds,
+ codeIsStale: false,
+ });
+
+ // Should use defaults when names/configs not provided
+ expect(state.cellData["3" as CellId].code).toBe("code1");
+ expect(state.cellData["3" as CellId].config.hide_code).toBe(false);
+ expect(state.cellData["3" as CellId].config.disabled).toBe(false);
+ });
+
+ it("can update names and configs on existing cells via setCellCodes", () => {
+ // Set initial state
+ actions.setCellCodes({
+ codes: ["x = 1"],
+ ids: [firstCellId],
+ codeIsStale: false,
+ names: ["old_name"],
+ configs: [{ hide_code: false, disabled: false, column: null }],
+ });
+ expect(state.cellData[firstCellId].name).toBe("old_name");
+ expect(state.cellData[firstCellId].config.hide_code).toBe(false);
+
+ // Update with new name and config (same code)
+ actions.setCellCodes({
+ codes: ["x = 1"],
+ ids: [firstCellId],
+ codeIsStale: true,
+ names: ["new_name"],
+ configs: [{ hide_code: true, disabled: false, column: null }],
+ });
+ expect(state.cellData[firstCellId].name).toBe("new_name");
+ expect(state.cellData[firstCellId].config.hide_code).toBe(true);
+ });
+
it("can fold and unfold all cells", () => {
actions.foldAll();
expect(foldAllBulk).toHaveBeenCalled();
diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts
index f0c879c83d..fd21b531e1 100644
--- a/frontend/src/core/cells/cells.ts
+++ b/frontend/src/core/cells/cells.ts
@@ -3,7 +3,7 @@
import { historyField } from "@codemirror/commands";
import { type Atom, atom, useAtom, useAtomValue } from "jotai";
import { atomFamily, selectAtom, splitAtom } from "jotai/utils";
-import { isEqual, zip } from "lodash-es";
+import { isEqual } from "lodash-es";
import { createRef, type ReducerWithoutAction } from "react";
import type { CellHandle } from "@/components/editor/notebook-cell";
import {
@@ -801,7 +801,13 @@ const {
},
setCellCodes: (
state,
- action: { codes: string[]; ids: CellId[]; codeIsStale: boolean },
+ action: {
+ codes: string[];
+ ids: CellId[];
+ codeIsStale: boolean;
+ names?: string[];
+ configs?: CellConfig[];
+ },
) => {
invariant(
action.codes.length === action.ids.length,
@@ -814,15 +820,21 @@ const {
cell,
code,
cellId,
+ name,
+ config,
}: {
cell: CellData | undefined;
code: string;
cellId: CellId;
+ name?: string;
+ config?: CellConfig;
}) => {
if (!cell) {
return createCell({
id: cellId,
code,
+ name: name,
+ config: config,
lastCodeRun: action.codeIsStale ? null : code,
edited: action.codeIsStale && code.trim().length > 0,
});
@@ -843,6 +855,8 @@ const {
code: code,
edited,
lastCodeRun,
+ ...(name !== undefined && { name }),
+ ...(config !== undefined && { config }),
};
}
@@ -860,13 +874,19 @@ const {
code: code,
edited,
lastCodeRun,
+ ...(name !== undefined && { name }),
+ ...(config !== undefined && { config }),
};
};
- for (const [cellId, code] of zip(action.ids, action.codes)) {
+ for (let i = 0; i < action.ids.length; i++) {
+ const cellId = action.ids[i];
+ const code = action.codes[i];
if (cellId === undefined || code === undefined) {
continue;
}
+ const name = action.names?.[i];
+ const config = action.configs?.[i];
nextState = {
...nextState,
cellData: {
@@ -875,6 +895,8 @@ const {
cell: nextState.cellData[cellId],
code,
cellId,
+ name,
+ config,
}),
},
};
diff --git a/frontend/src/core/websocket/useMarimoKernelConnection.tsx b/frontend/src/core/websocket/useMarimoKernelConnection.tsx
index 758e08f514..c43c172fc7 100644
--- a/frontend/src/core/websocket/useMarimoKernelConnection.tsx
+++ b/frontend/src/core/websocket/useMarimoKernelConnection.tsx
@@ -317,6 +317,8 @@ export function useMarimoKernelConnection(opts: {
codes: msg.data.codes,
ids: msg.data.cell_ids as CellId[],
codeIsStale: msg.data.code_is_stale,
+ names: msg.data.names,
+ configs: msg.data.configs,
});
return;
case "update-cell-ids":
diff --git a/marimo/_messaging/notification.py b/marimo/_messaging/notification.py
index 5694dced23..57f52fa53d 100644
--- a/marimo/_messaging/notification.py
+++ b/marimo/_messaging/notification.py
@@ -709,18 +709,22 @@ class FocusCellNotification(Notification, tag="focus-cell"):
class UpdateCellCodesNotification(Notification, tag="update-cell-codes"):
- """Updates cell code contents (kiosk mode).
+ """Updates cell code contents (kiosk mode and edit-mode file reload).
Attributes:
cell_ids: Cells to update.
codes: New code for each cell.
code_is_stale: If True, code was not executed on backend (output may not match).
+ names: Cell names for each cell (optional, for file reload).
+ configs: Cell configs for each cell (optional, for file reload).
"""
name: ClassVar[str] = "update-cell-codes"
cell_ids: list[CellId_t]
codes: list[str]
code_is_stale: bool
+ names: list[str] = msgspec.field(default_factory=list)
+ configs: list[CellConfig] = msgspec.field(default_factory=list)
class SecretKeysResultNotification(Notification, tag="secret-keys-result"):
diff --git a/marimo/_session/file_change_handler.py b/marimo/_session/file_change_handler.py
index 7ad1254c8c..1e2310de42 100644
--- a/marimo/_session/file_change_handler.py
+++ b/marimo/_session/file_change_handler.py
@@ -68,9 +68,12 @@ class EditModeReloadStrategy(ReloadStrategy):
self, session: Session, *, changed_cell_ids: set[CellId_t]
) -> None:
"""Handle reload in edit mode with optional auto-run."""
- # Get the latest codes and cell IDs
- codes = list(session.app_file_manager.app.cell_manager.codes())
- cell_ids = list(session.app_file_manager.app.cell_manager.cell_ids())
+ # Get the latest codes, cell IDs, names, and configs
+ cell_manager = session.app_file_manager.app.cell_manager
+ codes = list(cell_manager.codes())
+ cell_ids = list(cell_manager.cell_ids())
+ names = list(cell_manager.names())
+ configs = list(cell_manager.configs())
LOGGER.info(
f"File changed: {session.app_file_manager.path}. "
@@ -100,6 +103,20 @@ class EditModeReloadStrategy(ReloadStrategy):
changed_cell_ids_list = list(changed_cell_ids - deleted)
cells = dict(zip(cell_ids, codes))
+ # Send names and configs to the frontend (SyncGraphCommand
+ # doesn't carry them)
+ if cell_ids:
+ session.notify(
+ UpdateCellCodesNotification(
+ cell_ids=cell_ids,
+ codes=codes,
+ code_is_stale=False,
+ names=names,
+ configs=configs,
+ ),
+ from_consumer_id=None,
+ )
+
session.put_control_request(
SyncGraphCommand(
cells=cells,
@@ -121,6 +138,8 @@ class EditModeReloadStrategy(ReloadStrategy):
cell_ids=cell_ids,
codes=codes,
code_is_stale=True,
+ names=names,
+ configs=configs,
),
from_consumer_id=None,
)
diff --git a/marimo/_session/notebook/file_manager.py b/marimo/_session/notebook/file_manager.py
index 4c561cb4b6..4892d9a6e8 100644
--- a/marimo/_session/notebook/file_manager.py
+++ b/marimo/_session/notebook/file_manager.py
@@ -118,14 +118,20 @@ class AppFileManager:
# Capture deleted cells
changed_cell_ids: set[CellId_t] = prev_cell_ids - current_cell_ids
- # Check for added or modified cells
+ # Check for added or modified cells (code, config, or name)
for cell_id in current_cell_ids:
if cell_id not in prev_cell_ids:
changed_cell_ids.add(cell_id)
else:
- 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:
+ new_data = self.app.cell_manager.get_cell_data(cell_id)
+ prev_data = prev_cell_manager.get_cell_data(cell_id)
+ if new_data is None or prev_data is None:
+ changed_cell_ids.add(cell_id)
+ elif (
+ new_data.code != prev_data.code
+ or new_data.name != prev_data.name
+ or new_data.config != prev_data.config
+ ):
changed_cell_ids.add(cell_id)
return changed_cell_ids
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index 95a682549d..af13d064af 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -4670,10 +4670,12 @@ components:
title: UnknownError
type: object
UpdateCellCodesNotification:
- description: "Updates cell code contents (kiosk mode).\n\n Attributes:\n\
- \ cell_ids: Cells to update.\n codes: New code for each cell.\n\
- \ code_is_stale: If True, code was not executed on backend (output\
- \ may not match)."
+ description: "Updates cell code contents (kiosk mode and edit-mode file reload).\n\
+ \n Attributes:\n cell_ids: Cells to update.\n codes: New\
+ \ code for each cell.\n code_is_stale: If True, code was not executed\
+ \ on backend (output may not match).\n names: Cell names for each cell\
+ \ (optional, for file reload).\n configs: Cell configs for each cell\
+ \ (optional, for file reload)."
properties:
cell_ids:
items:
@@ -4685,6 +4687,16 @@ components:
items:
type: string
type: array
+ configs:
+ default: []
+ items:
+ $ref: '#/components/schemas/CellConfig'
+ type: array
+ names:
+ default: []
+ items:
+ type: string
+ type: array
op:
enum:
- update-cell-codes
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index 02d64a1d57..bc44193ee5 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -6021,17 +6021,23 @@ export interface components {
};
/**
* UpdateCellCodesNotification
- * @description Updates cell code contents (kiosk mode).
+ * @description Updates cell code contents (kiosk mode and edit-mode file reload).
*
* Attributes:
* cell_ids: Cells to update.
* codes: New code for each cell.
* code_is_stale: If True, code was not executed on backend (output may not match).
+ * names: Cell names for each cell (optional, for file reload).
+ * configs: Cell configs for each cell (optional, for file reload).
*/
UpdateCellCodesNotification: {
cell_ids: string[];
code_is_stale: boolean;
codes: string[];
+ /** @default [] */
+ configs?: components["schemas"]["CellConfig"][];
+ /** @default [] */
+ names?: string[];
/** @enum {unknown} */
op: "update-cell-codes";
};
diff --git a/tests/_server/test_sessions.py b/tests/_server/test_sessions.py
index d0fe8c9d53..3be9bff538 100644
--- a/tests/_server/test_sessions.py
+++ b/tests/_server/test_sessions.py
@@ -782,9 +782,14 @@ async def test_watch_mode_with_watcher_on_save_autorun(tmp_path: Path) -> None:
break
# Check that UpdateCellCodes was sent with code_is_stale=False (autorun)
- assert len(update_ops) == 1
- assert "2" in update_ops[0].codes[0]
- assert update_ops[0].code_is_stale is False
+ # Note: ReplayExtension also sends an UpdateCellCodesNotification
+ # when it intercepts the SyncGraphCommand, so we may get 2.
+ assert len(update_ops) >= 1
+ # The first notification (from file_change_handler) carries names/configs
+ named_ops = [op for op in update_ops if op.names]
+ assert len(named_ops) == 1
+ assert "2" in named_ops[0].codes[0]
+ assert named_ops[0].code_is_stale is False
# Verify that cells were queued for execution
assert session.session_view.add_control_request.called
@@ -1000,13 +1005,15 @@ def __():
break
# Check that UpdateCellCodes was sent with the new code
+ # Note: In autorun mode, ReplayExtension also sends an
+ # UpdateCellCodesNotification when it intercepts SyncGraphCommand.
update_ops = [
op
for op in operations
if isinstance(op, UpdateCellCodesNotification)
]
- assert len(update_ops) == 1
- assert "2" == update_ops[0].codes[0]
+ assert len(update_ops) >= 1
+ assert any("2" == op.codes[0] for op in update_ops)
finally:
# Cleanup
diff --git a/tests/_session/test_file_change_handler.py b/tests/_session/test_file_change_handler.py
index f0482ad091..eae264fcbe 100644
--- a/tests/_session/test_file_change_handler.py
+++ b/tests/_session/test_file_change_handler.py
@@ -89,8 +89,8 @@ def test_edit_mode_reload_strategy_lazy(
strategy.handle_reload(mock_session, changed_cell_ids=changed_cell_ids)
- # Should send UpdateCellIdsRequest
- assert mock_session.notify.call_count >= 1
+ # Should send at least UpdateCellIdsNotification and UpdateCellCodesNotification
+ assert mock_session.notify.call_count >= 2
update_ids_calls = [
call
for call in mock_session.notify.call_args_list
@@ -105,7 +105,13 @@ def test_edit_mode_reload_strategy_lazy(
if isinstance(call[0][0], UpdateCellCodesNotification)
]
assert len(update_codes_calls) == 1
- assert update_codes_calls[0][0][0].code_is_stale is True
+ notification = update_codes_calls[0][0][0]
+ assert notification.code_is_stale is True
+
+ # Names and configs should always be forwarded
+ assert notification.names == ["cell1"]
+ assert len(notification.configs) == 1
+ assert notification.configs[0] == CellConfig()
# Should not send execution requests
mock_session.put_control_request.assert_not_called()
@@ -130,12 +136,14 @@ def test_edit_mode_reload_strategy_autorun(
mock_session.app_file_manager = app_file_manager
strategy = EditModeReloadStrategy(config_manager_autorun)
- changed_cell_ids = {CellId_t("cell1")}
+ # Get actual cell IDs from the app
+ cell_ids = list(app_file_manager.app.cell_manager.cell_ids())
+ changed_cell_ids = set(cell_ids)
strategy.handle_reload(mock_session, changed_cell_ids=changed_cell_ids)
- # Should send UpdateCellIdsRequest
- assert mock_session.notify.call_count >= 1
+ # Should send at least UpdateCellIdsNotification and UpdateCellCodesNotification
+ assert mock_session.notify.call_count >= 2
update_ids_calls = [
call
for call in mock_session.notify.call_args_list
@@ -143,7 +151,20 @@ def test_edit_mode_reload_strategy_autorun(
]
assert len(update_ids_calls) == 1
- # Should send SyncGraphRequest for execution
+ # Should send UpdateCellCodesNotification with names/configs
+ update_codes_calls = [
+ call
+ for call in mock_session.notify.call_args_list
+ if isinstance(call[0][0], UpdateCellCodesNotification)
+ ]
+ assert len(update_codes_calls) == 1
+ notification = update_codes_calls[0][0][0]
+ assert notification.code_is_stale is False
+ assert notification.names == ["cell1"]
+ assert len(notification.configs) == 1
+ assert notification.configs[0] == CellConfig()
+
+ # Should send SyncGraphCommand for execution
assert mock_session.put_control_request.call_count >= 1
sync_calls = [
call
@@ -188,6 +209,17 @@ def test_edit_mode_reload_strategy_with_deleted_cells(
assert len(delete_calls) == 1
assert delete_calls[0][0][0].cell_id == CellId_t("cell2")
+ # Should still send names and configs for the remaining cell
+ update_codes_calls = [
+ call
+ for call in mock_session.notify.call_args_list
+ if isinstance(call[0][0], UpdateCellCodesNotification)
+ ]
+ assert len(update_codes_calls) == 1
+ notification = update_codes_calls[0][0][0]
+ assert notification.names == ["cell1"]
+ assert len(notification.configs) == 1
+
def test_run_mode_reload_strategy(mock_session: MagicMock) -> None:
"""Test run mode reload strategy sends Reload operation."""
@@ -407,3 +439,427 @@ async def test_file_change_coordinator_path_mismatch(
# Should not handle due to path mismatch
assert not result.handled
assert "mismatch" in result.error.lower()
+
+
+def test_edit_mode_reload_sends_names_and_configs_lazy(
+ tmp_path: Path, mock_session: MagicMock, config_manager_lazy
+) -> None:
+ """Test that cell names and configs are forwarded during lazy reload."""
+ content = dedent(
+ """\
+ import marimo
+ app = marimo.App()
+
+ @app.cell(hide_code=True)
+ def my_named_cell():
+ x = 1
+ return x
+ """
+ )
+ app_file_manager = create_test_app_file_manager(tmp_path, content)
+ mock_session.app_file_manager = app_file_manager
+
+ strategy = EditModeReloadStrategy(config_manager_lazy)
+ cell_ids = list(app_file_manager.app.cell_manager.cell_ids())
+ changed_cell_ids = set(cell_ids)
+
+ strategy.handle_reload(mock_session, changed_cell_ids=changed_cell_ids)
+
+ # Find the UpdateCellCodesNotification
+ update_codes_calls = [
+ call
+ for call in mock_session.notify.call_args_list
+ if isinstance(call[0][0], UpdateCellCodesNotification)
+ ]
+ assert len(update_codes_calls) == 1
+ notification = update_codes_calls[0][0][0]
+
+ # Verify names and configs are included
+ assert notification.names == ["my_named_cell"]
+ assert len(notification.configs) == 1
+ assert notification.configs[0].hide_code is True
+ assert notification.configs[0].disabled is False
+ assert notification.code_is_stale is True
+
+
+def test_edit_mode_reload_sends_names_and_configs_autorun(
+ tmp_path: Path, mock_session: MagicMock, config_manager_autorun
+) -> None:
+ """Test that cell names and configs are forwarded during autorun reload."""
+ content = dedent(
+ """\
+ import marimo
+ app = marimo.App()
+
+ @app.cell(hide_code=True)
+ def my_named_cell():
+ x = 1
+ return x
+ """
+ )
+ app_file_manager = create_test_app_file_manager(tmp_path, content)
+ mock_session.app_file_manager = app_file_manager
+
+ strategy = EditModeReloadStrategy(config_manager_autorun)
+ cell_ids = list(app_file_manager.app.cell_manager.cell_ids())
+ changed_cell_ids = set(cell_ids)
+
+ strategy.handle_reload(mock_session, changed_cell_ids=changed_cell_ids)
+
+ # Find the UpdateCellCodesNotification (also sent in autorun path)
+ update_codes_calls = [
+ call
+ for call in mock_session.notify.call_args_list
+ if isinstance(call[0][0], UpdateCellCodesNotification)
+ ]
+ assert len(update_codes_calls) == 1
+ notification = update_codes_calls[0][0][0]
+
+ # Verify names and configs are included
+ assert notification.names == ["my_named_cell"]
+ assert notification.configs[0].hide_code is True
+ # In autorun mode, code should not be stale
+ assert notification.code_is_stale is False
+
+ # SyncGraphCommand should still be sent for execution
+ sync_calls = [
+ call
+ for call in mock_session.put_control_request.call_args_list
+ if isinstance(call[0][0], SyncGraphCommand)
+ ]
+ assert len(sync_calls) == 1
+
+
+def test_edit_mode_reload_multiple_cells_mixed_configs(
+ tmp_path: Path, mock_session: MagicMock, config_manager_lazy
+) -> None:
+ """Test reload with multiple cells having different configs."""
+ content = dedent(
+ """\
+ import marimo
+ app = marimo.App()
+
+ @app.cell(hide_code=True)
+ def setup():
+ import pandas as pd
+ return (pd,)
+
+ @app.cell(disabled=True)
+ def disabled_cell():
+ x = 1
+ return x
+
+ @app.cell
+ def _():
+ y = 2
+ return y
+ """
+ )
+ app_file_manager = create_test_app_file_manager(tmp_path, content)
+ mock_session.app_file_manager = app_file_manager
+
+ strategy = EditModeReloadStrategy(config_manager_lazy)
+ cell_ids = list(app_file_manager.app.cell_manager.cell_ids())
+ changed_cell_ids = set(cell_ids)
+
+ strategy.handle_reload(mock_session, changed_cell_ids=changed_cell_ids)
+
+ update_codes_calls = [
+ call
+ for call in mock_session.notify.call_args_list
+ if isinstance(call[0][0], UpdateCellCodesNotification)
+ ]
+ assert len(update_codes_calls) == 1
+ notification = update_codes_calls[0][0][0]
+
+ # Verify all 3 cells have names and configs
+ assert len(notification.names) == 3
+ assert len(notification.configs) == 3
+ assert len(notification.codes) == 3
+ assert len(notification.cell_ids) == 3
+
+ assert notification.names[0] == "setup"
+ assert notification.configs[0].hide_code is True
+ assert notification.configs[0].disabled is False
+
+ assert notification.names[1] == "disabled_cell"
+ assert notification.configs[1].hide_code is False
+ assert notification.configs[1].disabled is True
+
+ # Anonymous cell gets underscore name
+ assert notification.names[2] == "_"
+ assert notification.configs[2].hide_code is False
+ assert notification.configs[2].disabled is False
+
+
+def test_reload_detects_config_only_changes(
+ tmp_path: Path,
+) -> None:
+ """Test that reload() detects config-only changes (e.g., hide_code added)."""
+ initial_content = dedent(
+ """\
+ import marimo
+ app = marimo.App()
+
+ @app.cell
+ def my_cell():
+ x = 1
+ return x
+ """
+ )
+ test_file = tmp_path / "test.py"
+ test_file.write_text(initial_content)
+ app_file_manager = AppFileManager(filename=str(test_file))
+
+ # Confirm initial state: no hide_code
+ cell_ids_before = list(app_file_manager.app.cell_manager.cell_ids())
+ configs_before = list(app_file_manager.app.cell_manager.configs())
+ assert len(cell_ids_before) == 1
+ assert configs_before[0].hide_code is False
+
+ # Now externally modify to add hide_code=True (code stays the same)
+ modified_content = dedent(
+ """\
+ import marimo
+ app = marimo.App()
+
+ @app.cell(hide_code=True)
+ def my_cell():
+ x = 1
+ return x
+ """
+ )
+ test_file.write_text(modified_content)
+
+ changed = app_file_manager.reload()
+
+ # Should detect the config change even though code is identical
+ assert len(changed) == 1
+
+ # Verify the new config is loaded
+ configs_after = list(app_file_manager.app.cell_manager.configs())
+ assert configs_after[0].hide_code is True
+
+
+def test_reload_detects_disabled_config_change(
+ tmp_path: Path,
+) -> None:
+ """Test that reload() detects disabled config change."""
+ initial_content = dedent(
+ """\
+ import marimo
+ app = marimo.App()
+
+ @app.cell
+ def my_cell():
+ x = 1
+ return x
+ """
+ )
+ test_file = tmp_path / "test.py"
+ test_file.write_text(initial_content)
+ app_file_manager = AppFileManager(filename=str(test_file))
+
+ modified_content = dedent(
+ """\
+ import marimo
+ app = marimo.App()
+
+ @app.cell(disabled=True)
+ def my_cell():
+ x = 1
+ return x
+ """
+ )
+ test_file.write_text(modified_content)
+
+ changed = app_file_manager.reload()
+ assert len(changed) == 1
+
+ configs_after = list(app_file_manager.app.cell_manager.configs())
+ assert configs_after[0].disabled is True
+
+
+def test_reload_detects_name_only_changes(
+ tmp_path: Path,
+) -> None:
+ """Test that reload() detects name-only changes (cell function renamed)."""
+ initial_content = dedent(
+ """\
+ import marimo
+ app = marimo.App()
+
+ @app.cell
+ def old_name():
+ x = 1
+ return x
+ """
+ )
+ test_file = tmp_path / "test.py"
+ test_file.write_text(initial_content)
+ app_file_manager = AppFileManager(filename=str(test_file))
+
+ names_before = list(app_file_manager.app.cell_manager.names())
+ assert names_before[0] == "old_name"
+
+ # Now externally rename the cell function (code stays the same)
+ modified_content = dedent(
+ """\
+ import marimo
+ app = marimo.App()
+
+ @app.cell
+ def new_name():
+ x = 1
+ return x
+ """
+ )
+ test_file.write_text(modified_content)
+
+ changed = app_file_manager.reload()
+
+ # Should detect the name change
+ assert len(changed) == 1
+
+ names_after = list(app_file_manager.app.cell_manager.names())
+ assert names_after[0] == "new_name"
+
+
+def test_reload_no_changes_returns_empty(
+ tmp_path: Path,
+) -> None:
+ """Test that reload() returns empty set when nothing changed."""
+ content = dedent(
+ """\
+ import marimo
+ app = marimo.App()
+
+ @app.cell
+ def my_cell():
+ x = 1
+ return x
+ """
+ )
+ test_file = tmp_path / "test.py"
+ test_file.write_text(content)
+ app_file_manager = AppFileManager(filename=str(test_file))
+
+ # Reload without modifying the file
+ changed = app_file_manager.reload()
+
+ assert len(changed) == 0
+
+
+def test_reload_detects_only_changed_cell_in_multi_cell(
+ tmp_path: Path,
+) -> None:
+ """Test that reload only flags the cell whose config changed."""
+ initial_content = dedent(
+ """\
+ import marimo
+ app = marimo.App()
+
+ @app.cell
+ def cell_a():
+ x = 1
+ return x
+
+ @app.cell
+ def cell_b():
+ y = 2
+ return y
+ """
+ )
+ test_file = tmp_path / "test.py"
+ test_file.write_text(initial_content)
+ app_file_manager = AppFileManager(filename=str(test_file))
+
+ cell_ids_before = list(app_file_manager.app.cell_manager.cell_ids())
+ assert len(cell_ids_before) == 2
+
+ # Only change the config of the second cell
+ modified_content = dedent(
+ """\
+ import marimo
+ app = marimo.App()
+
+ @app.cell
+ def cell_a():
+ x = 1
+ return x
+
+ @app.cell(hide_code=True)
+ def cell_b():
+ y = 2
+ return y
+ """
+ )
+ test_file.write_text(modified_content)
+
+ changed = app_file_manager.reload()
+
+ # Only the second cell should be flagged as changed
+ assert len(changed) == 1
+
+ cell_ids_after = list(app_file_manager.app.cell_manager.cell_ids())
+ names_after = list(app_file_manager.app.cell_manager.names())
+ configs_after = list(app_file_manager.app.cell_manager.configs())
+
+ # First cell unchanged
+ assert names_after[0] == "cell_a"
+ assert configs_after[0].hide_code is False
+
+ # Second cell has new config
+ assert names_after[1] == "cell_b"
+ assert configs_after[1].hide_code is True
+
+ # The changed cell ID should be cell_b's ID
+ assert changed == {cell_ids_after[1]}
+
+
+async def test_file_change_coordinator_config_only_change(
+ tmp_path: Path, mock_session: MagicMock
+) -> None:
+ """Test end-to-end: coordinator detects and handles config-only changes."""
+ initial_content = dedent(
+ """\
+ import marimo
+ app = marimo.App()
+
+ @app.cell
+ def my_cell():
+ x = 1
+ return x
+ """
+ )
+ test_file = tmp_path / "test.py"
+ test_file.write_text(initial_content)
+
+ app_file_manager = AppFileManager(filename=str(test_file))
+ mock_session.app_file_manager = app_file_manager
+
+ strategy = MagicMock()
+ coordinator = FileChangeCoordinator(strategy)
+
+ # Externally add hide_code=True only (same code)
+ test_file.write_text(
+ dedent(
+ """\
+ import marimo
+ app = marimo.App()
+
+ @app.cell(hide_code=True)
+ def my_cell():
+ x = 1
+ return x
+ """
+ )
+ )
+
+ result = await coordinator.handle_change(test_file, mock_session)
+
+ assert result.handled
+ assert result.error is None
+ assert result.changed_cell_ids is not None
+ assert len(result.changed_cell_ids) == 1
+ strategy.handle_reload.assert_called_once()