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.

Edit notebook documents through the host (#11264)

Trevor Manz37eb798a11e5
diff --git a/frontend/src/core/cells/__tests__/document-roundtrip.test.ts b/frontend/src/core/cells/__tests__/document-roundtrip.test.ts
index 41eeb40133..77ab724476 100644
--- a/frontend/src/core/cells/__tests__/document-roundtrip.test.ts
+++ b/frontend/src/core/cells/__tests__/document-roundtrip.test.ts
@@ -178,6 +178,22 @@ function documentSnapshot(state: NotebookState) {
}
describe("document round-trip", () => {
+ it("applies a server transaction that deletes every cell", () => {
+ setup("a", "b");
+ applyTransactionChanges(
+ [
+ ...replica.cellIds.inOrderIds.map((cellId) => ({
+ type: "delete-cell" as const,
+ cellId,
+ })),
+ { type: "reorder-cells", cellIds: [] },
+ ],
+ replicaActions,
+ () => replica.cellIds.inOrderIds,
+ );
+ expect(documentSnapshot(replica)).toEqual([]);
+ });
+
it("initial setup converges", () => {
setup("a", "b", "c");
expect(documentSnapshot(primary)).toEqual(documentSnapshot(replica));
diff --git a/marimo/_core/notebook.py b/marimo/_core/notebook.py
index f7fab4b3eb..372c0ba2e1 100644
--- a/marimo/_core/notebook.py
+++ b/marimo/_core/notebook.py
@@ -11,6 +11,7 @@ import msgspec
from msgspec.structs import replace
from marimo._core import backend as be, protocol
+from marimo._core.document import Changed
from marimo._core.errors import Conflict, NoRuntime, NotFound
from marimo._core.executions import Executions, Released, Removed
from marimo._core.ids import mint
@@ -20,12 +21,7 @@ if TYPE_CHECKING:
from collections.abc import Callable, Mapping, Sequence
from marimo._core.analysis import Analyzer
- from marimo._core.document import (
- CellSource,
- Changed,
- Document,
- DocumentSnapshot,
- )
+ from marimo._core.document import CellSource, Document, DocumentSnapshot
from marimo._core.executions import Change
from marimo._core.stream import Body, Sink
@@ -108,11 +104,18 @@ class Notebook:
cells: Sequence[CellSource],
app_config: Mapping[str, object],
*,
+ saved: bool = False,
request_id: str | None = None,
) -> Changed:
- """Replace the document and publish its changes."""
+ """Replace the document and publish its changes.
+
+ With `saved`, the new contents are also the persisted revision.
+ """
self._require_open()
- changed = self.document.replace(cells, app_config)
+ document = self.document
+ changed = document.replace(cells, app_config)
+ if saved and (published := document.mark_saved()) is not None:
+ changed = Changed(changed.cells, changed.removed, published)
self._publish_changed(changed, request_id)
return changed
diff --git a/marimo/_internal/commands.py b/marimo/_internal/commands.py
index 642bec9f70..09dcd5d36f 100644
--- a/marimo/_internal/commands.py
+++ b/marimo/_internal/commands.py
@@ -11,6 +11,7 @@ from marimo._runtime.commands import (
DebugCellCommand,
DeleteCellCommand,
DiscoverDataSourcesCommand,
+ EditCellsCommand,
ExecuteCellCommand,
ExecuteCellsCommand,
ExecuteScratchpadCommand,
@@ -52,6 +53,7 @@ __all__ = [
"DebugCellCommand",
"DeleteCellCommand",
"DiscoverDataSourcesCommand",
+ "EditCellsCommand",
"ExecuteCellCommand",
"ExecuteCellsCommand",
"ExecuteScratchpadCommand",
diff --git a/marimo/_messaging/notebook/changes.py b/marimo/_messaging/notebook/changes.py
index c602756393..85570225f2 100644
--- a/marimo/_messaging/notebook/changes.py
+++ b/marimo/_messaging/notebook/changes.py
@@ -100,7 +100,7 @@ DocumentChange = (
# ------------------------------------------------------------------
TransactionSource = Literal[
- "frontend", "kernel", "code-mode", "file-watch", "cell-manager"
+ "frontend", "kernel", "code-mode", "file-watch", "cell-manager", "host"
]
diff --git a/marimo/_runtime/commands.py b/marimo/_runtime/commands.py
index 67e87b55a8..a9ab67de00 100644
--- a/marimo/_runtime/commands.py
+++ b/marimo/_runtime/commands.py
@@ -370,6 +370,30 @@ class SyncGraphCommand(Command):
]
+class EditCellsCommand(Command):
+ """Apply one edit of the notebook's cells to the kernel.
+
+ TODO(MO-8002): Replace this temporary command with synchronization of
+ a versioned notebook document replica in the kernel. Replica updates
+ must be applied before any execution trigger.
+
+ Sent when the notebook changes without a run, as a host edit does.
+ Changed code is registered without running, so no later run uses
+ code the notebook no longer has. Deletions and configs take effect
+ together, before any cell runs because of them, so a cell the edit
+ deletes or disables does not run when a cell it depended on goes.
+
+ Attributes:
+ codes: New code for each cell the edit created or changed.
+ configs: New config for each cell the edit created or reconfigured.
+ delete_ids: Cells the edit removed.
+ """
+
+ codes: dict[CellId_t, str]
+ configs: dict[CellId_t, dict[str, Any]]
+ delete_ids: list[CellId_t]
+
+
class ExecuteScratchpadCommand(Command):
"""Execute code in the scratchpad.
@@ -958,6 +982,7 @@ CommandMessage = (
| SetBreakpointsCommand
| DeleteCellCommand
| SyncGraphCommand
+ | EditCellsCommand
| UpdateCellConfigCommand
# Package management
| InstallPackagesCommand
diff --git a/marimo/_runtime/kernel_request_handlers.py b/marimo/_runtime/kernel_request_handlers.py
index db78ae96cd..9d02005e71 100644
--- a/marimo/_runtime/kernel_request_handlers.py
+++ b/marimo/_runtime/kernel_request_handlers.py
@@ -27,6 +27,7 @@ from marimo._runtime.commands import (
CreateNotebookCommand,
DebugCellCommand,
DeleteCellCommand,
+ EditCellsCommand,
ExecuteCellsCommand,
ExecuteScratchpadCommand,
ExecuteStaleCellsCommand,
@@ -82,6 +83,7 @@ class KernelRequestHandlers:
router.register(DeleteCellCommand, self._handle_delete_cell)
router.register(ExecuteCellsCommand, self._handle_execute_multiple)
router.register(SyncGraphCommand, self._handle_sync_graph)
+ router.register(EditCellsCommand, self._handle_edit_cells)
router.register(
ExecuteScratchpadCommand, self._handle_execute_scratchpad
)
@@ -162,6 +164,10 @@ class KernelRequestHandlers:
with self._run_context():
await self._kernel.set_cell_config(request)
+ async def _handle_edit_cells(self, request: EditCellsCommand) -> None:
+ with self._run_context():
+ await self._kernel.edit_cells(request)
+
async def _handle_instantiate(
self, request: CreateNotebookCommand
) -> None:
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 0195f3900d..86f237b7b9 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -107,6 +107,7 @@ from marimo._runtime.commands import (
CommandMessage,
CreateNotebookCommand,
DeleteCellCommand,
+ EditCellsCommand,
ExecuteCellCommand,
ExecuteStaleCellsCommand,
InvokeFunctionCommand,
@@ -1694,6 +1695,42 @@ class Kernel:
self.mutate_graph(execution_requests, deletion_requests)
await self.run(execution_requests)
+ @kernel_tracer.start_as_current_span("edit_cells")
+ async def edit_cells(self, request: EditCellsCommand) -> None:
+ """Apply a notebook edit to the graph, then run what follows from it.
+
+ Changed code is registered as stale, not run. The kernel only
+ takes code for cells it has: a cell it has never seen arrives
+ with the run that first carries it, and code pending from an
+ instantiation without a run is replaced in place. Deletions and
+ configs then apply together, and only their consequences run:
+ cells that depended on a deleted cell, and under autorun, stale
+ cells the edit enabled.
+ """
+ edits: list[ExecuteCellCommand] = []
+ for cell_id, code in request.codes.items():
+ command = ExecuteCellCommand(cell_id=cell_id, code=code)
+ if cell_id in self.graph.cells:
+ edits.append(command)
+ elif cell_id in self._uninstantiated_execution_requests:
+ self._uninstantiated_execution_requests[cell_id] = command
+ if edits:
+ self.mutate_graph(
+ edits,
+ deletion_requests=[],
+ cells_starting_stale={edit.cell_id for edit in edits},
+ )
+ deletions = [
+ DeleteCellCommand(cell_id=cell_id)
+ for cell_id in request.delete_ids
+ ]
+ cells_to_run = self.mutate_graph([], deletions) if deletions else set()
+ stale_cells = self._configure_cells(request.configs)
+ if self.reactive_execution_mode == "autorun":
+ cells_to_run |= stale_cells
+ if cells_to_run:
+ await self._run_cells(cells_to_run)
+
def prepare_execution_requests(
self,
execution_requests: Sequence[ExecuteCellCommand],
@@ -1944,9 +1981,16 @@ class Kernel:
Cells that are enabled (via config) but stale are run as a side-effect.
"""
- # Stale cells that are enabled will need to be run.
+ stale_cells = self._configure_cells(request.configs)
+ if stale_cells and self.reactive_execution_mode == "autorun":
+ await self._run_cells(stale_cells)
+
+ def _configure_cells(
+ self, configs: dict[CellId_t, dict[str, Any]]
+ ) -> set[CellId_t]:
+ """Apply cell configs and return the stale cells they enabled."""
stale_cells: set[CellId_t] = set()
- for cell_id, config in request.configs.items():
+ for cell_id, config in configs.items():
previous = self.cell_metadata.get(cell_id, CellMetadata()).config
merged = CellConfig.from_dict(previous.asdict())
merged.configure(config)
@@ -1955,13 +1999,11 @@ class Kernel:
if cell is None:
continue
cell.configure(config)
- if not cell.config.disabled:
- stale_cells |= self.graph.enable_cell(cell_id)
- elif cell.config.disabled:
+ if cell.config.disabled:
self.graph.disable_cell(cell_id)
-
- if stale_cells and self.reactive_execution_mode == "autorun":
- await self._run_cells(stale_cells)
+ else:
+ stale_cells |= self.graph.enable_cell(cell_id)
+ return stale_cells
@kernel_tracer.start_as_current_span("set_user_config")
def set_user_config(self, request: UpdateUserConfigCommand) -> None:
diff --git a/marimo/_server/host/__init__.py b/marimo/_server/host/__init__.py
index 28e1258f52..4ef4e55e46 100644
--- a/marimo/_server/host/__init__.py
+++ b/marimo/_server/host/__init__.py
@@ -9,6 +9,7 @@ OPERATIONS = [
"notebook.update",
"notebook.delete",
"notebook.open",
+ "notebook.edit",
"runtime.start",
"runtime.stop",
"runtime.restart",
diff --git a/marimo/_server/host/api.py b/marimo/_server/host/api.py
index 62c1392031..083d8f587b 100644
--- a/marimo/_server/host/api.py
+++ b/marimo/_server/host/api.py
@@ -19,7 +19,13 @@ from starlette.routing import Route, Router
from marimo import _loggers
from marimo._core import protocol
-from marimo._core.errors import Conflict, NoRuntime, NotFound
+from marimo._core.errors import (
+ Conflict,
+ EditConflict,
+ Invalid,
+ NoRuntime,
+ NotFound,
+)
from marimo._server.api.auth import TOKEN_QUERY_PARAM
from marimo._server.api.deps import AppStateBase
from marimo._server.api.utils import format_url_host, open_url_in_browser
@@ -83,13 +89,17 @@ _HTTP_KINDS = {
def problem(
- status: int, kind: str | None = None, detail: str | None = None
+ status: int,
+ kind: str | None = None,
+ detail: str | None = None,
+ *,
+ edit: protocol.EditConflict | None = None,
) -> Response:
"""Return a protocol error as an HTTP problem response.
Without a kind, the status picks one. A status this protocol does
not name is a server bug, so it becomes a 500 rather than a problem
- of an unknown kind.
+ of an unknown kind. A conflict over an edit carries `edit`.
"""
kind = _HTTP_KINDS.get(status) if kind is None else kind
@@ -101,6 +111,7 @@ def problem(
title=_TITLES[kind],
status=status,
detail=msgspec.UNSET if detail is None else detail,
+ edit=msgspec.UNSET if edit is None else edit,
)
return Response(
msgspec.json.encode(body),
@@ -117,6 +128,7 @@ def build_app() -> Router:
Route("/notebooks/{id}", _update_notebook, methods=["PATCH"]),
Route("/notebooks/{id}", _delete_notebook, methods=["DELETE"]),
Route("/notebooks/{id}/events", _notebook_events, methods=["GET"]),
+ Route("/notebooks/{id}/edits", _edit_notebook, methods=["POST"]),
Route("/notebooks/{id}/open", _open_notebook, methods=["POST"]),
Route("/notebooks/{id}/runtime", _start_runtime, methods=["PUT"]),
Route("/notebooks/{id}/runtime", _stop_runtime, methods=["DELETE"]),
@@ -340,8 +352,19 @@ async def _execute_mutation(endpoint: _Endpoint, request: Request) -> Response:
return await endpoint(request)
except NoRuntime as e:
return problem(409, "no-runtime", str(e))
+ except EditConflict as e:
+ return problem(
+ 409,
+ "conflict",
+ str(e),
+ edit=protocol.EditConflict(
+ change=e.change, cell=e.cell, document=e.document
+ ),
+ )
except Conflict as e:
return problem(409, "conflict", str(e))
+ except Invalid as e:
+ return problem(400, "invalid-request", str(e))
except NotFound as e:
return problem(404, "not-found", str(e))
except msgspec.DecodeError as e:
@@ -582,6 +605,19 @@ async def _delete_notebook(request: Request) -> Response:
return _reply(204, None)
+@_mutation("notebook.edit")
+async def _edit_notebook(request: Request) -> Response:
+ """Apply an edit as one unit; 409 with `edit` when a precondition is stale."""
+ context = _context(request)
+ key = request.headers["Idempotency-Key"]
+ notebook = await _notebook(request)
+ body = await _decode(request, protocol.EditRequest)
+ response = await context.bridge.edit(
+ notebook.id, body.changes, request_id=key
+ )
+ return _reply(200, response)
+
+
@_mutation("notebook.open")
async def _open_notebook(request: Request) -> Response:
"""Open the notebook in the configured browser."""
diff --git a/marimo/_server/host/backend.py b/marimo/_server/host/backend.py
index a432a244cc..b167250954 100644
--- a/marimo/_server/host/backend.py
+++ b/marimo/_server/host/backend.py
@@ -15,6 +15,7 @@ from marimo._messaging.notification import (
CompletedRunNotification,
ExecutionNotification,
InterruptedNotification,
+ NotebookDocumentTransactionNotification,
StartupProgressNotification,
)
from marimo._messaging.serde import deserialize_kernel_message
@@ -76,12 +77,18 @@ class SessionBackend(SessionConsumer):
file: Callable[[], str | None],
manager: SessionManager,
observe: Observe,
+ document_changed: Callable[[], None] | None = None,
+ session_attached: Callable[[], None] | None = None,
) -> None:
self._notebook_id = notebook_id
self._file = file
"""Resolve the notebook's current path after file moves."""
self._manager = manager
self._observe = observe
+ self._document_changed = document_changed
+ """Called after the session's document changes, from any writer."""
+ self._session_attached = session_attached
+ """Called with the session attached, before the runtime is reported."""
self._kernel: _Kernel | None = None
self._run: _Run | None = None
self._translators: dict[str, RunTranslator] = {}
@@ -258,6 +265,8 @@ class SessionBackend(SessionConsumer):
if kernel is None:
return
kernel.session = session
+ if self._session_attached is not None:
+ self._session_attached()
self._observe(be.Running(kernel.runtime_id, __version__))
def on_detach(self) -> None:
@@ -278,6 +287,10 @@ class SessionBackend(SessionConsumer):
def notify(self, notification: KernelMessage) -> None:
message = deserialize_kernel_message(notification)
+ if isinstance(message, NotebookDocumentTransactionNotification):
+ if self._document_changed is not None and self.session is not None:
+ self._document_changed()
+ return
if isinstance(message, StartupProgressNotification):
if (kernel := self._kernel) is not None:
phase = _PHASES.get(message.phase, message.phase)
diff --git a/marimo/_server/host/bridge.py b/marimo/_server/host/bridge.py
index 587dbe4b26..57fe3c67d1 100644
--- a/marimo/_server/host/bridge.py
+++ b/marimo/_server/host/bridge.py
@@ -15,7 +15,7 @@ from marimo._core.executions import Executions
from marimo._core.host import Host
from marimo._core.notebook import Notebook
from marimo._runtime.commands import RenameNotebookCommand
-from marimo._server.host import OPERATIONS
+from marimo._server.host import OPERATIONS, document as documents
from marimo._server.host.analysis import HostAnalyzer
from marimo._server.host.backend import SessionBackend
from marimo._server.host.index import WorkspaceIndex
@@ -23,21 +23,22 @@ from marimo._session.events import SessionEventListener
from marimo._session.notebook.storage import rename_no_replace
if TYPE_CHECKING:
+ from collections.abc import Sequence
from pathlib import Path
- from marimo._ast.cell import CellConfig
from marimo._config.manager import MarimoConfigManager
from marimo._core.backend import Message
from marimo._core.document import Policy
from marimo._core.stream import Event, Sink
from marimo._server.session_manager import SessionManager
- from marimo._session.notebook import AppFileManager
from marimo._session.session import Session
LOGGER = _loggers.marimo_logger()
-# TODO: Remove once sessions consume host-owned notebooks.
+# NB: The host keeps a separate document to avoid migrating the frontend yet.
+# Editor changes are mirrored into it; host edits become session transactions.
+# Remove this adapter when MO-8002 unifies document ownership after host saving.
class SessionBridge(SessionEventListener):
"""Connect a host's notebook catalog to a session manager."""
@@ -95,7 +96,7 @@ class SessionBridge(SessionEventListener):
session = candidate
break
if session is not None:
- cells, app_config = _from_session(session)
+ cells, app_config = documents.from_session(session)
else:
if loaded is None:
raise Conflict("The notebook document could not be loaded")
@@ -137,7 +138,71 @@ class SessionBridge(SessionEventListener):
if self._config_manager is None
else AppDefaults.from_config_manager(self._config_manager)
)
- return _from_file_manager(AppFileManager(path, defaults=defaults))
+ return documents.from_file_manager(
+ AppFileManager(path, defaults=defaults)
+ )
+
+ async def edit(
+ self,
+ notebook_id: str,
+ changes: Sequence[protocol.Change],
+ *,
+ request_id: str,
+ ) -> protocol.EditResponse:
+ """Apply an edit to the document, and to the session when there is one.
+
+ The file is not written. The session mirrors the edit back with
+ its own app config, so the response carries the document as it
+ stands after that, which is the one the client reads next.
+
+ Raises:
+ EditConflict: If a precondition is stale.
+ Invalid: If a change could not apply to any state.
+ """
+ notebook = await self.host.notebook(notebook_id)
+ response = notebook.edit(changes, request_id=request_id)
+ session = self._session_of(notebook.id)
+ if session is None:
+ return response
+ documents.apply_to_session(session, notebook.document)
+ return protocol.EditResponse(
+ cells=response.cells, document=notebook.document._record
+ )
+
+ def _session_of(self, notebook_id: protocol.NotebookId) -> Session | None:
+ backend = self._backends.get(notebook_id)
+ return None if backend is None else backend.session
+
+ def _attach_document(self, notebook_id: protocol.NotebookId) -> None:
+ """Reconcile the document with a session that just attached.
+
+ Host edits made before the session existed are carried into the
+ editor, even when the file changed meanwhile. Without any, the
+ session has the file as it is now, so its contents replace the
+ host's earlier read and are the saved revision.
+ """
+ session = self._session_of(notebook_id)
+ notebook = self.host.peek_notebook(notebook_id)
+ if session is None or notebook is None:
+ return
+ document = notebook.document
+ if document._record.saved_etag != document._record.etag:
+ documents.apply_to_session(session, document)
+ return
+ cells, app_config = documents.from_session(session)
+ notebook.replace(cells, app_config, saved=True)
+
+ def _mirror(self, notebook_id: protocol.NotebookId) -> None:
+ """Bring the document up to date with the session's after it changed."""
+ session = self._session_of(notebook_id)
+ try:
+ notebook = self.host.peek_notebook(notebook_id)
+ except NotFound:
+ return
+ if session is None or notebook is None:
+ return
+ cells, app_config = documents.from_session(session)
+ notebook.replace(cells, app_config)
def _policy(self, file: Path | None, session: Session | None) -> Policy:
config_manager = (
@@ -293,6 +358,8 @@ class SessionBridge(SessionEventListener):
file,
self._manager,
observe,
+ document_changed=lambda: self._mirror(notebook_id),
+ session_attached=lambda: self._attach_document(notebook_id),
)
self._backends[notebook_id] = backend
return backend
@@ -341,30 +408,3 @@ class SessionBridge(SessionEventListener):
await self._adopt(session)
return
self.index.moved(notebook.id, path)
-
-
-def _from_session(session: Session) -> tuple[list[CellSource], dict[str, Any]]:
- cells = [
- CellSource(cell.id, cell.code, cell.name, _config(cell.config))
- for cell in session.document.cells
- ]
- return cells, session.app_file_manager.app.config.asdict_difference()
-
-
-def _from_file_manager(
- manager: AppFileManager,
-) -> tuple[list[CellSource], dict[str, Any]]:
- cells = [
- CellSource(data.cell_id, data.code, data.name, _config(data.config))
- for data in manager.app.cell_manager.cell_data()
- ]
- return cells, manager.app.config.asdict_difference()
-
-
-def _config(config: CellConfig) -> protocol.CellConfig:
- return protocol.CellConfig(
- column=config.column,
- disabled=config.disabled,
- hide_code=config.hide_code,
- expand_output=config.expand_output,
- )
diff --git a/marimo/_server/host/document.py b/marimo/_server/host/document.py
new file mode 100644
index 0000000000..68afdf74c5
--- /dev/null
+++ b/marimo/_server/host/document.py
@@ -0,0 +1,151 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""Translate between host records and the editor's document model.
+
+The host owns protocol edits and etags. Sessions still own the editor's
+transaction history, so the bridge mirrors each session transaction into
+the host document.
+
+While a session is attached it also owns the app config, and the host
+document only mirrors it. Host edits change cells and their order.
+
+TODO: An editor app config change produces no document transaction, so
+the host does not learn of it until the next cell transaction, and
+`app_config` and `app_config_etag` on the host stream lag until then.
+Nothing writes app config from the host side, so no data is at risk.
+Resolve once the frontend consumes the host protocol, when a config
+change becomes a change on the core document like any other.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any
+
+from marimo._ast.cell import CellConfig
+from marimo._core import protocol
+from marimo._core.document import CellSource
+from marimo._messaging.notebook import (
+ CreateCell,
+ DeleteCell,
+ DocumentChange,
+ ReorderCells,
+ SetCode,
+ SetConfig,
+ SetName,
+ Transaction,
+)
+from marimo._messaging.notification import (
+ NotebookDocumentTransactionNotification,
+)
+from marimo._runtime.commands import EditCellsCommand
+from marimo._types.ids import CellId_t
+
+if TYPE_CHECKING:
+ from marimo._core.document import Document
+ from marimo._session.notebook import AppFileManager
+ from marimo._session.session import Session
+
+
+def from_session(session: Session) -> tuple[list[CellSource], dict[str, Any]]:
+ cells = [
+ CellSource(cell.id, cell.code, cell.name, _config(cell.config))
+ for cell in session.document.cells
+ ]
+ return cells, session.app_file_manager.app.config.asdict_difference()
+
+
+def from_file_manager(
+ manager: AppFileManager,
+) -> tuple[list[CellSource], dict[str, Any]]:
+ cells = [
+ CellSource(data.cell_id, data.code, data.name, _config(data.config))
+ for data in manager.app.cell_manager.cell_data()
+ ]
+ return cells, manager.app.config.asdict_difference()
+
+
+def _config(config: CellConfig) -> protocol.CellConfig:
+ return protocol.CellConfig(
+ column=config.column,
+ disabled=config.disabled,
+ hide_code=config.hide_code,
+ expand_output=config.expand_output,
+ )
+
+
+def _cell_config(config: protocol.CellConfig) -> CellConfig:
+ return CellConfig(
+ column=config.column,
+ disabled=config.disabled,
+ hide_code=config.hide_code,
+ expand_output=config.expand_output,
+ )
+
+
+def apply_to_session(session: Session, document: Document) -> None:
+ """Apply the document's cells and order to the session as one transaction.
+
+ The session tells its consumers, so the frontend sees the edit and
+ the host backend mirrors it back as a no-op. The kernel is told of
+ the edit as one command, so nothing runs code the document no longer
+ has: changed code is registered without running, and a cell the edit
+ deletes or disables is gone before any run the deletion causes. The
+ app config is the session's own and is left alone.
+ """
+ current = session.document
+ changes: list[DocumentChange] = []
+ codes: dict[CellId_t, str] = {}
+ configs: dict[CellId_t, dict[str, Any]] = {}
+ previous: CellId_t | None = None
+ for cell in document:
+ cell_id = CellId_t(cell.id)
+ existing = current.get(cell_id)
+ config = _cell_config(cell.config)
+ if existing is None:
+ changes.append(
+ CreateCell(
+ cell_id=cell_id,
+ code=cell.code,
+ name=cell.name,
+ config=config,
+ after=previous,
+ )
+ )
+ codes[cell_id] = cell.code
+ if config != CellConfig():
+ configs[cell_id] = config.asdict()
+ else:
+ if existing.code != cell.code:
+ changes.append(SetCode(cell_id=cell_id, code=cell.code))
+ codes[cell_id] = cell.code
+ if existing.name != cell.name:
+ changes.append(SetName(cell_id=cell_id, name=cell.name))
+ if _config(existing.config) != cell.config:
+ changes.append(
+ SetConfig(
+ cell_id=cell_id,
+ column=cell.config.column,
+ disabled=cell.config.disabled,
+ hide_code=cell.config.hide_code,
+ expand_output=cell.config.expand_output,
+ )
+ )
+ configs[cell_id] = config.asdict()
+ previous = cell_id
+ wanted = {CellId_t(cell.id) for cell in document}
+ deleted = [c for c in current.cell_ids if c not in wanted]
+ changes.extend(DeleteCell(cell_id=cell_id) for cell_id in deleted)
+ order = [CellId_t(c) for c in document.order]
+ if current.cell_ids != order:
+ changes.append(ReorderCells(cell_ids=tuple(order)))
+ if not changes:
+ return
+ applied = current.apply(Transaction(changes=tuple(changes), source="host"))
+ session.notify(
+ NotebookDocumentTransactionNotification(transaction=applied),
+ from_consumer_id=None,
+ )
+ if codes or configs or deleted:
+ session.put_control_request(
+ EditCellsCommand(codes=codes, configs=configs, delete_ids=deleted),
+ from_consumer_id=None,
+ )
diff --git a/marimo/_session/capabilities.py b/marimo/_session/capabilities.py
index 3e0502db6a..586062d5cc 100644
--- a/marimo/_session/capabilities.py
+++ b/marimo/_session/capabilities.py
@@ -71,6 +71,7 @@ _EDIT_COMMANDS: frozenset[type] = frozenset(
commands.SetBreakpointsCommand,
commands.DeleteCellCommand,
commands.SyncGraphCommand,
+ commands.EditCellsCommand,
commands.UpdateCellConfigCommand,
commands.InstallPackagesCommand,
commands.UpdateUserConfigCommand,
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index d85c71402a..a529c94d89 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -6230,6 +6230,7 @@ components:
- code-mode
- file-watch
- frontend
+ - host
- kernel
version:
anyOf:
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index f86f93e852..a26c21c6e3 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -7612,6 +7612,7 @@ export interface components {
| "code-mode"
| "file-watch"
| "frontend"
+ | "host"
| "kernel";
/** @default null */
version?: number | null;
diff --git a/tests/_core/test_notebook_document.py b/tests/_core/test_notebook_document.py
index 700a020688..5df39de7e8 100644
--- a/tests/_core/test_notebook_document.py
+++ b/tests/_core/test_notebook_document.py
@@ -416,6 +416,26 @@ class TestNotebook:
assert all(e.data.request_id == "edit-1" for e in log) # type: ignore[union-attr]
assert log[1].data.id == "k7f2" # type: ignore[union-attr]
+ def test_replace_can_record_the_saved_revision(
+ self, notebook: Notebook, log: list[Event]
+ ) -> None:
+ notebook.replace(fixture_cells(), {})
+ log.clear()
+
+ changed = notebook.replace(
+ [CellSource("c1", "x = 22")], {}, saved=True
+ )
+
+ assert changed.document is not None
+ assert changed.document.saved_etag == changed.document.etag
+ assert names(log) == [
+ "cell",
+ "cell.removed",
+ "cell.removed",
+ "document",
+ ]
+ assert log[-1].data.document == changed.document # type: ignore[union-attr]
+
def test_edit_publishes_as_one_unit_with_the_request_key(
self, notebook: Notebook, log: list[Event]
) -> None:
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index a76b6df60f..57b6fe16d4 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -35,6 +35,7 @@ from marimo._plugins.ui._core.ui_element import UIElement
from marimo._runtime.commands import (
CreateNotebookCommand,
DeleteCellCommand,
+ EditCellsCommand,
ExecuteCellCommand,
UpdateCellConfigCommand,
UpdateUIElementCommand,
@@ -2192,6 +2193,49 @@ except NameError:
assert "c" in k.globals
assert "d" not in k.globals
+ async def test_edit_cells_registers_code_without_running(
+ self, any_kernel: Kernel
+ ) -> None:
+ k = any_kernel
+ await k.run([ExecuteCellCommand(cell_id="0", code="x = 1")])
+
+ await k.edit_cells(
+ EditCellsCommand(
+ codes={"0": "x = 2", "1": "y = 3"}, configs={}, delete_ids=[]
+ )
+ )
+
+ cell = k.graph.cells["0"]
+ assert cell.code == "x = 2"
+ assert cell.stale
+ assert "y" not in k.globals
+ # A cell the kernel has never seen arrives with its first run.
+ assert "1" not in k.graph.cells
+
+ async def test_edit_cells_replaces_pending_code(
+ self, any_kernel: Kernel
+ ) -> None:
+ k = any_kernel
+ await k.instantiate(
+ CreateNotebookCommand(
+ execution_requests=(
+ ExecuteCellCommand(cell_id="0", code="x = 0"),
+ ),
+ cell_ids=("0",),
+ set_ui_element_value_request=UpdateUIElementCommand.from_ids_and_values(
+ []
+ ),
+ auto_run=False,
+ )
+ )
+
+ await k.edit_cells(
+ EditCellsCommand(codes={"0": "x = 5"}, configs={}, delete_ids=[])
+ )
+
+ assert k._uninstantiated_execution_requests["0"].code == "x = 5"
+ assert not k.graph.cells
+
async def test_sync_graph_uninstantiated_request_cleanup(
self, any_kernel: Kernel
) -> None:
diff --git a/tests/_server/host/conftest.py b/tests/_server/host/conftest.py
index cdefd250af..5efe780541 100644
--- a/tests/_server/host/conftest.py
+++ b/tests/_server/host/conftest.py
@@ -10,11 +10,14 @@ from unittest.mock import MagicMock
import pytest
from marimo._core import backend as be
+from marimo._messaging.notebook import NotebookDocument
+from marimo._messaging.notification import NotificationMessage
from marimo._messaging.serde import serialize_kernel_message
from marimo._session.consumer import SessionConsumer
from marimo._session.events import SessionEventBus
from marimo._session.model import ConnectionState
from marimo._session.types import KernelState
+from marimo._types.ids import ConsumerId
class FakeSession:
@@ -25,6 +28,7 @@ class FakeSession:
self.event_bus = SessionEventBus()
self.consumers: list[tuple[SessionConsumer, bool]] = []
self.commands: list[Any] = []
+ self.notifications: list[NotificationMessage] = []
self.submitted = asyncio.Event()
self.interrupts = 0
self.closed = False
@@ -33,9 +37,7 @@ class FakeSession:
self.app_file_manager = MagicMock()
self.app_file_manager.path = path
self.app_file_manager.app.config.asdict_difference.return_value = {}
- self.document = MagicMock()
- self.document.cell_ids = []
- self.document.cells = []
+ self.document = NotebookDocument([])
self.session_view = MagicMock()
self.config_manager = MagicMock()
self.config_manager.get_config.return_value = {
@@ -88,6 +90,16 @@ class FakeSession:
for consumer, _ in list(self.consumers):
consumer.notify(message)
+ def notify(
+ self,
+ notification: NotificationMessage,
+ from_consumer_id: ConsumerId | None = None,
+ ) -> None:
+ """What a session does with a notification: record and broadcast."""
+ del from_consumer_id
+ self.notifications.append(notification)
+ self.broadcast(notification)
+
class FakeManager:
"""A session manager with configurable startup results and timing."""
diff --git a/tests/_server/host/test_host_api.py b/tests/_server/host/test_host_api.py
index bdb6768ca7..b35741196b 100644
--- a/tests/_server/host/test_host_api.py
+++ b/tests/_server/host/test_host_api.py
@@ -7,7 +7,7 @@ import asyncio
import json
import threading
from pathlib import Path
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any
from urllib.parse import parse_qs, urlsplit
import msgspec
@@ -29,6 +29,7 @@ from marimo._server.workspace import FixedFilesWorkspace, SingleFileWorkspace
from tests._core.conftest import ScriptedBackend, make_notebook, runtime_id_of
from tests._server.host.drive import (
PORT,
+ Response,
finished,
request,
until_ready,
@@ -40,6 +41,8 @@ from tests._server.mocks import (
)
if TYPE_CHECKING:
+ from collections.abc import Callable
+
from starlette.applications import Starlette
TOKEN = "record-token"
@@ -1541,3 +1544,122 @@ async def test_deleting_an_unreadable_notebook_does_not_initialize_it(
assert notebook_id not in harness.host.notebooks
assert not file.exists()
assert harness.backends == {}
+
+
+def edit_body(*changes: dict[str, object]) -> bytes:
+ return json.dumps({"changes": list(changes)}).encode()
+
+
+async def opened(harness: Harness) -> tuple[Response, Callable[[], None]]:
+ """Open the notebook's stream past `ready`, returning it and its closer."""
+ (harness.root / "forecasts.py").write_text(NOTEBOOK)
+ response, _, disconnect = request(
+ harness.app,
+ "GET",
+ f"/notebooks/{harness.notebook_id}/events",
+ headers=AUTH,
+ )
+ await wait_for(response, until_ready)
+ return response, disconnect
+
+
+def first_record(stream: Response, event: str) -> dict[str, Any]:
+ return next(r["data"] for r in stream.records if r.get("event") == event)
+
+
+async def test_an_edit_reaches_the_stream_as_one_unit(
+ harness: Harness,
+) -> None:
+ stream, disconnect = await opened(harness)
+ document = first_record(stream, "document")["document"]
+ first_id = document["order"][0]
+ # The first revision's analysis arrives off the event loop.
+ await wait_for(stream, lambda r: "analysis" in r.names())
+ seen = len(stream.records)
+
+ edited = await finished(
+ harness.app,
+ "POST",
+ f"/notebooks/{harness.notebook_id}/edits",
+ headers=key("edit-1"),
+ body=edit_body(
+ {
+ "kind": "put_cell",
+ "base_etag": None,
+ "after": first_id,
+ "cell": {"id": "fresh", "code": "z = 3"},
+ }
+ ),
+ )
+ assert edited.status == 200, edited.body
+ response = edited.json()
+ assert set(response["cells"]) == {"fresh"}
+ assert response["document"]["order"][1] == "fresh"
+ assert response["document"]["saved_etag"] == document["etag"]
+ assert response["document"]["etag"] != document["etag"]
+
+ await wait_for(stream, lambda r: r.names().count("analysis") >= 2)
+ after = [r for r in stream.records[seen:] if "event" in r]
+ assert [r["event"] for r in after] == ["cell", "document", "analysis"]
+ assert all(r["data"]["request_id"] == "edit-1" for r in after)
+ assert (
+ after[0]["data"]["cell"]["etag"] == response["cells"]["fresh"]["etag"]
+ )
+ assert after[1]["data"]["document"] == response["document"]
+ analysis = after[2]["data"]["analysis"]
+ assert analysis["document_etag"] == response["document"]["etag"]
+ assert analysis["cells"]["fresh"]["defs"] == ["z"]
+ assert "z = 3" not in (harness.root / "forecasts.py").read_text()
+ disconnect()
+
+
+async def test_a_stale_etag_is_a_conflict_that_changes_nothing(
+ harness: Harness,
+) -> None:
+ stream, disconnect = await opened(harness)
+ disconnect()
+ cell = first_record(stream, "cell")["cell"]
+ document = first_record(stream, "document")["document"]
+
+ refused = await finished(
+ harness.app,
+ "POST",
+ f"/notebooks/{harness.notebook_id}/edits",
+ headers=key("edit-stale"),
+ body=edit_body(
+ {
+ "kind": "put_cell",
+ "base_etag": None,
+ "cell": {"id": "new", "code": "1"},
+ },
+ {
+ "kind": "put_cell",
+ "base_etag": "0000000000000000",
+ "cell": {"id": cell["id"], "code": "x = 99"},
+ },
+ ),
+ )
+ assert refused.status == 409
+ problem = refused.json()
+ assert problem["type"].endswith("/conflict")
+ assert problem["edit"]["change"] == 1
+ assert problem["edit"]["cell"]["etag"] == cell["etag"]
+ assert problem["edit"]["document"]["etag"] == document["etag"]
+
+ invalid = await finished(
+ harness.app,
+ "POST",
+ f"/notebooks/{harness.notebook_id}/edits",
+ headers=key("edit-invalid"),
+ body=edit_body(
+ {"kind": "set_order", "base_etag": "*", "order": [cell["id"]]},
+ ),
+ )
+ assert invalid.status == 400
+ assert invalid.json()["type"].endswith("/invalid-request")
+
+ again, disconnect = await opened(harness)
+ disconnect()
+ assert (
+ first_record(again, "document")["document"]["etag"] == document["etag"]
+ )
diff --git a/tests/_server/host/test_host_bridge.py b/tests/_server/host/test_host_bridge.py
index 7b96cbfc11..4b5cbe5d83 100644
--- a/tests/_server/host/test_host_bridge.py
+++ b/tests/_server/host/test_host_bridge.py
@@ -444,3 +444,301 @@ async def test_failed_session_move_preserves_the_notebook(
assert bridge.host.notebooks[notebook.id].path == "a.py"
assert (await bridge.host.notebook(notebook.id)).runtime is runtime
bridge.close()
+
+
+async def test_editor_transactions_reach_the_host_document(
+ manager: FakeManager, tmp_path: Path
+) -> None:
+ from marimo._ast.cell import CellConfig
+ from marimo._messaging.notebook import (
+ NotebookCell,
+ NotebookDocument,
+ SetCode,
+ Transaction,
+ )
+ from marimo._messaging.notification import (
+ NotebookDocumentTransactionNotification,
+ )
+ from marimo._types.ids import CellId_t
+
+ prepare(manager, tmp_path, "a.py")
+ session = FakeSession(str(tmp_path / "a.py"))
+ session.document = NotebookDocument(
+ [NotebookCell(CellId_t("Hbol"), "x = 1", "_", CellConfig())]
+ )
+ manager.sessions["browser-1"] = session
+ bridge = SessionBridge(manager) # type: ignore[arg-type]
+ await bridge.open()
+ record = bridge.index.notebook_for(str(tmp_path / "a.py"))
+ assert record is not None
+ events: list[Event] = []
+ bridge.host.subscribe(events.append, notebook_id=record.id)
+
+ # The document comes from the session, ids included.
+ document = (await bridge.host.notebook(record.id)).document
+ assert document.order == ["Hbol"]
+
+ # A frontend edit reaches the host document, and the app config as
+ # the session reports it comes along.
+ applied = session.document.apply(
+ Transaction(
+ changes=(SetCode(CellId_t("Hbol"), "x = 2"),), source="frontend"
+ )
+ )
+ session.app_file_manager.app.config.asdict_difference.return_value = {
+ "width": "full"
+ }
+ session.broadcast(
+ NotebookDocumentTransactionNotification(transaction=applied)
+ )
+
+ cell = document.cell("Hbol")
+ assert cell is not None
+ assert cell.code == "x = 2"
+ assert document._record.app_config == {"width": "full"}
+ assert names(events)[-2:] == ["cell", "document"]
+ bridge.close()
+
+
+async def test_host_edits_reach_the_session_as_one_transaction(
+ manager: FakeManager, tmp_path: Path
+) -> None:
+ from marimo._ast.cell import CellConfig
+ from marimo._messaging.notebook import NotebookCell, NotebookDocument
+ from marimo._messaging.notification import (
+ NotebookDocumentTransactionNotification,
+ )
+ from marimo._types.ids import CellId_t
+
+ prepare(manager, tmp_path, "a.py")
+ session = FakeSession(str(tmp_path / "a.py"))
+ session.document = NotebookDocument(
+ [NotebookCell(CellId_t("Hbol"), "x = 1", "_", CellConfig())]
+ )
+ manager.sessions["browser-1"] = session
+ bridge = SessionBridge(manager) # type: ignore[arg-type]
+ await bridge.open()
+ record = bridge.index.notebook_for(str(tmp_path / "a.py"))
+ assert record is not None
+ document = (await bridge.host.notebook(record.id)).document
+ events: list[Event] = []
+ bridge.host.subscribe(events.append, notebook_id=record.id)
+
+ response = await bridge.edit(
+ record.id,
+ [
+ protocol.PutCell(
+ base_etag=None,
+ cell=protocol.CellInput(
+ id=protocol.CellId("new"), code="y = x"
+ ),
+ )
+ ],
+ request_id="edit-1",
+ )
+
+ assert set(response.cells) == {"new"}
+ assert session.document.cell_ids == ["Hbol", "new"]
+ (notification,) = session.notifications
+ assert isinstance(notification, NotebookDocumentTransactionNotification)
+ assert notification.transaction.source == "host"
+ # The backend saw its own edit come back and mirrored nothing new.
+ assert names(events) == ["cell", "document"]
+ assert document._record.etag == response.document.etag
+ assert "y = x" not in (tmp_path / "a.py").read_text()
+ bridge.close()
+
+
+async def test_edit_response_includes_app_config_mirrored_from_the_session(
+ manager: FakeManager, tmp_path: Path
+) -> None:
+ from marimo._session.notebook import AppFileManager
+
+ prepare(manager, tmp_path, "a.py")
+ path = tmp_path / "a.py"
+ path.write_text(NOTEBOOK)
+ session = FakeSession(str(path))
+ session.document = AppFileManager(str(path)).app.cell_manager.document
+ manager.sessions["browser-1"] = session
+ bridge = SessionBridge(manager) # type: ignore[arg-type]
+ await bridge.open()
+ try:
+ record = bridge.index.notebook_for(str(path))
+ assert record is not None
+ notebook = await bridge.host.notebook(record.id)
+ session.app_file_manager.app.config.asdict_difference.return_value = {
+ "width": "full"
+ }
+
+ response = await bridge.edit(
+ record.id,
+ [
+ protocol.PutCell(
+ base_etag=None,
+ cell=protocol.CellInput(
+ id=protocol.CellId("new"), code="y = 2"
+ ),
+ )
+ ],
+ request_id="edit-1",
+ )
+
+ current = notebook.document.snapshot().document
+ assert current.app_config == {"width": "full"}
+ assert response.document == current
+ finally:
+ bridge.close()
+
+
+async def test_a_new_session_replaces_a_read_without_host_edits(
+ manager: FakeManager, tmp_path: Path
+) -> None:
+ from marimo._session.notebook import AppFileManager
+
+ prepare(manager, tmp_path, "a.py")
+ path = tmp_path / "a.py"
+ path.write_text(NOTEBOOK)
+ bridge = SessionBridge(manager) # type: ignore[arg-type]
+ await bridge.open()
+ record = bridge.index.notebook_for(str(path))
+ assert record is not None
+ document = (await bridge.host.notebook(record.id)).document
+ events: list[Event] = []
+ bridge.host.subscribe(events.append, notebook_id=record.id)
+
+ # The file changes after the host read it, then a session opens it.
+ path.write_text(NOTEBOOK.replace("x = 1", "x = 2"))
+ session = FakeSession(str(path))
+ session.document = AppFileManager(str(path)).app.cell_manager.document
+ await manager.event_bus.emit_session_created(session) # type: ignore[arg-type]
+
+ assert [cell.code for cell in document] == ["x = 2"]
+ assert document._record.saved_etag == document._record.etag
+ assert names(events)[-3:] == ["cell", "document", "runtime"]
+ assert session.notifications == []
+ bridge.close()
+
+
+async def test_a_new_session_adopts_unsaved_host_edits(
+ manager: FakeManager, tmp_path: Path
+) -> None:
+ from marimo._ast.cell import CellConfig
+ from marimo._messaging.notebook import NotebookCell, NotebookDocument
+ from marimo._types.ids import CellId_t
+
+ def editor_cell(cell: protocol.Cell) -> NotebookCell:
+ return NotebookCell(
+ CellId_t(cell.id), cell.code, cell.name, CellConfig()
+ )
+
+ prepare(manager, tmp_path, "a.py")
+ bridge = SessionBridge(manager) # type: ignore[arg-type]
+ await bridge.open()
+ record = bridge.index.notebook_for(str(tmp_path / "a.py"))
+ assert record is not None
+ document = (await bridge.host.notebook(record.id)).document
+ session = FakeSession(str(tmp_path / "a.py"))
+ session.document = NotebookDocument(editor_cell(c) for c in document)
+ await bridge.edit(
+ record.id,
+ [
+ protocol.PutCell(
+ base_etag=None,
+ cell=protocol.CellInput(
+ id=protocol.CellId("new"), code="unsaved = 42"
+ ),
+ )
+ ],
+ request_id="edit-before-session",
+ )
+
+ await manager.event_bus.emit_session_created(session) # type: ignore[arg-type]
+
+ assert [(c.id, c.code) for c in session.document.cells] == [
+ (c.id, c.code) for c in document
+ ]
+ assert document._record.saved_etag != document._record.etag
+ assert "unsaved" not in (tmp_path / "a.py").read_text()
+ bridge.close()
+
+
+async def test_an_edit_reaches_the_kernel_as_one_command(
+ manager: FakeManager, tmp_path: Path
+) -> None:
+ from marimo._runtime.commands import EditCellsCommand
+ from marimo._session.notebook import AppFileManager
+
+ prepare(manager, tmp_path, "a.py")
+ path = tmp_path / "a.py"
+ path.write_text(
+ NOTEBOOK + "@app.cell\ndef _(x):\n y = x\n return (y,)\n"
+ )
+ session = FakeSession(str(path))
+ session.document = AppFileManager(str(path)).app.cell_manager.document
+ manager.sessions["browser-1"] = session
+ bridge = SessionBridge(manager) # type: ignore[arg-type]
+ await bridge.open()
+ record = bridge.index.notebook_for(str(path))
+ assert record is not None
+ first, second = (await bridge.host.notebook(record.id)).document
+
+ await bridge.edit(
+ record.id,
+ [
+ protocol.PutCell(
+ base_etag=first.etag,
+ cell=protocol.CellInput(
+ id=first.id,
+ code=first.code,
+ config=protocol.CellConfigInput(disabled=True),
+ ),
+ ),
+ protocol.DeleteCell(id=second.id, base_etag=second.etag),
+ protocol.PutCell(
+ base_etag=None,
+ cell=protocol.CellInput(
+ id=protocol.CellId("new"),
+ code="z = 1",
+ config=protocol.CellConfigInput(hide_code=True),
+ ),
+ ),
+ ],
+ request_id="edit-1",
+ )
+
+ default = {
+ "column": None,
+ "disabled": False,
+ "hide_code": False,
+ "expand_output": False,
+ }
+ assert session.commands == [
+ EditCellsCommand(
+ codes={"new": "z = 1"},
+ configs={
+ first.id: {**default, "disabled": True},
+ "new": {**default, "hide_code": True},
+ },
+ delete_ids=[second.id],
+ )
+ ]
+
+ # Changed code reaches the kernel without a run.
+ await bridge.edit(
+ record.id,
+ [
+ protocol.PutCell(
+ base_etag="*",
+ cell=protocol.CellInput(
+ id=protocol.CellId("new"),
+ code="z = 2",
+ config=protocol.CellConfigInput(hide_code=True),
+ ),
+ )
+ ],
+ request_id="edit-2",
+ )
+ assert session.commands[1:] == [
+ EditCellsCommand(codes={"new": "z = 2"}, configs={}, delete_ids=[])
+ ]
+ bridge.close()
diff --git a/tests/_server/host/test_host_document.py b/tests/_server/host/test_host_document.py
new file mode 100644
index 0000000000..f744d575a0
--- /dev/null
+++ b/tests/_server/host/test_host_document.py
@@ -0,0 +1,113 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""Host edits delivered to the editor and kernel."""
+
+from __future__ import annotations
+
+import pytest
+
+from marimo._ast.cell import CellConfig
+from marimo._core import protocol
+from marimo._core.document import CellSource, Document
+from marimo._messaging.notebook import (
+ NotebookCell,
+ NotebookDocument,
+ ReorderCells,
+)
+from marimo._messaging.notification import (
+ NotebookDocumentTransactionNotification,
+)
+from marimo._runtime.commands import ExecuteCellCommand
+from marimo._server.host.document import apply_to_session
+from marimo._types.ids import CellId_t
+from tests._runtime._helpers.session import mocked_kernel_session
+from tests._server.host.conftest import FakeSession
+
+
+def test_deleting_all_cells_broadcasts_the_final_order() -> None:
+ session = FakeSession()
+ session.document = NotebookDocument(
+ [NotebookCell(CellId_t("a"), "x = 1", "_", CellConfig())]
+ )
+ document = Document(protocol.NotebookId("nb"), [], {})
+
+ apply_to_session(session, document) # type: ignore[arg-type]
+
+ notification = session.notifications[0]
+ assert isinstance(notification, NotebookDocumentTransactionNotification)
+ # The editor guards the last deletion; the final ordering must clear it.
+ assert notification.transaction.changes[-1] == ReorderCells(cell_ids=())
+ assert session.document.cell_ids == []
+
+
+async def test_enabling_an_edited_cell_does_not_run_old_code() -> None:
+ cell_id = CellId_t("a")
+ old_code, new_code = 'print("old")', 'print("new")'
+ session = FakeSession()
+ session.document = NotebookDocument(
+ [NotebookCell(cell_id, old_code, "_", CellConfig(disabled=True))]
+ )
+ document = Document(
+ protocol.NotebookId("nb"), [CellSource(cell_id, new_code)], {}
+ )
+
+ with mocked_kernel_session(
+ configs={cell_id: CellConfig(disabled=True)}
+ ) as runtime:
+ await runtime.kernel.run(
+ [ExecuteCellCommand(cell_id=cell_id, code=old_code)]
+ )
+ apply_to_session(session, document) # type: ignore[arg-type]
+ for command in session.commands:
+ await runtime.kernel.handle_message(command)
+
+ assert "old" not in "".join(runtime.stdout.messages)
+
+
+ "delete_dependent", [True, False], ids=["delete", "disable"]
+)
+async def test_deleted_or_disabled_cells_do_not_run_during_an_edit(
+ delete_dependent: bool,
+) -> None:
+ first, second = CellId_t("a"), CellId_t("b")
+ code = (
+ 'print("ran")\ntry:\n result = x\nexcept NameError:\n result = 0'
+ )
+ session = FakeSession()
+ session.document = NotebookDocument(
+ [
+ NotebookCell(first, "x = 1", "_", CellConfig()),
+ NotebookCell(second, code, "_", CellConfig()),
+ ]
+ )
+ cells = (
+ []
+ if delete_dependent
+ else [
+ CellSource(
+ second,
+ code,
+ config=protocol.CellConfig(
+ column=None,
+ disabled=True,
+ hide_code=False,
+ expand_output=False,
+ ),
+ )
+ ]
+ )
+ document = Document(protocol.NotebookId("nb"), cells, {})
+
+ with mocked_kernel_session() as runtime:
+ await runtime.kernel.run(
+ [
+ ExecuteCellCommand(cell_id=first, code="x = 1"),
+ ExecuteCellCommand(cell_id=second, code=code),
+ ]
+ )
+ runtime.stdout.messages.clear()
+ apply_to_session(session, document) # type: ignore[arg-type]
+ for command in session.commands:
+ await runtime.kernel.handle_message(command)
+
+ assert runtime.stdout.messages == []