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.

Emit document transactions from `--watch` file reload (#8846)

Trevor Manz70a09115fbf9
diff --git a/frontend/src/core/islands/main.ts b/frontend/src/core/islands/main.ts
index 57a375d888..18fe949958 100644
--- a/frontend/src/core/islands/main.ts
+++ b/frontend/src/core/islands/main.ts
@@ -113,7 +113,6 @@ export async function initialize() {
case "installing-package-alert":
case "completion-result":
case "reload":
- case "update-cell-codes":
case "update-cell-ids":
case "focus-cell":
case "variables":
diff --git a/frontend/src/core/websocket/useMarimoKernelConnection.tsx b/frontend/src/core/websocket/useMarimoKernelConnection.tsx
index d59c7953bb..709b52b768 100644
--- a/frontend/src/core/websocket/useMarimoKernelConnection.tsx
+++ b/frontend/src/core/websocket/useMarimoKernelConnection.tsx
@@ -97,7 +97,7 @@ export function useMarimoKernelConnection(opts: {
const { autoInstantiate, sessionId, setCells } = opts;
const { showBoundary } = useErrorBoundary();
- const { handleCellMessage, setCellCodes, setCellIds } = useCellActions();
+ const { handleCellMessage, setCellIds } = useCellActions();
const actionsWithoutMiddleware = useCellActions({ skipMiddleware: true });
const handleDocumentTransaction = (
@@ -328,15 +328,6 @@ export function useMarimoKernelConnection(opts: {
case "focus-cell":
focusAndScrollCellOutputIntoView(msg.data.cell_id);
return;
- case "update-cell-codes":
- setCellCodes({
- codes: msg.data.codes,
- ids: msg.data.cell_ids,
- codeIsStale: msg.data.code_is_stale,
- names: msg.data.names,
- configs: msg.data.configs,
- });
- return;
case "update-cell-ids":
setCellIds({ cellIds: msg.data.cell_ids });
return;
diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.py
index b56a69f7d7..82e2a1ccec 100644
--- a/marimo/_cli/development/commands.py
+++ b/marimo/_cli/development/commands.py
@@ -311,7 +311,6 @@ def _generate_server_api_schema() -> dict[str, Any]:
notifications.QueryParamsAppendNotification,
notifications.QueryParamsDeleteNotification,
notifications.QueryParamsClearNotification,
- notifications.UpdateCellCodesNotification,
notifications.UpdateCellIdsNotification,
notifications.FocusCellNotification,
notifications.NotificationMessage,
diff --git a/marimo/_code_mode/_context.py b/marimo/_code_mode/_context.py
index c5ef494dae..d9679a750b 100644
--- a/marimo/_code_mode/_context.py
+++ b/marimo/_code_mode/_context.py
@@ -55,7 +55,6 @@ from marimo._messaging.notebook.document import NotebookCell, NotebookDocument
from marimo._messaging.notification import (
NotebookDocumentTransactionNotification,
Notification,
- UpdateCellCodesNotification,
)
from marimo._messaging.notification_utils import broadcast_notification
from marimo._runtime.commands import (
@@ -318,19 +317,6 @@ class AsyncCodeModeContext:
self._dry_run_compile(ops)
await self._apply_ops(ops, cells_to_run)
elif cells_to_run:
- # run_cell was called without any structural ops — just re-run.
- # Notify the frontend that these cells are no longer stale so
- # it clears edited/lastCodeRun (covers the two-step pattern:
- # edit_cell in one flush, run_cell in a separate flush).
- valid = cells_to_run & set(self.graph.cells.keys())
- if valid:
- self.notify(
- UpdateCellCodesNotification(
- cell_ids=list(valid),
- codes=[self.graph.cells[cid].code for cid in valid],
- code_is_stale=False,
- )
- )
await self._kernel._run_cells(cells_to_run)
# Flush queued UI updates as a single batch.
diff --git a/marimo/_internal/notifications.py b/marimo/_internal/notifications.py
index b4b5d4b694..5afdce7838 100644
--- a/marimo/_internal/notifications.py
+++ b/marimo/_internal/notifications.py
@@ -39,7 +39,6 @@ from marimo._messaging.notification import (
SQLTablePreviewNotification,
StartupLogsNotification,
UIElementMessageNotification,
- UpdateCellCodesNotification,
UpdateCellIdsNotification,
ValidateSQLResultNotification,
VariableDeclarationNotification,
@@ -86,7 +85,6 @@ __all__ = [
"SecretKeysResultNotification",
"StartupLogsNotification",
"UIElementMessageNotification",
- "UpdateCellCodesNotification",
"UpdateCellIdsNotification",
"VariableDeclarationNotification",
"VariableValue",
diff --git a/marimo/_messaging/notification.py b/marimo/_messaging/notification.py
index 6aa076b41d..3aa1fe3457 100644
--- a/marimo/_messaging/notification.py
+++ b/marimo/_messaging/notification.py
@@ -745,25 +745,6 @@ class FocusCellNotification(Notification, tag="focus-cell"):
cell_id: CellId_t
-class UpdateCellCodesNotification(Notification, tag="update-cell-codes"):
- """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"):
"""Available secret keys from secret providers.
@@ -880,7 +861,6 @@ NotificationMessage = Union[
CacheInfoNotification,
# Kiosk
FocusCellNotification,
- UpdateCellCodesNotification,
UpdateCellIdsNotification,
# Document
NotebookDocumentTransactionNotification,
diff --git a/marimo/_schemas/generated/notifications.yaml b/marimo/_schemas/generated/notifications.yaml
index 5f56ede95e..b33410532e 100644
--- a/marimo/_schemas/generated/notifications.yaml
+++ b/marimo/_schemas/generated/notifications.yaml
@@ -2,6 +2,9 @@
components:
schemas:
AlertNotification:
+ description: "User-facing alert message.\n\nAttributes:\n title: Alert title.\n\
+ \ description: Alert body (may contain HTML).\n variant: Visual variant\
+ \ (e.g., \"danger\")."
properties:
description:
type: string
@@ -23,6 +26,10 @@ components:
title: AlertNotification
type: object
BannerNotification:
+ description: "Persistent banner message at top of notebook.\n\nAttributes:\n\
+ \ title: Banner title.\n description: Banner body (may contain HTML).\n\
+ \ variant: Visual variant (e.g., \"danger\").\n action: Optional user\
+ \ action (e.g., \"restart\")."
properties:
action:
anyOf:
@@ -50,7 +57,8 @@ components:
title: BannerNotification
type: object
CacheClearedNotification:
- description: Result of clearing cache.
+ description: "Execution cache cleared result.\n\nAttributes:\n bytes_freed:\
+ \ Bytes freed by clearing cache."
properties:
bytes_freed:
type: integer
@@ -63,7 +71,10 @@ components:
title: CacheClearedNotification
type: object
CacheInfoNotification:
- description: Cache statistics information.
+ description: "Execution cache statistics.\n\nAttributes:\n hits: Cache hits.\n\
+ \ misses: Cache misses.\n time: Time spent on cache operations (seconds).\n\
+ \ disk_to_free: Disk space that could be freed (bytes).\n disk_total:\
+ \ Total disk space used (bytes)."
properties:
disk_to_free:
type: integer
@@ -118,14 +129,16 @@ components:
title: CellConfig
type: object
CellNotification:
- description: "Op to transition a cell.\n\n A CellNotification's data has\
- \ some optional fields:\n\n output - a CellOutput\n console \
- \ - a CellOutput (console msg to append), or a list of\n \
- \ CellOutputs\n status - execution status\n stale_inputs\
- \ - whether the cell has stale inputs (variables, modules, ...)\n run_id\
- \ - the run associated with this cell.\n serialization - the serialization\
- \ status of the cell\n\n Omitting a field means that its value should be\
- \ unchanged!\n\n And one required field:\n\n cell_id - the cell id"
+ description: "Updates a cell's state in the frontend.\n\nOnly fields that are\
+ \ set (not None) will update the cell state.\nOmitting a field leaves that\
+ \ aspect unchanged.\n\nAttributes:\n cell_id: Unique identifier of the\
+ \ cell being updated.\n output: Cell's output. Use CellOutput.empty() to\
+ \ clear.\n console: Console messages. Single/list appends, [] clears, None\
+ \ unchanged.\n status: Execution status (idle/running/stale/queued/disabled-transitively).\n\
+ \ stale_inputs: Whether cell has stale inputs from changed dependencies.\n\
+ \ run_id: Execution run ID for tracing. Auto-set from context.\n serialization:\
+ \ Serialization status (TopLevelHints).\n timestamp: Creation timestamp,\
+ \ auto-set."
properties:
cell_id:
type: string
@@ -224,7 +237,9 @@ components:
- application/vnd.marimo+mimebundle
- application/vnd.marimo+traceback
- application/vnd.vega.v5+json
+ - application/vnd.vega.v6+json
- application/vnd.vegalite.v5+json
+ - application/vnd.vegalite.v6+json
- image/avif
- image/bmp
- image/gif
@@ -236,6 +251,7 @@ components:
- text/html
- text/latex
- text/markdown
+ - text/password
- text/plain
- video/mp4
- video/mpeg
@@ -324,7 +340,7 @@ components:
title: ColumnStats
type: object
CompletedRunNotification:
- description: Written on run completion (of submitted cells and their descendants.
+ description: Run of submitted cells and descendants completed.
properties:
op:
enum:
@@ -350,7 +366,9 @@ components:
title: CompletionOption
type: object
CompletionResultNotification:
- description: Code completion result.
+ description: "Code completion result from language server.\n\nAttributes:\n\
+ \ completion_id: Request ID this responds to.\n prefix_length: Length\
+ \ of prefix to replace.\n options: Completion options to display."
properties:
completion_id:
type: string
@@ -394,7 +412,9 @@ components:
title: CycleError
type: object
DataColumnPreviewNotification:
- description: Preview of a column in a dataset.
+ description: "Data column preview with stats and visualization.\n\nInherits\
+ \ all ColumnPreview attributes.\n\nAttributes:\n table_name: Table containing\
+ \ the column.\n column_name: Column being previewed."
properties:
chart_code:
anyOf:
@@ -478,6 +498,8 @@ components:
title: DataSourceConnection
type: object
DataSourceConnectionsNotification:
+ description: "Available data source connections for SQL cells.\n\nAttributes:\n\
+ \ connections: Available data source connections."
properties:
connections:
items:
@@ -620,7 +642,9 @@ components:
title: Database
type: object
DatasetsNotification:
- description: List of datasets.
+ description: "Available datasets for data explorer.\n\nAttributes:\n tables:\
+ \ Available data tables/datasets.\n clear_channel: If set, clears tables\
+ \ from this channel first."
properties:
clear_channel:
anyOf:
@@ -644,6 +668,8 @@ components:
title: DatasetsNotification
type: object
FocusCellNotification:
+ description: "Focuses a cell (kiosk mode).\n\nAttributes:\n cell_id: Cell\
+ \ to focus."
properties:
cell_id:
type: string
@@ -656,7 +682,10 @@ components:
title: FocusCellNotification
type: object
FunctionCallResultNotification:
- description: Result of calling a function.
+ description: "Result of a frontend-initiated function call.\n\nAttributes:\n\
+ \ function_call_id: ID matching the original request.\n return_value:\
+ \ Function return value as JSON.\n status: Human-readable success/failure\
+ \ status."
properties:
function_call_id:
type: string
@@ -674,7 +703,9 @@ components:
title: FunctionCallResultNotification
type: object
HumanReadableStatus:
- description: Human-readable status.
+ description: "Human-readable status for operation results.\n\nAttributes:\n\
+ \ code: Status code (\"ok\" or \"error\").\n title: Optional short title.\n\
+ \ message: Optional detailed description."
properties:
code:
enum:
@@ -712,6 +743,10 @@ components:
title: ImportStarError
type: object
InstallingPackageAlertNotification:
+ description: "Package installation progress with streaming logs.\n\nAttributes:\n\
+ \ packages: Package name to status (queued/installing/installed/failed).\n\
+ \ logs: Optional streaming logs per package.\n log_status: Log stream\
+ \ status (append/start/done)."
properties:
log_status:
anyOf:
@@ -745,7 +780,7 @@ components:
title: InstallingPackageAlertNotification
type: object
InterruptedNotification:
- description: Written when the kernel is interrupted by the user.
+ description: Kernel was interrupted by user (SIGINT/Ctrl+C).
properties:
op:
enum:
@@ -755,6 +790,11 @@ components:
title: InterruptedNotification
type: object
KernelCapabilitiesNotification:
+ description: "Kernel capabilities detected at startup.\n\nAll fields auto-detected\
+ \ in __post_init__.\n\nAttributes:\n terminal: Terminal access (unavailable\
+ \ on Windows/Pyodide).\n pylsp: Python Language Server Protocol installed.\n\
+ \ ty: ty type checker installed.\n basedpyright: basedpyright type checker\
+ \ installed."
properties:
basedpyright:
default: false
@@ -762,23 +802,35 @@ components:
pylsp:
default: false
type: boolean
- terminal:
+ pyrefly:
default: false
type: boolean
- ty:
+ terminal:
default: false
type: boolean
- pyrefly:
+ ty:
default: false
type: boolean
required: []
title: KernelCapabilitiesNotification
type: object
KernelReadyNotification:
- description: Kernel is ready for execution.
+ description: "Kernel ready for execution. First notification sent at startup.\n\
+ \nAttributes:\n cell_ids: Cell IDs in order.\n codes: Source code for\
+ \ each cell.\n names: Cell names/titles.\n layout: Notebook layout config.\n\
+ \ configs: Per-cell configuration.\n resumed: Whether resumed from previous\
+ \ session.\n ui_values: Previous UI element values if resumed.\n last_executed_code:\
+ \ Last executed code per cell if resumed.\n last_execution_time: Last execution\
+ \ time per cell if resumed.\n app_config: Application configuration.\n\
+ \ kiosk: Whether running in kiosk mode.\n capabilities: Available kernel\
+ \ capabilities.\n auto_instantiated: Whether cells already executed (run\
+ \ mode)."
properties:
app_config:
$ref: '#/components/schemas/_AppConfig'
+ auto_instantiated:
+ default: false
+ type: boolean
capabilities:
$ref: '#/components/schemas/KernelCapabilitiesNotification'
cell_ids:
@@ -1013,6 +1065,12 @@ components:
title: MarimoSyntaxError
type: object
MissingPackageAlertNotification:
+ description: "Alert for missing packages with install option.\n\nAttributes:\n\
+ \ packages: Missing package names.\n isolated: Whether auto-install\
+ \ is possible in this environment.\n source: Which Python environment to\
+ \ install into. \"kernel\" (default)\n installs in the kernel's\
+ \ venv; \"server\" installs in the\n server's own Python env (e.g.\
+ \ for formatter tools like ruff)."
properties:
isolated:
type: boolean
@@ -1023,6 +1081,11 @@ components:
items:
type: string
type: array
+ source:
+ default: kernel
+ enum:
+ - kernel
+ - server
required:
- op
- packages
@@ -1047,6 +1110,8 @@ components:
title: MultipleDefinitionError
type: object
QueryParamsAppendNotification:
+ description: "Appends value to URL query parameter.\n\nAttributes:\n key:\
+ \ Query parameter key.\n value: Value to append."
properties:
key:
type: string
@@ -1062,6 +1127,7 @@ components:
title: QueryParamsAppendNotification
type: object
QueryParamsClearNotification:
+ description: Clears all URL query parameters.
properties:
op:
enum:
@@ -1071,6 +1137,9 @@ components:
title: QueryParamsClearNotification
type: object
QueryParamsDeleteNotification:
+ description: "Deletes URL query parameter values.\n\nAttributes:\n key: Query\
+ \ parameter key.\n value: Specific value to delete. If None, deletes all\
+ \ values for key."
properties:
key:
type: string
@@ -1088,7 +1157,8 @@ components:
title: QueryParamsDeleteNotification
type: object
QueryParamsSetNotification:
- description: Set query parameters.
+ description: "Sets URL query parameter, replacing existing values.\n\nAttributes:\n\
+ \ key: Query parameter key.\n value: Value(s) to set."
properties:
key:
type: string
@@ -1108,6 +1178,7 @@ components:
title: QueryParamsSetNotification
type: object
ReconnectedNotification:
+ description: WebSocket reconnection confirmed.
properties:
op:
enum:
@@ -1117,6 +1188,7 @@ components:
title: ReconnectedNotification
type: object
ReloadNotification:
+ description: Instructs frontend to reload the page.
properties:
op:
enum:
@@ -1126,7 +1198,9 @@ components:
title: ReloadNotification
type: object
RemoveUIElementsNotification:
- description: Invalidate UI elements for a given cell.
+ description: "Removes UI elements associated with a cell.\n\nSent when cell\
+ \ is re-executed or deleted.\n\nAttributes:\n cell_id: Cell whose UI elements\
+ \ should be removed."
properties:
cell_id:
type: string
@@ -1139,7 +1213,8 @@ components:
title: RemoveUIElementsNotification
type: object
SQLDatabaseMetadata:
- description: Metadata for a SQL database, including its dialect and name.
+ description: "SQL database metadata.\n\nAttributes:\n connection: Connection\
+ \ identifier.\n database: Database name."
properties:
connection:
type: string
@@ -1151,7 +1226,9 @@ components:
title: SQLDatabaseMetadata
type: object
SQLMetadata:
- description: Metadata for a SQL database.
+ description: "SQL database and schema metadata.\n\nAttributes:\n connection:\
+ \ Connection identifier.\n database: Database name.\n schema: Schema\
+ \ name."
properties:
connection:
type: string
@@ -1170,7 +1247,9 @@ components:
title: SQLMetadata
type: object
SQLSchemaListPreviewNotification:
- description: Preview of a list of schemas in a database.
+ description: "List of SQL schemas in a database.\n\nAttributes:\n request_id:\
+ \ Request ID this responds to.\n metadata: Database and schema metadata.\n\
+ \ schemas: Schemas in database.\n error: Error message if failed."
properties:
error:
anyOf:
@@ -1196,7 +1275,9 @@ components:
title: SQLSchemaListPreviewNotification
type: object
SQLTableListPreviewNotification:
- description: Preview of a list of tables in a schema.
+ description: "List of SQL tables in a schema.\n\nAttributes:\n request_id:\
+ \ Request ID this responds to.\n metadata: Database and schema metadata.\n\
+ \ tables: Tables in schema.\n error: Error message if failed."
properties:
error:
anyOf:
@@ -1222,7 +1303,9 @@ components:
title: SQLTableListPreviewNotification
type: object
SQLTablePreviewNotification:
- description: Preview of a table in a SQL database.
+ description: "SQL table preview.\n\nAttributes:\n request_id: Request ID\
+ \ this responds to.\n metadata: Database and schema metadata.\n table:\
+ \ Table data (None if error).\n error: Error message if failed."
properties:
error:
anyOf:
@@ -1261,7 +1344,9 @@ components:
title: Schema
type: object
SecretKeysResultNotification:
- description: Result of listing secret keys.
+ description: "Available secret keys from secret providers.\n\nAttributes:\n\
+ \ request_id: Request ID this responds to.\n secrets: Secret keys with\
+ \ provider info."
properties:
op:
enum:
@@ -1296,37 +1381,6 @@ components:
- keys
title: SecretKeysWithProvider
type: object
- UIElementMessageNotification:
- description: Send a message to a UI element.
- properties:
- buffers:
- anyOf:
- - items:
- contentEncoding: base64
- type: string
- type: array
- - type: 'null'
- default: null
- message:
- type: object
- model_id:
- anyOf:
- - type: string
- - type: 'null'
- op:
- enum:
- - send-ui-element-message
- ui_element:
- anyOf:
- - type: string
- - type: 'null'
- required:
- - op
- - ui_element
- - model_id
- - message
- title: UIElementMessageNotification
- type: object
SetupRootError:
properties:
edges_with_vars:
@@ -1405,6 +1459,8 @@ components:
title: SqlParseResult
type: object
StartupLogsNotification:
+ description: "Streaming kernel startup logs.\n\nAttributes:\n content: Log\
+ \ content to display.\n status: Stream status (start/append/done)."
properties:
content:
type: string
@@ -1422,6 +1478,32 @@ components:
- status
title: StartupLogsNotification
type: object
+ UIElementMessageNotification:
+ description: "Sends a message to a UI element/widget.\n\nAttributes:\n ui_element:\
+ \ UI element identifier.\n message: Message payload as dictionary.\n \
+ \ buffers: Optional binary buffers for large data."
+ properties:
+ buffers:
+ anyOf:
+ - items:
+ contentEncoding: base64
+ type: string
+ type: array
+ - type: 'null'
+ default: null
+ message:
+ type: object
+ op:
+ enum:
+ - send-ui-element-message
+ ui_element:
+ type: string
+ required:
+ - op
+ - ui_element
+ - message
+ title: UIElementMessageNotification
+ type: object
UnknownError:
properties:
error_type:
@@ -1439,35 +1521,9 @@ components:
- msg
title: UnknownError
type: object
- UpdateCellCodesNotification:
- properties:
- cell_ids:
- items:
- type: string
- type: array
- code_is_stale:
- type: boolean
- codes:
- items:
- type: string
- type: array
- op:
- enum:
- - update-cell-codes
- required:
- - op
- - cell_ids
- - codes
- - code_is_stale
- title: UpdateCellCodesNotification
- type: object
UpdateCellIdsNotification:
- description: 'Update the cell ID ordering of the cells in the notebook.
-
-
- Right now we send the entire list of cell IDs,
-
- but in the future we might want to send change-deltas.'
+ description: "Updates cell ordering in notebook.\n\nAttributes:\n cell_ids:\
+ \ Complete ordered list of cell IDs."
properties:
cell_ids:
items:
@@ -1482,6 +1538,9 @@ components:
title: UpdateCellIdsNotification
type: object
ValidateSQLResultNotification:
+ description: "SQL query validation result.\n\nAttributes:\n request_id: Request\
+ \ ID this responds to.\n parse_result: SQL parsing result.\n validate_result:\
+ \ Catalog validation result.\n error: Error message if failed."
properties:
error:
anyOf:
@@ -1509,6 +1568,9 @@ components:
title: ValidateSQLResultNotification
type: object
VariableDeclarationNotification:
+ description: "Variable declaration and usage for dataflow graph.\n\nAttributes:\n\
+ \ name: Variable name.\n declared_by: Cell IDs that define this variable.\n\
+ \ used_by: Cell IDs that use this variable."
properties:
declared_by:
items:
@@ -1527,6 +1589,9 @@ components:
title: VariableDeclarationNotification
type: object
VariableValue:
+ description: "Variable value and type for variables panel.\n\nAttributes:\n\
+ \ name: Variable name.\n value: String representation of value.\n \
+ \ datatype: Data type as string."
properties:
datatype:
anyOf:
@@ -1545,7 +1610,8 @@ components:
title: VariableValue
type: object
VariableValuesNotification:
- description: List of variables and their types/values.
+ description: "Current variable values.\n\nAttributes:\n variables: Variables\
+ \ with current values and types."
properties:
op:
enum:
@@ -1560,7 +1626,8 @@ components:
title: VariableValuesNotification
type: object
VariablesNotification:
- description: List of variable declarations.
+ description: "Variable dataflow graph.\n\nAttributes:\n variables: Variable\
+ \ declarations and usage."
properties:
op:
enum:
@@ -1575,8 +1642,12 @@ components:
title: VariablesNotification
type: object
_AppConfig:
- description: "Program-specific configuration.\n\n Configuration for frontends\
- \ or runtimes that is specific to\n a single marimo program."
+ description: 'Program-specific configuration.
+
+
+ Configuration for frontends or runtimes that is specific to
+
+ a single marimo program.'
properties:
app_title:
anyOf:
diff --git a/marimo/_session/extensions/extensions.py b/marimo/_session/extensions/extensions.py
index 94c9f6c31a..e4736ef301 100644
--- a/marimo/_session/extensions/extensions.py
+++ b/marimo/_session/extensions/extensions.py
@@ -430,7 +430,6 @@ class ReplayExtension(SessionExtension, SessionEventListener):
"""Called when a command is received."""
from marimo._messaging.notification import (
FocusCellNotification,
- UpdateCellCodesNotification,
)
from marimo._runtime.commands import (
ExecuteCellsCommand,
@@ -444,22 +443,8 @@ class ReplayExtension(SessionExtension, SessionEventListener):
# Collect cell ids and codes
if isinstance(request, ExecuteCellsCommand):
cell_ids = request.cell_ids
- codes = request.codes
else:
cell_ids = request.run_ids
- codes = [request.cells[cell_id] for cell_id in cell_ids]
-
- # Send update cell codes notification
- if cell_ids:
- session.notify(
- UpdateCellCodesNotification(
- cell_ids=cell_ids,
- codes=codes,
- # Not stale because we just ran the code
- code_is_stale=False,
- ),
- from_consumer_id=from_consumer_id,
- )
# Send focus cell notification
if len(cell_ids) == 1:
diff --git a/marimo/_session/file_change_handler.py b/marimo/_session/file_change_handler.py
index 1e2310de42..c1ad37181c 100644
--- a/marimo/_session/file_change_handler.py
+++ b/marimo/_session/file_change_handler.py
@@ -12,12 +12,21 @@ from typing import TYPE_CHECKING, Optional, Protocol
from marimo import _loggers
from marimo._config.manager import MarimoConfigManager
+from marimo._messaging.notebook import DocumentChange
+from marimo._messaging.notebook.changes import (
+ CreateCell,
+ DeleteCell,
+ ReorderCells,
+ SetCode,
+ SetConfig,
+ SetName,
+ Transaction,
+)
from marimo._messaging.notification import (
+ NotebookDocumentTransactionNotification,
ReloadNotification,
- UpdateCellCodesNotification,
- UpdateCellIdsNotification,
)
-from marimo._runtime.commands import DeleteCellCommand, SyncGraphCommand
+from marimo._runtime.commands import SyncGraphCommand
from marimo._session.model import SessionMode
from marimo._types.ids import CellId_t
from marimo._utils import async_path
@@ -68,12 +77,9 @@ 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, 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())
+ codes = list(cell_manager.codes())
LOGGER.info(
f"File changed: {session.app_file_manager.path}. "
@@ -81,68 +87,86 @@ class EditModeReloadStrategy(ReloadStrategy):
f"changed_cell_ids: {changed_cell_ids}"
)
- # Send the updated cell IDs to the frontend
- session.notify(
- UpdateCellIdsNotification(cell_ids=cell_ids),
- from_consumer_id=None,
- )
+ # Build a transaction by diffing session.document vs new cell_manager.
+ doc = session.document
+ doc_ids = set(doc)
+ new_ids = set(cell_ids)
+ deleted = doc_ids - new_ids
+
+ changes: list[DocumentChange] = []
+
+ # Deletes
+ for cid in deleted:
+ changes.append(DeleteCell(cell_id=cid))
+
+ # Creates and updates
+ for cd in cell_manager.cell_data():
+ if cd.cell_id not in doc_ids:
+ changes.append(
+ CreateCell(
+ cell_id=cd.cell_id,
+ code=cd.code,
+ name=cd.name,
+ config=cd.config,
+ )
+ )
+ else:
+ doc_cell = doc.get_cell(cd.cell_id)
+ if cd.code != doc_cell.code:
+ changes.append(SetCode(cell_id=cd.cell_id, code=cd.code))
+ if cd.name != doc_cell.name:
+ changes.append(SetName(cell_id=cd.cell_id, name=cd.name))
+ if cd.config != doc_cell.config:
+ changes.append(
+ SetConfig(
+ cell_id=cd.cell_id,
+ column=cd.config.column,
+ disabled=cd.config.disabled,
+ hide_code=cd.config.hide_code,
+ )
+ )
+
+ # Reorder if the lists differ
+ if tuple(cell_ids) != tuple(doc.cell_ids):
+ changes.append(ReorderCells(cell_ids=tuple(cell_ids)))
+
+ if changes:
+ # Broadcast transaction — document.apply() applies to
+ # document and stamps the version before forwarding.
+ transaction = Transaction(
+ changes=tuple(changes), source="file-watch"
+ )
+ applied = session.document.apply(transaction)
+ session.notify(
+ NotebookDocumentTransactionNotification(transaction=applied),
+ from_consumer_id=None,
+ )
- # Check if we should auto-run cells based on config
+ # Auto-run changed cells if configured.
watcher_on_save = self._config_manager.get_config()["runtime"][
"watcher_on_save"
]
- should_autorun = watcher_on_save == "autorun"
-
- # Determine deleted cells
- deleted = {
- cell_id for cell_id in changed_cell_ids if cell_id not in cell_ids
- }
-
- # Auto-run cells if configured
- if should_autorun:
- 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,
- )
-
+ if watcher_on_save == "autorun":
+ changed_not_deleted = list(changed_cell_ids - deleted)
session.put_control_request(
SyncGraphCommand(
- cells=cells,
- run_ids=changed_cell_ids_list,
+ cells=dict(zip(cell_ids, codes)),
+ run_ids=changed_not_deleted,
+ delete_ids=list(deleted),
+ ),
+ from_consumer_id=None,
+ )
+ elif deleted:
+ # Even in lazy mode, sync deletions to the kernel so removed
+ # cells are cleaned up from the dependency graph.
+ session.put_control_request(
+ SyncGraphCommand(
+ cells=dict(zip(cell_ids, codes)),
+ run_ids=[],
delete_ids=list(deleted),
),
from_consumer_id=None,
)
- else:
- # Just send deletes and code updates
- for to_delete in deleted:
- session.put_control_request(
- DeleteCellCommand(cell_id=to_delete),
- from_consumer_id=None,
- )
- if cell_ids:
- session.notify(
- UpdateCellCodesNotification(
- cell_ids=cell_ids,
- codes=codes,
- code_is_stale=True,
- names=names,
- configs=configs,
- ),
- from_consumer_id=None,
- )
class RunModeReloadStrategy:
diff --git a/marimo/_session/state/session_view.py b/marimo/_session/state/session_view.py
index 27dd0d5a68..9dc2a3f502 100644
--- a/marimo/_session/state/session_view.py
+++ b/marimo/_session/state/session_view.py
@@ -26,7 +26,6 @@ from marimo._messaging.notification import (
StartupLogsNotification,
StorageNamespacesNotification,
UIElementMessageNotification,
- UpdateCellCodesNotification,
UpdateCellIdsNotification,
VariablesNotification,
VariableValue,
@@ -170,8 +169,6 @@ class SessionView:
self.last_executed_code: dict[CellId_t, str] = {}
# Map of cell id to the last cell execution time
self.last_execution_time: dict[CellId_t, float] = {}
- # Any stale code that was read from a file-watcher
- self.stale_code: Optional[UpdateCellCodesNotification] = None
# Aggregated model state — one snapshot per live model.
# Updates merge in; close removes the entry.
self.model_states: dict[WidgetModelId, ModelReplayState] = {}
@@ -393,12 +390,6 @@ class SessionView:
elif isinstance(notification, UpdateCellIdsNotification):
self.cell_ids = notification
- elif (
- isinstance(notification, UpdateCellCodesNotification)
- and notification.code_is_stale
- ):
- self.stale_code = notification
-
elif isinstance(notification, UIElementMessageNotification):
# TODO: Consider reducing to a single message per element
# (similar to ModelReplayState) instead of keeping the full
@@ -572,8 +563,6 @@ class SessionView:
all_notifications.extend(ui_messages)
all_notifications.extend(self.cell_notifications.values())
- if self.stale_code:
- all_notifications.append(self.stale_code)
# Only include startup logs if they are in progress (not done)
if self.startup_logs and self.startup_logs.status != "done":
all_notifications.append(self.startup_logs)
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index e4fbdf7c06..53c68bb6a2 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -2571,7 +2571,6 @@ components:
- $ref: '#/components/schemas/CacheClearedNotification'
- $ref: '#/components/schemas/CacheInfoNotification'
- $ref: '#/components/schemas/FocusCellNotification'
- - $ref: '#/components/schemas/UpdateCellCodesNotification'
- $ref: '#/components/schemas/UpdateCellIdsNotification'
- $ref: '#/components/schemas/NotebookDocumentTransactionNotification'
discriminator:
@@ -2611,7 +2610,6 @@ components:
storage-download-ready: '#/components/schemas/StorageDownloadReadyNotification'
storage-entries: '#/components/schemas/StorageEntriesNotification'
storage-namespaces: '#/components/schemas/StorageNamespacesNotification'
- update-cell-codes: '#/components/schemas/UpdateCellCodesNotification'
update-cell-ids: '#/components/schemas/UpdateCellIdsNotification'
validate-sql-result: '#/components/schemas/ValidateSQLResultNotification'
variable-values: '#/components/schemas/VariableValuesNotification'
@@ -5074,44 +5072,6 @@ components:
- msg
title: UnknownError
type: object
- UpdateCellCodesNotification:
- 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:
- $ref: '#/components/schemas/CellId'
- type: array
- code_is_stale:
- type: boolean
- codes:
- 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
- required:
- - op
- - cell_ids
- - codes
- - code_is_stale
- title: UpdateCellCodesNotification
- type: object
UpdateCellConfigCommand:
description: "Update cell configuration.\n\n Updates cell-level settings\
\ like disabled state, hide code, etc.\n\n Attributes:\n configs:\
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index 82314ebeed..c579ed2a23 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -4886,7 +4886,6 @@ export interface components {
| components["schemas"]["CacheClearedNotification"]
| components["schemas"]["CacheInfoNotification"]
| components["schemas"]["FocusCellNotification"]
- | components["schemas"]["UpdateCellCodesNotification"]
| components["schemas"]["UpdateCellIdsNotification"]
| components["schemas"]["NotebookDocumentTransactionNotification"];
};
@@ -6406,28 +6405,6 @@ export interface components {
/** @enum {unknown} */
type: "unknown";
};
- /**
- * UpdateCellCodesNotification
- * @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: components["schemas"]["CellId"][];
- code_is_stale: boolean;
- codes: string[];
- /** @default [] */
- configs?: components["schemas"]["CellConfig"][];
- /** @default [] */
- names?: string[];
- /** @enum {unknown} */
- op: "update-cell-codes";
- };
/**
* UpdateCellConfigCommand
* @description Update cell configuration.
diff --git a/scripts/generate_schemas.py b/scripts/generate_schemas.py
index 41fd223388..dbea1ddaa7 100755
--- a/scripts/generate_schemas.py
+++ b/scripts/generate_schemas.py
@@ -61,7 +61,6 @@ with app.setup:
o.QueryParamsDeleteNotification,
o.QueryParamsClearNotification,
o.FocusCellNotification,
- o.UpdateCellCodesNotification,
o.SecretKeysResultNotification,
o.CacheClearedNotification,
o.CacheInfoNotification,
diff --git a/tests/_code_mode/test_context.py b/tests/_code_mode/test_context.py
index 881722de09..164f39882d 100644
--- a/tests/_code_mode/test_context.py
+++ b/tests/_code_mode/test_context.py
@@ -20,7 +20,6 @@ from marimo._messaging.notebook.document import (
)
from marimo._messaging.notification import (
NotebookDocumentTransactionNotification,
- UpdateCellCodesNotification,
)
from marimo._runtime.commands import ExecuteCellCommand
from marimo._runtime.runtime import Kernel
@@ -48,14 +47,6 @@ def _tx_ops(k: Kernel) -> list[dict[str, object]]:
return ops
-def _code_notifs(k: Kernel) -> list[UpdateCellCodesNotification]:
- return [
- op
- for op in k.stream.operations
- if isinstance(op, UpdateCellCodesNotification)
- ]
-
-
def _clear_messages(k: Kernel) -> None:
k.stream.messages.clear()
@@ -642,7 +633,7 @@ class TestAutorunStaleState:
async def test_two_step_edit_then_run(self, k: Kernel) -> None:
"""edit_cell in one flush, run_cell in a separate flush should
- send code_is_stale=false so the frontend clears the stale state."""
+ execute the updated code."""
await k.run([ExecuteCellCommand(cell_id="0", code="x = 1")])
# Flush 1: edit only
@@ -658,7 +649,3 @@ class TestAutorunStaleState:
nb.run_cell("0")
assert k.globals["x"] == 42
-
- code_notifs = msgspec.to_builtins(_code_notifs(k))
- assert len(code_notifs) == 1
- assert code_notifs[0]["code_is_stale"] is False
diff --git a/tests/_internal/snapshots/internal_api.txt b/tests/_internal/snapshots/internal_api.txt
index d6c1cbe3f8..08bea94058 100644
--- a/tests/_internal/snapshots/internal_api.txt
+++ b/tests/_internal/snapshots/internal_api.txt
@@ -94,7 +94,6 @@ notifications
SecretKeysResultNotification
StartupLogsNotification
UIElementMessageNotification
- UpdateCellCodesNotification
UpdateCellIdsNotification
ValidateSQLResultNotification
VariableDeclarationNotification
diff --git a/tests/_server/api/endpoints/test_resume_session.py b/tests/_server/api/endpoints/test_resume_session.py
index 27d4584b49..f2665052a5 100644
--- a/tests/_server/api/endpoints/test_resume_session.py
+++ b/tests/_server/api/endpoints/test_resume_session.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import os
import time
from contextlib import contextmanager
-from typing import TYPE_CHECKING, Any, Optional
+from typing import TYPE_CHECKING, Optional
from marimo._config.manager import UserConfigManager
from marimo._messaging.notification import (
@@ -286,12 +286,13 @@ def test_resume_session_after_file_change(client: TestClient) -> None:
assert result.handled
data = websocket.receive_json()
- assert data == {
- "op": "update-cell-ids",
- "data": {"cell_ids": ["MJUe", "Hbol"], "op": "update-cell-ids"},
- }
- data = websocket.receive_json()
- assert data["op"] == "update-cell-codes"
+ assert data["op"] == "notebook-document-transaction"
+ tx = data["data"]["transaction"]
+ # Transaction should contain the new cell and reorder.
+ op_types = [op["type"] for op in tx["changes"]]
+ assert "create-cell" in op_types
+ assert "reorder-cells" in op_types
+ assert tx["source"] == "file-watch"
# Resume session with new ID (simulates refresh)
with client.websocket_connect(_create_ws_url("456")) as websocket:
@@ -302,24 +303,10 @@ def test_resume_session_after_file_change(client: TestClient) -> None:
# Check for KernelReady message
data = websocket.receive_json()
assert parse_raw(data["data"], KernelReadyNotification)
- messages: list[dict[str, Any]] = []
-
- # Wait for update-cell-ids message
- while True:
- data = websocket.receive_json()
- messages.append(data)
- if data["op"] == "update-cell-ids":
- break
-
- # 2 messages:
- # 1. banner
- # 2. update-cell-ids
- assert len(messages) == 2
- assert messages[0]["op"] == "banner"
- assert messages[1] == {
- "op": "update-cell-ids",
- "data": {"cell_ids": ["MJUe", "Hbol"], "op": "update-cell-ids"},
- }
+
+ # Banner notification (session replay)
+ data = websocket.receive_json()
+ assert data["op"] == "banner"
@contextmanager
diff --git a/tests/_server/test_sessions.py b/tests/_server/test_sessions.py
index 3be9bff538..08c2314d24 100644
--- a/tests/_server/test_sessions.py
+++ b/tests/_server/test_sessions.py
@@ -24,8 +24,8 @@ from marimo._config.manager import (
get_default_config_manager,
)
from marimo._messaging.notification import (
+ NotebookDocumentTransactionNotification,
NotificationMessage,
- UpdateCellCodesNotification,
)
from marimo._messaging.serde import deserialize_kernel_message
from marimo._messaging.types import KernelMessage
@@ -541,15 +541,13 @@ def __():
if len(session_consumer.notify_calls) > 0:
break
- # Check that UpdateCellCodes was sent with the new code
- update_ops = [
+ # Check that a document transaction was sent with the new code
+ tx_ops = [
op
for op in session_consumer.notify_calls
- if isinstance(op, UpdateCellCodesNotification)
+ if isinstance(op, NotebookDocumentTransactionNotification)
]
- assert len(update_ops) == 1
- assert "2" == update_ops[0].codes[0]
- assert update_ops[0].code_is_stale is True
+ assert len(tx_ops) >= 1
# Create another session for the same file
session_consumer2 = MockSessionConsumer()
@@ -584,17 +582,15 @@ def __():
update_ops = [
op
for op in session_consumer.notify_calls
- if isinstance(op, UpdateCellCodesNotification)
+ if isinstance(op, NotebookDocumentTransactionNotification)
]
update_ops2 = [
op
for op in session_consumer2.notify_calls
- if isinstance(op, UpdateCellCodesNotification)
+ if isinstance(op, NotebookDocumentTransactionNotification)
]
- assert len(update_ops) == 1
- assert len(update_ops2) == 1
- assert "3" == update_ops[0].codes[0]
- assert "3" == update_ops2[0].codes[0]
+ assert len(update_ops) >= 1
+ assert len(update_ops2) >= 1
# Close one session and verify the other still receives updates
session_manager.close_session(session_id)
@@ -621,10 +617,9 @@ def __():
update_ops2 = [
op
for op in session_consumer2.notify_calls
- if isinstance(op, UpdateCellCodesNotification)
+ if isinstance(op, NotebookDocumentTransactionNotification)
]
- assert len(update_ops2) == 1
- assert "4" == update_ops2[0].codes[0]
+ assert len(update_ops2) >= 1
finally:
# Cleanup
session_manager.shutdown()
@@ -769,27 +764,20 @@ async def test_watch_mode_with_watcher_on_save_autorun(tmp_path: Path) -> None:
)
)
- # Wait for the watcher to detect the change and send UpdateCellCodes
- update_ops: list[UpdateCellCodesNotification] = []
+ # Wait for the watcher to detect the change and send transaction
+ tx_ops: list[NotebookDocumentTransactionNotification] = []
for _ in range(20): # noqa: B007
await asyncio.sleep(0.1)
- update_ops = [
+ tx_ops = [
op
for op in session_consumer.notify_calls
- if isinstance(op, UpdateCellCodesNotification)
+ if isinstance(op, NotebookDocumentTransactionNotification)
]
- if update_ops:
+ if tx_ops:
break
- # Check that UpdateCellCodes was sent with code_is_stale=False (autorun)
- # 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
+ # Check that a document transaction was sent (autorun)
+ assert len(tx_ops) >= 1
# Verify that cells were queued for execution
assert session.session_view.add_control_request.called
@@ -887,15 +875,13 @@ async def test_watch_mode_with_watcher_on_save_lazy(tmp_path: Path) -> None:
if len(session_consumer.notify_calls) > 0:
break
- # Check that UpdateCellCodes was sent with code_is_stale=True (lazy)
- update_ops = [
+ # Check that a document transaction was sent (lazy mode)
+ tx_ops = [
op
for op in session_consumer.notify_calls
- if isinstance(op, UpdateCellCodesNotification)
+ if isinstance(op, NotebookDocumentTransactionNotification)
]
- assert len(update_ops) == 1
- assert "2" in update_ops[0].codes[0]
- assert update_ops[0].code_is_stale is True
+ assert len(tx_ops) >= 1
finally:
# Cleanup
@@ -1004,16 +990,13 @@ def __():
if len(operations) > 0:
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 = [
+ # Check that a document transaction was sent with the new code
+ tx_ops = [
op
for op in operations
- if isinstance(op, UpdateCellCodesNotification)
+ if isinstance(op, NotebookDocumentTransactionNotification)
]
- assert len(update_ops) >= 1
- assert any("2" == op.codes[0] for op in update_ops)
+ assert len(tx_ops) >= 1
finally:
# Cleanup
diff --git a/tests/_session/extensions/test_extensions.py b/tests/_session/extensions/test_extensions.py
index f272bf1b40..56bd4ad751 100644
--- a/tests/_session/extensions/test_extensions.py
+++ b/tests/_session/extensions/test_extensions.py
@@ -465,7 +465,7 @@ class TestReplayExtension:
)
extension.on_received_command(mock_session, cmd, None)
- assert mock_session.notify.call_count == 2
+ assert mock_session.notify.call_count == 1
extension.on_detach()
def test_sync_graph_command_replayed(
@@ -486,7 +486,7 @@ class TestReplayExtension:
)
extension.on_received_command(mock_session, cmd, None)
- assert mock_session.notify.call_count == 2
+ assert mock_session.notify.call_count == 1
extension.on_detach()
def test_other_commands_not_replayed(
diff --git a/tests/_session/state/test_session_view.py b/tests/_session/state/test_session_view.py
index 6ddf4c6cb6..dadb559cff 100644
--- a/tests/_session/state/test_session_view.py
+++ b/tests/_session/state/test_session_view.py
@@ -31,7 +31,6 @@ from marimo._messaging.notification import (
SQLTableListPreviewNotification,
SQLTablePreviewNotification,
StartupLogsNotification,
- UpdateCellCodesNotification,
UpdateCellIdsNotification,
VariableDeclarationNotification,
VariablesNotification,
@@ -1362,48 +1361,6 @@ def test_mark_auto_export(session_view: SessionView):
assert session_view.needs_export("session")
-def test_stale_code(session_view: SessionView) -> None:
- """Test that stale code is properly tracked and included in operations."""
- assert session_view.stale_code is None
-
- # Add stale code operation
- stale_code_op = UpdateCellCodesNotification(
- cell_ids=["cell1"],
- codes=["print('hello')"],
- code_is_stale=True,
- )
- session_view.add_notification(stale_code_op)
-
- # Verify stale code is tracked
- assert session_view.stale_code == stale_code_op
- assert session_view.stale_code in session_view.notifications
-
- # Add non-stale code operation
- non_stale_code_op = UpdateCellCodesNotification(
- cell_ids=["cell2"],
- codes=["print('world')"],
- code_is_stale=False,
- )
- session_view.add_notification(non_stale_code_op)
-
- # Verify non-stale code doesn't affect stale_code tracking
- assert session_view.stale_code == stale_code_op
- assert session_view.stale_code in session_view.notifications
-
- # Update stale code
- new_stale_code_op = UpdateCellCodesNotification(
- cell_ids=["cell3"],
- codes=["print('updated')"],
- code_is_stale=True,
- )
- session_view.add_notification(new_stale_code_op)
-
- # Verify stale code is updated
- assert session_view.stale_code == new_stale_code_op
- assert session_view.stale_code in session_view.notifications
- assert stale_code_op not in session_view.notifications
-
-
def test_dataset_filter_by_engine_and_variable(
session_view: SessionView,
) -> None:
diff --git a/tests/_session/test_file_change_handler.py b/tests/_session/test_file_change_handler.py
index eae264fcbe..1995a089f5 100644
--- a/tests/_session/test_file_change_handler.py
+++ b/tests/_session/test_file_change_handler.py
@@ -11,12 +11,21 @@ import pytest
from marimo._ast.cell import CellConfig
from marimo._config.manager import get_default_config_manager
+from marimo._messaging.notebook.changes import (
+ CreateCell,
+ DeleteCell,
+ ReorderCells,
+ SetCode,
+ SetConfig,
+ SetName,
+ Transaction,
+)
+from marimo._messaging.notebook.document import NotebookCell, NotebookDocument
from marimo._messaging.notification import (
+ NotebookDocumentTransactionNotification,
ReloadNotification,
- UpdateCellCodesNotification,
- UpdateCellIdsNotification,
)
-from marimo._runtime.commands import DeleteCellCommand, SyncGraphCommand
+from marimo._runtime.commands import SyncGraphCommand
from marimo._server.models.models import SaveNotebookRequest
from marimo._session.file_change_handler import (
EditModeReloadStrategy,
@@ -29,19 +38,116 @@ from marimo._types.ids import CellId_t
if TYPE_CHECKING:
from pathlib import Path
+SINGLE_CELL_NOTEBOOK = dedent(
+ """\
+ import marimo
+ app = marimo.App()
-def create_test_app_file_manager(
- tmp_path: Path, content: str
-) -> AppFileManager:
- """Create a test app file manager with the given content."""
+ @app.cell
+ def cell1():
+ x = 1
+ return x
+ """
+)
+
+
+def _make_app(tmp_path: Path, content: str) -> AppFileManager:
test_file = tmp_path / "test.py"
test_file.write_text(content)
return AppFileManager(filename=str(test_file))
+def _document_from(app_file_manager: AppFileManager) -> NotebookDocument:
+ cm = app_file_manager.app.cell_manager
+ return NotebookDocument(
+ [
+ NotebookCell(
+ id=cd.cell_id,
+ code=cd.code,
+ name=cd.name,
+ config=cd.config,
+ )
+ for cd in cm.cell_data()
+ ]
+ )
+
+
+def _get_transaction(mock_session: MagicMock) -> Transaction:
+ calls = [
+ call
+ for call in mock_session.notify.call_args_list
+ if isinstance(call[0][0], NotebookDocumentTransactionNotification)
+ ]
+ assert len(calls) == 1
+ return calls[0][0][0].transaction
+
+
+def _changes_of_type(tx: Transaction, cls: type) -> list:
+ return [c for c in tx.changes if isinstance(c, cls)]
+
+
+def _get_sync_command(mock_session: MagicMock) -> SyncGraphCommand:
+ assert mock_session.put_control_request.call_count == 1
+ cmd = mock_session.put_control_request.call_args[0][0]
+ assert isinstance(cmd, SyncGraphCommand)
+ return cmd
+
+
+def _run_reload(
+ tmp_path: Path,
+ mock_session: MagicMock,
+ config_manager,
+ content: str = SINGLE_CELL_NOTEBOOK,
+ document: NotebookDocument | None = None,
+) -> tuple[AppFileManager, list[CellId_t]]:
+ """Wire up a mock session and run EditModeReloadStrategy.handle_reload.
+
+ Returns (app_file_manager, cell_ids) for further assertions.
+ """
+ afm = _make_app(tmp_path, content)
+ mock_session.app_file_manager = afm
+ mock_session.document = (
+ document if document is not None else NotebookDocument()
+ )
+ strategy = EditModeReloadStrategy(config_manager)
+ cell_ids = list(afm.app.cell_manager.cell_ids())
+ strategy.handle_reload(mock_session, changed_cell_ids=set(cell_ids))
+ return afm, cell_ids
+
+
+DEFAULT_CELL_ID = CellId_t("cell1")
+
+
+def _make_document_with_extra_cell(
+ cell_ids: list[CellId_t],
+ deleted_id: CellId_t = DEFAULT_CELL_ID,
+) -> NotebookDocument:
+ """Build a document containing cell_ids[0] plus an extra cell to be deleted."""
+ return NotebookDocument(
+ [
+ NotebookCell(
+ id=cell_ids[0],
+ code="x = 1",
+ name="cell1",
+ config=CellConfig(),
+ ),
+ NotebookCell(
+ id=deleted_id,
+ code="y = 2",
+ name="cell2",
+ config=CellConfig(),
+ ),
+ ]
+ )
+
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+
@pytest.fixture
def mock_session():
- """Create a mock session for testing."""
session = MagicMock()
session.notify = MagicMock()
session.put_control_request = MagicMock()
@@ -50,7 +156,6 @@ def mock_session():
@pytest.fixture
def config_manager_lazy():
- """Create a config manager with lazy watcher mode."""
return get_default_config_manager(current_path=None).with_overrides(
{"runtime": {"watcher_on_save": "lazy"}}
)
@@ -58,482 +163,221 @@ def config_manager_lazy():
@pytest.fixture
def config_manager_autorun():
- """Create a config manager with autorun watcher mode."""
return get_default_config_manager(current_path=None).with_overrides(
{"runtime": {"watcher_on_save": "autorun"}}
)
+# ---------------------------------------------------------------------------
+# EditModeReloadStrategy — lazy vs autorun
+# ---------------------------------------------------------------------------
+
+
def test_edit_mode_reload_strategy_lazy(
tmp_path: Path, mock_session: MagicMock, config_manager_lazy
) -> None:
- """Test edit mode reload strategy with lazy mode."""
- content = dedent(
- """\
- import marimo
- app = marimo.App()
-
- @app.cell
- def cell1():
- 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)
- # Get actual cell IDs from the app
- cell_ids = list(app_file_manager.app.cell_manager.cell_ids())
- changed_cell_ids = set(cell_ids)
+ _run_reload(tmp_path, mock_session, config_manager_lazy)
- strategy.handle_reload(mock_session, changed_cell_ids=changed_cell_ids)
-
- # 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
- if isinstance(call[0][0], UpdateCellIdsNotification)
- ]
- assert len(update_ids_calls) == 1
-
- # Should send UpdateCellCodes with code_is_stale=True
- 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 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
+ tx = _get_transaction(mock_session)
+ assert len(_changes_of_type(tx, CreateCell)) == 1
+ assert len(_changes_of_type(tx, ReorderCells)) == 1
mock_session.put_control_request.assert_not_called()
def test_edit_mode_reload_strategy_autorun(
tmp_path: Path, mock_session: MagicMock, config_manager_autorun
) -> None:
- """Test edit mode reload strategy with autorun mode."""
- content = dedent(
- """\
- import marimo
- app = marimo.App()
+ _, cell_ids = _run_reload(tmp_path, mock_session, config_manager_autorun)
- @app.cell
- def cell1():
- 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)
- # Get actual cell IDs from the app
- cell_ids = list(app_file_manager.app.cell_manager.cell_ids())
- changed_cell_ids = set(cell_ids)
+ tx = _get_transaction(mock_session)
+ assert len(_changes_of_type(tx, CreateCell)) == 1
- strategy.handle_reload(mock_session, changed_cell_ids=changed_cell_ids)
+ sync_cmd = _get_sync_command(mock_session)
+ assert len(sync_cmd.run_ids) == len(cell_ids)
- # 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
- if isinstance(call[0][0], UpdateCellIdsNotification)
- ]
- assert len(update_ids_calls) == 1
- # 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
- 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_strategy_with_deleted_cells(
+def test_edit_mode_reload_no_deletions_lazy_no_control_request(
tmp_path: Path, mock_session: MagicMock, config_manager_lazy
) -> None:
- """Test edit mode reload strategy with deleted cells."""
- content = dedent(
- """\
- import marimo
- app = marimo.App()
-
- @app.cell
- def cell1():
- 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)
- # Get actual cell IDs from the app
- cell_ids = list(app_file_manager.app.cell_manager.cell_ids())
- # Indicate that cell2 was deleted (it's in changed but not in current cells)
- changed_cell_ids = set(cell_ids) | {CellId_t("cell2")}
-
- strategy.handle_reload(mock_session, changed_cell_ids=changed_cell_ids)
-
- # Should send DeleteCellRequest for cell2
- delete_calls = [
- call
- for call in mock_session.put_control_request.call_args_list
- if isinstance(call[0][0], DeleteCellCommand)
- ]
- 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."""
- strategy = RunModeReloadStrategy()
- changed_cell_ids = {CellId_t("cell1")}
-
- strategy.handle_reload(mock_session, changed_cell_ids=changed_cell_ids)
-
- # Should send Reload operation
- mock_session.notify.assert_called_once()
- operation = mock_session.notify.call_args[0][0]
- assert isinstance(operation, ReloadNotification)
-
-
-async def test_file_change_coordinator_handles_change(
- tmp_path: Path, mock_session: MagicMock
-) -> None:
- """Test file change coordinator handles file changes."""
- content = dedent(
- """\
- import marimo
- app = marimo.App()
-
- @app.cell
- def cell1():
- x = 1
- return x
- """
- )
- test_file = tmp_path / "test.py"
- test_file.write_text(content)
-
- app_file_manager = AppFileManager(filename=str(test_file))
- mock_session.app_file_manager = app_file_manager
-
- strategy = MagicMock()
- coordinator = FileChangeCoordinator(strategy)
-
- # Modify the file
- test_file.write_text(
- dedent(
- """\
- import marimo
- app = marimo.App()
-
- @app.cell
- def cell1():
- x = 2 # Changed
- return x
- """
- )
+ afm = _make_app(tmp_path, SINGLE_CELL_NOTEBOOK)
+ _run_reload(
+ tmp_path,
+ mock_session,
+ config_manager_lazy,
+ document=_document_from(afm),
)
+ mock_session.put_control_request.assert_not_called()
- result = await coordinator.handle_change(test_file, mock_session)
- # Should handle the change
- assert result.handled
- assert result.error is None
- strategy.handle_reload.assert_called_once()
+# ---------------------------------------------------------------------------
+# EditModeReloadStrategy — deleted cells
+# ---------------------------------------------------------------------------
-async def test_file_change_coordinator_skips_own_writes(
- tmp_path: Path, mock_session: MagicMock
[email protected]("mode", ["lazy", "autorun"])
+def test_edit_mode_reload_with_deleted_cells(
+ tmp_path: Path,
+ mock_session: MagicMock,
+ config_manager_lazy,
+ config_manager_autorun,
+ mode: str,
) -> None:
- """Test that file change coordinator skips reloading when it detects its own writes."""
- # Create a temporary file with initial content
- temp_file = tmp_path / "test_own_writes.py"
- temp_file.write_text(
- dedent(
- """\
- import marimo
- app = marimo.App()
-
- @app.cell
- def cell1():
- x = 1
- return x
-
- if __name__ == "__main__":
- app.run()
- """
- )
+ config = config_manager_lazy if mode == "lazy" else config_manager_autorun
+ deleted_id = CellId_t("cell2")
+
+ afm = _make_app(tmp_path, SINGLE_CELL_NOTEBOOK)
+ mock_session.app_file_manager = afm
+ cell_ids = list(afm.app.cell_manager.cell_ids())
+ mock_session.document = _make_document_with_extra_cell(
+ cell_ids, deleted_id
)
- # Set up app file manager
- app_file_manager = AppFileManager(filename=str(temp_file))
- mock_session.app_file_manager = app_file_manager
-
- # Save the file to track the last saved content
- cell_ids = list(app_file_manager.app.cell_manager.cell_ids())
- codes = list(app_file_manager.app.cell_manager.codes())
- app_file_manager.save(
- SaveNotebookRequest(
- cell_ids=cell_ids,
- filename=str(temp_file),
- codes=codes,
- names=["cell1"],
- configs=[CellConfig()],
- persist=True,
- )
+ strategy = EditModeReloadStrategy(config)
+ strategy.handle_reload(
+ mock_session,
+ changed_cell_ids=set(cell_ids) | {deleted_id},
)
- # Create file change coordinator
- strategy = MagicMock()
- coordinator = FileChangeCoordinator(strategy)
+ # Transaction should include a DeleteCell
+ tx = _get_transaction(mock_session)
+ deletes = _changes_of_type(tx, DeleteCell)
+ assert len(deletes) == 1
+ assert deletes[0].cell_id == deleted_id
- # Call handle_change - should skip reload because content matches
- result = await coordinator.handle_change(temp_file, mock_session)
+ # Both modes must sync deletions to the kernel
+ sync_cmd = _get_sync_command(mock_session)
+ assert sync_cmd.delete_ids == [deleted_id]
- # Verify reload was NOT called (early return triggered)
- assert not result.handled
- strategy.handle_reload.assert_not_called()
+ if mode == "lazy":
+ assert sync_cmd.run_ids == []
+ else:
+ assert set(sync_cmd.run_ids) == set(cell_ids)
- # Now externally modify the file
- temp_file.write_text(
- dedent(
- """\
- import marimo
- app = marimo.App()
-
- @app.cell
- def cell1():
- x = 2 # Changed by external editor
- return x
-
- if __name__ == "__main__":
- app.run()
- """
- )
- )
- # Call handle_change again - should now trigger reload
- result = await coordinator.handle_change(temp_file, mock_session)
+# ---------------------------------------------------------------------------
+# EditModeReloadStrategy — transaction change types
+# ---------------------------------------------------------------------------
- # Verify reload WAS called (content changed externally)
- assert result.handled
- strategy.handle_reload.assert_called_once()
-
-async def test_file_change_coordinator_handles_syntax_errors(
- tmp_path: Path, mock_session: MagicMock
+def test_edit_mode_reload_sends_config_changes(
+ tmp_path: Path, mock_session: MagicMock, config_manager_lazy
) -> None:
- """Test file change coordinator handles syntax errors gracefully."""
content = dedent(
"""\
import marimo
app = marimo.App()
- @app.cell
- def cell1():
+ @app.cell(hide_code=True)
+ def my_named_cell():
x = 1
return x
"""
)
- test_file = tmp_path / "test.py"
- test_file.write_text(content)
-
- app_file_manager = AppFileManager(filename=str(test_file))
- mock_session.app_file_manager = app_file_manager
-
- strategy = MagicMock()
- coordinator = FileChangeCoordinator(strategy)
-
- # Write invalid syntax
- test_file.write_text(
- dedent(
- """\
- import marimo
- app = marimo.App()
-
- @app.cell
- def cell1():
- x = 1
- # Invalid syntax below
- def broken(
- """
- )
+ afm = _make_app(tmp_path, content)
+ cell_ids = list(afm.app.cell_manager.cell_ids())
+ _run_reload(
+ tmp_path,
+ mock_session,
+ config_manager_lazy,
+ content=content,
+ document=NotebookDocument(
+ [
+ NotebookCell(
+ id=cell_ids[0],
+ code="x = 1",
+ name="my_named_cell",
+ config=CellConfig(hide_code=False),
+ ),
+ ]
+ ),
)
- result = await coordinator.handle_change(test_file, session=mock_session)
-
- # Should not handle due to error
- assert not result.handled
- assert result.error is not None
+ config_changes = _changes_of_type(
+ _get_transaction(mock_session), SetConfig
+ )
+ assert len(config_changes) == 1
+ assert config_changes[0].hide_code is True
-async def test_file_change_coordinator_path_mismatch(
- tmp_path: Path, mock_session: MagicMock
+def test_edit_mode_reload_sends_name_changes(
+ tmp_path: Path, mock_session: MagicMock, config_manager_lazy
) -> None:
- """Test file change coordinator with path mismatch."""
content = dedent(
"""\
import marimo
app = marimo.App()
@app.cell
- def cell1():
+ def new_name():
x = 1
return x
"""
)
- test_file = tmp_path / "test.py"
- test_file.write_text(content)
-
- other_file = tmp_path / "other.py"
- other_file.write_text(content)
-
- app_file_manager = AppFileManager(filename=str(test_file))
- mock_session.app_file_manager = app_file_manager
-
- strategy = MagicMock()
- coordinator = FileChangeCoordinator(strategy)
-
- # Try to handle change for different file
- result = await coordinator.handle_change(other_file, session=mock_session)
+ afm = _make_app(tmp_path, content)
+ cell_ids = list(afm.app.cell_manager.cell_ids())
+ _run_reload(
+ tmp_path,
+ mock_session,
+ config_manager_lazy,
+ content=content,
+ document=NotebookDocument(
+ [
+ NotebookCell(
+ id=cell_ids[0],
+ code="x = 1",
+ name="old_name",
+ config=CellConfig(),
+ ),
+ ]
+ ),
+ )
- # Should not handle due to path mismatch
- assert not result.handled
- assert "mismatch" in result.error.lower()
+ name_changes = _changes_of_type(_get_transaction(mock_session), SetName)
+ assert len(name_changes) == 1
+ assert name_changes[0].name == "new_name"
-def test_edit_mode_reload_sends_names_and_configs_lazy(
+def test_edit_mode_reload_sends_code_changes(
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
+ @app.cell
+ def cell1():
+ x = 2
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
- """
+ afm = _make_app(tmp_path, content)
+ cell_ids = list(afm.app.cell_manager.cell_ids())
+ _run_reload(
+ tmp_path,
+ mock_session,
+ config_manager_lazy,
+ content=content,
+ document=NotebookDocument(
+ [
+ NotebookCell(
+ id=cell_ids[0],
+ code="x = 1",
+ name="cell1",
+ config=CellConfig(),
+ ),
+ ]
+ ),
)
- 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
+ code_changes = _changes_of_type(_get_transaction(mock_session), SetCode)
+ assert len(code_changes) == 1
+ assert "x = 2" in code_changes[0].code
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
@@ -555,311 +399,259 @@ def test_edit_mode_reload_multiple_cells_mixed_configs(
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)
+ _run_reload(tmp_path, mock_session, config_manager_lazy, content=content)
- strategy.handle_reload(mock_session, changed_cell_ids=changed_cell_ids)
+ tx = _get_transaction(mock_session)
+ creates = _changes_of_type(tx, CreateCell)
+ assert len(creates) == 3
+ assert len(_changes_of_type(tx, ReorderCells)) == 1
- 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]
+ by_name = {c.name: c for c in creates}
+ assert by_name["setup"].config.hide_code is True
+ assert by_name["disabled_cell"].config.disabled is True
+ assert by_name["_"].config.hide_code is False
+ assert by_name["_"].config.disabled is False
- # 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
+# ---------------------------------------------------------------------------
+# AppFileManager.reload() — change detection
+# ---------------------------------------------------------------------------
- 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(
+def _assert_reload_detects_change(
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
- """
- )
+ initial: str,
+ modified: str,
+ expected_count: int = 1,
+) -> AppFileManager:
+ """Write initial content, overwrite with modified, reload, and assert."""
test_file = tmp_path / "test.py"
- test_file.write_text(initial_content)
- app_file_manager = AppFileManager(filename=str(test_file))
+ test_file.write_text(initial)
+ afm = AppFileManager(filename=str(test_file))
+ test_file.write_text(modified)
+ changed = afm.reload()
+ assert len(changed) == expected_count
+ return afm
+
+
+_BASE_CELL = dedent(
+ """\
+ import marimo
+ app = marimo.App()
+
+ @app.cell
+ def my_cell():
+ x = 1
+ return x
+ """
+)
- # 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()
+def test_reload_detects_config_only_changes(tmp_path: Path) -> None:
+ modified = _BASE_CELL.replace("@app.cell", "@app.cell(hide_code=True)")
+ afm = _assert_reload_detects_change(tmp_path, _BASE_CELL, modified)
+ assert list(afm.app.cell_manager.configs())[0].hide_code is True
- @app.cell(hide_code=True)
- def my_cell():
- x = 1
- return x
- """
- )
- test_file.write_text(modified_content)
- changed = app_file_manager.reload()
+def test_reload_detects_disabled_config_change(tmp_path: Path) -> None:
+ modified = _BASE_CELL.replace("@app.cell", "@app.cell(disabled=True)")
+ afm = _assert_reload_detects_change(tmp_path, _BASE_CELL, modified)
+ assert list(afm.app.cell_manager.configs())[0].disabled is True
- # 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_name_only_changes(tmp_path: Path) -> None:
+ initial = _BASE_CELL.replace("my_cell", "old_name")
+ modified = _BASE_CELL.replace("my_cell", "new_name")
+ afm = _assert_reload_detects_change(tmp_path, initial, modified)
+ assert list(afm.app.cell_manager.names())[0] == "new_name"
+
+
+def test_reload_no_changes_returns_empty(tmp_path: Path) -> None:
+ test_file = tmp_path / "test.py"
+ test_file.write_text(SINGLE_CELL_NOTEBOOK)
+ afm = AppFileManager(filename=str(test_file))
+ assert len(afm.reload()) == 0
-def test_reload_detects_disabled_config_change(
+def test_reload_detects_only_changed_cell_in_multi_cell(
tmp_path: Path,
) -> None:
- """Test that reload() detects disabled config change."""
- initial_content = dedent(
+ initial = dedent(
"""\
import marimo
app = marimo.App()
@app.cell
- def my_cell():
+ def cell_a():
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
+ @app.cell
+ def cell_b():
+ y = 2
+ return y
"""
)
- test_file.write_text(modified_content)
+ modified = initial.replace(
+ "@app.cell\ndef cell_b", "@app.cell(hide_code=True)\ndef cell_b"
+ )
+ afm = _assert_reload_detects_change(tmp_path, initial, modified)
- changed = app_file_manager.reload()
- assert len(changed) == 1
+ names = list(afm.app.cell_manager.names())
+ configs = list(afm.app.cell_manager.configs())
+ cell_ids = list(afm.app.cell_manager.cell_ids())
- configs_after = list(app_file_manager.app.cell_manager.configs())
- assert configs_after[0].disabled is True
+ assert names == ["cell_a", "cell_b"]
+ assert configs[0].hide_code is False
+ assert configs[1].hide_code is True
+ assert afm.reload() == set() # no further changes
+ # The earlier reload should have flagged cell_b's ID
+ # (already asserted by _assert_reload_detects_change returning 1)
-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()
+# ---------------------------------------------------------------------------
+# RunModeReloadStrategy
+# ---------------------------------------------------------------------------
- @app.cell
- def old_name():
- x = 1
- return x
- """
+
+def test_run_mode_reload_strategy(mock_session: MagicMock) -> None:
+ RunModeReloadStrategy().handle_reload(
+ mock_session, changed_cell_ids={CellId_t("cell1")}
)
- test_file = tmp_path / "test.py"
- test_file.write_text(initial_content)
- app_file_manager = AppFileManager(filename=str(test_file))
+ mock_session.notify.assert_called_once()
+ assert isinstance(mock_session.notify.call_args[0][0], ReloadNotification)
- 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()
+# ---------------------------------------------------------------------------
+# FileChangeCoordinator
+# ---------------------------------------------------------------------------
- @app.cell
- def new_name():
- x = 1
- return x
- """
- )
- test_file.write_text(modified_content)
- changed = app_file_manager.reload()
+async def test_file_change_coordinator_handles_change(
+ tmp_path: Path, mock_session: MagicMock
+) -> None:
+ test_file = tmp_path / "test.py"
+ test_file.write_text(SINGLE_CELL_NOTEBOOK)
+ mock_session.app_file_manager = AppFileManager(filename=str(test_file))
+
+ strategy = MagicMock()
+ coordinator = FileChangeCoordinator(strategy)
- # Should detect the name change
- assert len(changed) == 1
+ test_file.write_text(
+ SINGLE_CELL_NOTEBOOK.replace("x = 1", "x = 2 # Changed")
+ )
+ result = await coordinator.handle_change(test_file, mock_session)
- names_after = list(app_file_manager.app.cell_manager.names())
- assert names_after[0] == "new_name"
+ assert result.handled
+ assert result.error is None
+ strategy.handle_reload.assert_called_once()
-def test_reload_no_changes_returns_empty(
- tmp_path: Path,
+async def test_file_change_coordinator_skips_own_writes(
+ tmp_path: Path, mock_session: MagicMock
) -> None:
- """Test that reload() returns empty set when nothing changed."""
- content = dedent(
+ content_with_main = dedent(
"""\
import marimo
app = marimo.App()
@app.cell
- def my_cell():
+ def cell1():
x = 1
return x
+
+ if __name__ == "__main__":
+ app.run()
"""
)
- 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()
+ temp_file = tmp_path / "test_own_writes.py"
+ temp_file.write_text(content_with_main)
- assert len(changed) == 0
+ afm = AppFileManager(filename=str(temp_file))
+ mock_session.app_file_manager = afm
+ cell_ids = list(afm.app.cell_manager.cell_ids())
+ codes = list(afm.app.cell_manager.codes())
+ afm.save(
+ SaveNotebookRequest(
+ cell_ids=cell_ids,
+ filename=str(temp_file),
+ codes=codes,
+ names=["cell1"],
+ configs=[CellConfig()],
+ persist=True,
+ )
+ )
-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()
+ strategy = MagicMock()
+ coordinator = FileChangeCoordinator(strategy)
- @app.cell
- def cell_a():
- x = 1
- return x
+ # Content matches last save — should skip
+ result = await coordinator.handle_change(temp_file, mock_session)
+ assert not result.handled
+ strategy.handle_reload.assert_not_called()
- @app.cell
- def cell_b():
- y = 2
- return y
- """
+ # External edit — should reload
+ temp_file.write_text(
+ content_with_main.replace("x = 1", "x = 2 # Changed by editor")
)
- test_file = tmp_path / "test.py"
- test_file.write_text(initial_content)
- app_file_manager = AppFileManager(filename=str(test_file))
+ result = await coordinator.handle_change(temp_file, mock_session)
+ assert result.handled
+ strategy.handle_reload.assert_called_once()
- 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()
+async def test_file_change_coordinator_handles_syntax_errors(
+ tmp_path: Path, mock_session: MagicMock
+) -> None:
+ test_file = tmp_path / "test.py"
+ test_file.write_text(SINGLE_CELL_NOTEBOOK)
+ mock_session.app_file_manager = AppFileManager(filename=str(test_file))
- @app.cell
- def cell_a():
- x = 1
- return x
+ strategy = MagicMock()
+ coordinator = FileChangeCoordinator(strategy)
- @app.cell(hide_code=True)
- def cell_b():
- y = 2
- return y
- """
- )
- test_file.write_text(modified_content)
+ test_file.write_text(SINGLE_CELL_NOTEBOOK.replace("x = 1", "def broken("))
+ result = await coordinator.handle_change(test_file, session=mock_session)
+
+ assert not result.handled
+ assert result.error is not None
- changed = app_file_manager.reload()
- # Only the second cell should be flagged as changed
- assert len(changed) == 1
+async def test_file_change_coordinator_path_mismatch(
+ tmp_path: Path, mock_session: MagicMock
+) -> None:
+ test_file = tmp_path / "test.py"
+ test_file.write_text(SINGLE_CELL_NOTEBOOK)
+ other_file = tmp_path / "other.py"
+ other_file.write_text(SINGLE_CELL_NOTEBOOK)
- 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())
+ mock_session.app_file_manager = AppFileManager(filename=str(test_file))
- # First cell unchanged
- assert names_after[0] == "cell_a"
- assert configs_after[0].hide_code is False
+ strategy = MagicMock()
+ coordinator = FileChangeCoordinator(strategy)
- # Second cell has new config
- assert names_after[1] == "cell_b"
- assert configs_after[1].hide_code is True
+ result = await coordinator.handle_change(other_file, session=mock_session)
- # The changed cell ID should be cell_b's ID
- assert changed == {cell_ids_after[1]}
+ assert not result.handled
+ assert "mismatch" in result.error.lower()
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
+ test_file.write_text(SINGLE_CELL_NOTEBOOK)
+ mock_session.app_file_manager = AppFileManager(filename=str(test_file))
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
- """
- )
+ SINGLE_CELL_NOTEBOOK.replace("@app.cell", "@app.cell(hide_code=True)")
)
-
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()