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.

Add internal code mode module for programmatic notebook control (#8670)

Trevor Manz1e5a7bf70a64
diff --git a/marimo/_code_mode/__init__.py b/marimo/_code_mode/__init__.py
new file mode 100644
index 0000000000..bb321c2a77
--- /dev/null
+++ b/marimo/_code_mode/__init__.py
@@ -0,0 +1,45 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""Code mode: programmatic notebook editing via async context manager.
+
+.. warning::
+
+ **Internal, agent-only API.** Not part of marimo's public API.
+ No versioning guarantees. May change or be removed without notice.
+
+Usage::
+
+ import marimo._code_mode as cm
+
+ async with cm.get_context() as ctx:
+ # Create cells (appends at end by default)
+ cid = ctx.create_cell("x = 1")
+ ctx.create_cell("y = x + 1", after=cid)
+
+ # Update cells by ID or name
+ ctx.edit_cell("my_cell", code="z = 42")
+
+ # Delete cells
+ ctx.delete_cell("old_cell")
+
+ # Move cells
+ ctx.move_cell("my_cell", after="other_cell")
+
+ # Read cells (works outside the context manager too)
+ ctx = cm.get_context()
+ ctx.cells[0] # by index
+ ctx.cells["my_cell"] # by name
+"""
+
+from __future__ import annotations
+
+from marimo._code_mode._context import (
+ AsyncCodeModeContext,
+ NotebookCellData,
+ get_context,
+)
+
+__all__ = [
+ "AsyncCodeModeContext",
+ "NotebookCellData",
+ "get_context",
+]
diff --git a/marimo/_code_mode/_context.py b/marimo/_code_mode/_context.py
new file mode 100644
index 0000000000..817cde3ebf
--- /dev/null
+++ b/marimo/_code_mode/_context.py
@@ -0,0 +1,1048 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""AsyncCodeModeContext: programmatic notebook editing via async context manager.
+
+.. warning::
+
+ **Internal, agent-only API.** Not part of marimo's public API.
+ No versioning guarantees. May change or be removed without notice.
+
+Usage::
+
+ import marimo._code_mode as cm
+
+ async with cm.get_context() as ctx:
+ cid = ctx.create_cell("x = 1")
+ ctx.create_cell("y = x + 1", after=cid)
+ ctx.edit_cell("my_cell", code="z = 42")
+ ctx.delete_cell("old_cell")
+ ctx.move_cell("my_cell", after="other_cell")
+"""
+
+from __future__ import annotations
+
+import sys
+from dataclasses import dataclass, field
+from typing import TYPE_CHECKING, Any, overload
+from uuid import uuid4
+
+from marimo import _loggers
+from marimo._ast.cell import CellConfig, CellImpl
+from marimo._ast.cell_id import CellIdGenerator
+from marimo._ast.compiler import compile_cell
+from marimo._ast.names import SETUP_CELL_NAME
+from marimo._code_mode._plan import (
+ _AddOp,
+ _build_plan,
+ _DeleteOp,
+ _MoveOp,
+ _Op,
+ _PlanEntry,
+ _UpdateOp,
+ _validate_ops,
+)
+from marimo._messaging.notification import (
+ Notification,
+ UpdateCellCodesNotification,
+ UpdateCellIdsNotification,
+)
+from marimo._messaging.notification_utils import broadcast_notification
+from marimo._runtime.commands import (
+ CommandMessage,
+ DeleteCellCommand,
+ ExecuteCellCommand,
+ InstallPackagesCommand,
+ UpdateCellConfigCommand,
+ UpdateUIElementCommand,
+)
+from marimo._runtime.context import get_context as _get_runtime_context
+from marimo._runtime.context.kernel_context import KernelRuntimeContext
+from marimo._runtime.runtime import CellMetadata
+from marimo._types.ids import CellId_t, UIElementId
+from marimo._utils.formatter import DefaultFormatter
+
+if TYPE_CHECKING:
+ from collections.abc import Iterator
+ from types import TracebackType
+
+ from marimo._ast.cell_manager import CellManager
+ from marimo._runtime.dataflow import DirectedGraph
+ from marimo._runtime.runtime import Kernel
+
+
+# ------------------------------------------------------------------
+# Data types
+# ------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class NotebookCellData:
+ """Read-only snapshot of a notebook cell (returned by ``ctx.cells[...]``)."""
+
+ code: str | None = None
+ config: CellConfig | None = None
+ cell_id: CellId_t = field(default_factory=lambda: CellId_t(str(uuid4())))
+ name: str | None = field(default=None, repr=True, compare=False)
+
+
+LOGGER = _loggers.marimo_logger()
+
+# Module-level store for cell names set via code_mode.
+# Persists across context manager invocations within the same kernel.
+_cell_names: dict[CellId_t, str] = {}
+
+
+# ------------------------------------------------------------------
+# Entry point
+# ------------------------------------------------------------------
+
+
+def get_context(*, check: bool = True) -> AsyncCodeModeContext:
+ """Return an ``AsyncCodeModeContext`` for the running kernel.
+
+ Use as an async context manager::
+
+ async with cm.get_context() as ctx:
+ ctx.create_cell("x = 1")
+
+ By default, a dry-run compile check is performed on exit to catch
+ syntax errors, multiply-defined names, and cycles before any graph
+ mutations. Pass ``check=False`` to skip this validation::
+
+ async with cm.get_context(check=False) as ctx:
+ ...
+ """
+ runtime_ctx = _get_runtime_context()
+ if not isinstance(runtime_ctx, KernelRuntimeContext):
+ raise RuntimeError("code mode requires a running kernel context") # noqa: TRY004
+ cell_manager = runtime_ctx._app.cell_manager if runtime_ctx._app else None
+ return AsyncCodeModeContext(
+ runtime_ctx._kernel, cell_manager=cell_manager, check=check
+ )
+
+
+class _CellsView:
+ """Read-only view over notebook cells as ``NotebookCellData`` objects.
+
+ Supports lookup by integer index, cell ID, or cell name::
+
+ ctx.cells[0] # by index
+ ctx.cells[-1] # negative index
+ ctx.cells["Abcd1234"] # by cell ID
+ ctx.cells["my_cell"] # by cell name
+ """
+
+ def __init__(self, ctx: AsyncCodeModeContext) -> None:
+ self._ctx = ctx
+
+ def _cell_ids(self) -> list[CellId_t]:
+ return list(self._ctx.graph.cells.keys())
+
+ def _cell_name(self, cell_id: CellId_t) -> str | None:
+ # Check code_mode's own name store first.
+ name = _cell_names.get(cell_id)
+ if name is not None:
+ return name
+ # Fall back to cell_manager if available.
+ cm = self._ctx._cell_manager
+ if cm is None:
+ return None
+ data = cm.get_cell_data(cell_id)
+ return data.name if data else None
+
+ def _build_at(self, cell_id: CellId_t) -> NotebookCellData:
+ cell_impl = self._ctx.graph.cells[cell_id]
+ meta = self._ctx._kernel.cell_metadata.get(cell_id)
+ return NotebookCellData(
+ code=cell_impl.code,
+ config=meta.config if meta else CellConfig(),
+ name=self._cell_name(cell_id),
+ cell_id=cell_id,
+ )
+
+ def _resolve(self, target: str) -> CellId_t:
+ """Resolve a cell ID or cell name to a ``CellId_t``.
+
+ Raises ``KeyError`` if not found.
+ """
+ cell_ids = self._cell_ids()
+
+ # Try cell ID first.
+ cell_id_key = CellId_t(target)
+ for cid in cell_ids:
+ if cid == cell_id_key:
+ return cid
+
+ # Fall back to cell name.
+ for cid in cell_ids:
+ name = self._cell_name(cid)
+ if name == target:
+ return cid
+
+ raise KeyError(target)
+
+ def __len__(self) -> int:
+ return len(self._ctx.graph.cells)
+
+ @overload
+ def __getitem__(self, key: int) -> NotebookCellData: ...
+ @overload
+ def __getitem__(self, key: str) -> NotebookCellData: ...
+
+ def __getitem__(self, key: int | str) -> NotebookCellData:
+ cell_ids = self._cell_ids()
+
+ if isinstance(key, int):
+ return self._build_at(cell_ids[key])
+
+ return self._build_at(self._resolve(key))
+
+ def __iter__(self) -> Iterator[NotebookCellData]:
+ for cid in self._cell_ids():
+ yield self._build_at(cid)
+
+
+# ------------------------------------------------------------------
+# Context
+# ------------------------------------------------------------------
+
+
+class AsyncCodeModeContext:
+ """Async programmatic control of a running marimo notebook.
+
+ Use as an async context manager — mutations are queued during the
+ block and applied atomically on exit::
+
+ async with cm.get_context() as ctx:
+ ctx.create_cell("x = 1")
+ ctx.edit_cell("my_cell", code="x = 42")
+ ctx.delete_cell("old_cell")
+
+ Read cells via ``ctx.cells[key]`` where *key* is an integer index,
+ cell ID string, or cell name.
+ """
+
+ def __init__(
+ self,
+ kernel: Kernel,
+ cell_manager: CellManager | None = None,
+ *,
+ check: bool = True,
+ ) -> None:
+ self._kernel = kernel
+ self._cell_manager = cell_manager
+ self._check = check
+ self._ops: list[_Op] = []
+ # Track cell IDs added during this batch so subsequent ops
+ # can reference them before they exist in the graph.
+ self._pending_adds: dict[CellId_t, _AddOp] = {}
+ # ID generator for new cells — seeded with existing IDs to
+ # avoid collisions.
+ self._id_generator = CellIdGenerator()
+ self._id_generator.seen_ids = set(kernel.graph.cells.keys())
+ self._packages_to_install: list[str] = []
+ self._ui_updates: list[tuple[UIElementId, Any]] = []
+ self._entered = False
+
+ def _require_entered(self) -> None:
+ if not self._entered:
+ raise RuntimeError(
+ "Cell operations require 'async with'. Use:\n"
+ "\n"
+ " async with cm.get_context() as ctx:\n"
+ " ctx.create_cell(...)\n"
+ "\n"
+ "Without 'async with', operations are silently lost."
+ )
+
+ # ------------------------------------------------------------------
+ # Async context manager
+ # ------------------------------------------------------------------
+
+ async def __aenter__(self) -> AsyncCodeModeContext:
+ self._ops = []
+ self._pending_adds = {}
+ self._packages_to_install = []
+ self._ui_updates = []
+ self._entered = True
+ return self
+
+ async def __aexit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_val: BaseException | None,
+ exc_tb: TracebackType | None,
+ ) -> None:
+ ops = self._ops
+ packages = self._packages_to_install
+ ui_updates = self._ui_updates
+ self._ops = []
+ self._pending_adds = {}
+ self._packages_to_install = []
+ self._ui_updates = []
+
+ if exc_type is not None:
+ return # let exception propagate, discard queued ops
+
+ # Install queued packages before applying cell ops so that
+ # newly added cells can import them.
+ if packages:
+ manager = self._kernel.user_config["package_management"]["manager"]
+ for pkg in packages:
+ await self.execute_command(
+ InstallPackagesCommand(manager=manager, versions={pkg: ""})
+ )
+
+ if ops:
+ _validate_ops(ops)
+ if self._check:
+ self._dry_run_compile(ops)
+ await self._apply_ops(ops)
+
+ # Flush queued UI updates as a single batch.
+ if ui_updates:
+ object_ids, values = zip(*ui_updates)
+ await self._kernel.set_ui_element_value(
+ UpdateUIElementCommand(
+ object_ids=list(object_ids),
+ values=list(values),
+ )
+ )
+
+ # Print a summary of what was applied.
+ self._print_summary(ops, packages, ui_updates)
+
+ # ------------------------------------------------------------------
+ # Summary
+ # ------------------------------------------------------------------
+
+ def _print_summary(
+ self,
+ ops: list[_Op],
+ packages: list[str],
+ ui_updates: list[tuple[UIElementId, Any]],
+ ) -> None:
+ """Print a human-readable summary of applied operations."""
+ lines: list[str] = []
+
+ for pkg in packages:
+ lines.append(f"installed {pkg}")
+
+ for op in ops:
+ cell_id = op.cell_id
+ label = self._cell_label(cell_id)
+ if isinstance(op, _AddOp):
+ lines.append(f"created cell {label}")
+ elif isinstance(op, _UpdateOp):
+ parts = []
+ if op.code is not None:
+ parts.append("code")
+ if op.config is not None:
+ parts.append("config")
+ detail = " and ".join(parts) if parts else "config"
+ lines.append(f"edited {detail} of cell {label}")
+ elif isinstance(op, _DeleteOp):
+ lines.append(f"deleted cell {label}")
+ elif isinstance(op, _MoveOp):
+ lines.append(f"moved cell {label}")
+
+ if ui_updates:
+ lines.append(f"updated {len(ui_updates)} UI element(s)")
+
+ if not lines:
+ return
+
+ for line in lines:
+ sys.stdout.write(line + "\n")
+
+ def _cell_label(self, cell_id: CellId_t) -> str:
+ """Return a display label for a cell: name if available, else short ID."""
+ cm = self._cell_manager
+ if cm is not None:
+ data = cm.get_cell_data(cell_id)
+ if data and data.name:
+ return repr(data.name)
+ short = str(cell_id)[:8]
+ return repr(short)
+
+ # ------------------------------------------------------------------
+ # Read-only attributes
+ # ------------------------------------------------------------------
+
+ @property
+ def graph(self) -> DirectedGraph:
+ """The notebook's dependency graph."""
+ return self._kernel.graph
+
+ @property
+ def globals(self) -> dict[str, Any]:
+ """The kernel's global namespace (all variables defined by cells)."""
+ return self._kernel.globals
+
+ @property
+ def cells(self) -> _CellsView:
+ """Read-only view of notebook cells.
+
+ Supports lookup by index, cell ID, or cell name::
+
+ ctx.cells[0] # by index
+ ctx.cells["cell-id"] # by cell ID
+ ctx.cells["my_cell"] # by cell name
+ """
+ return _CellsView(self)
+
+ # ------------------------------------------------------------------
+ # Mutation methods (queue ops, applied on __aexit__)
+ # ------------------------------------------------------------------
+
+ def _resolve_target(self, target: str) -> CellId_t:
+ """Resolve a cell ID or name to a ``CellId_t``.
+
+ Checks the live graph first, then pending adds (by ID and by
+ name), then queued renames from ``edit_cell``.
+ """
+ # Try the live graph.
+ try:
+ return self.cells._resolve(target)
+ except KeyError:
+ pass
+
+ # Try pending adds (by cell ID).
+ cid = CellId_t(target)
+ if cid in self._pending_adds:
+ return cid
+
+ # Try pending adds (by name).
+ for pending_id, add_op in self._pending_adds.items():
+ if add_op.name == target:
+ return pending_id
+
+ # Try queued renames from edit_cell ops.
+ for op in self._ops:
+ if isinstance(op, _UpdateOp) and op.name == target:
+ return op.new_cell_id or op.cell_id
+
+ raise KeyError(
+ f"Cell {target!r} not found in notebook or pending adds"
+ )
+
+ def _resolve_new_cell(
+ self, name: str | None
+ ) -> tuple[CellId_t, str | None]:
+ """Return ``(cell_id, resolved_name)`` for a new cell.
+
+ The ``"setup"`` name is special-cased to use the well-known setup
+ cell ID. Raises ``ValueError`` if a setup cell already exists.
+ """
+ if name == SETUP_CELL_NAME:
+ # Check if a setup cell already exists (by name or by ID).
+ try:
+ self.cells._resolve(SETUP_CELL_NAME)
+ raise ValueError(
+ "A setup cell already exists. Use "
+ 'ctx.edit_cell("setup", code=...) to modify it.'
+ )
+ except KeyError:
+ pass
+ cell_id = (
+ self._cell_manager.setup_cell_id
+ if self._cell_manager is not None
+ else CellId_t(SETUP_CELL_NAME)
+ )
+ # Setup is identified by cell_id, not name — clear the name.
+ return cell_id, None
+ cell_id = self._id_generator.create_cell_id()
+ return cell_id, name
+
+ def create_cell(
+ self,
+ code: str,
+ *,
+ before: str | None = None,
+ after: str | None = None,
+ hide_code: bool = True,
+ disabled: bool = False,
+ column: int | None = None,
+ draft: bool = False,
+ name: str | None = None,
+ ) -> CellId_t:
+ """Queue a new cell. Returns the new cell's ID.
+
+ The returned ID can be used in subsequent operations within the
+ same batch (e.g. as an ``after`` target for the next cell).
+
+ Examples:
+ ```python
+ # Append at the end
+ cid = ctx.create_cell("import pandas as pd")
+
+ # Chain cells in order
+ cid2 = ctx.create_cell("df = pd.read_csv('data.csv')", after=cid)
+ ctx.create_cell("df.head()", after=cid2)
+
+ # Insert before a named cell, with code visible
+ ctx.create_cell("# Setup", before="analysis", hide_code=False)
+
+ # Stage without executing
+ ctx.create_cell("expensive_computation()", draft=True)
+
+ # Create a setup cell with imports, then a cell that uses them
+ ctx.create_cell("import marimo as mo", name="setup")
+ ctx.create_cell("mo.md('# Hello')", name="greeting")
+ ```
+
+ Args:
+ code (str): Python source code for the cell.
+ before (str, optional): Insert before this cell (ID or name).
+ Mutually exclusive with ``after``.
+ after (str, optional): Insert after this cell (ID or name).
+ Mutually exclusive with ``before``.
+ hide_code (bool): Collapse the code editor in the UI.
+ Defaults to True.
+ disabled (bool): Prevent the cell from executing.
+ Defaults to False.
+ column (int, optional): Column index for multi-column layouts.
+ draft (bool): Insert code without executing it.
+ Defaults to False.
+ name (str, optional): Name for the cell (e.g. ``"data_loader"``,
+ ``"setup"`` for a setup cell).
+ """
+ self._require_entered()
+ if before is not None and after is not None:
+ raise ValueError("Cannot specify both 'before' and 'after'")
+
+ cell_id, resolved_name = self._resolve_new_cell(name)
+
+ config = CellConfig(
+ hide_code=hide_code, disabled=disabled, column=column
+ )
+
+ before_id = (
+ self._resolve_target(before) if before is not None else None
+ )
+ after_id = self._resolve_target(after) if after is not None else None
+
+ op = _AddOp(
+ cell_id=cell_id,
+ code=code,
+ config=config,
+ draft=draft,
+ before=before_id,
+ after=after_id,
+ name=resolved_name,
+ )
+ self._ops.append(op)
+ self._pending_adds[cell_id] = op
+ return cell_id
+
+ def edit_cell(
+ self,
+ target: str,
+ *,
+ code: str | None = None,
+ hide_code: bool | None = None,
+ disabled: bool | None = None,
+ column: int | None = None,
+ draft: bool = False,
+ name: str | None = None,
+ ) -> None:
+ """Queue an update to an existing cell's code and/or config.
+
+ Only the arguments you explicitly pass are changed — the cell's
+ existing config is preserved for any argument left as ``None``.
+
+ Examples:
+ ```python
+ # Update only code (config like hide_code is preserved)
+ ctx.edit_cell(
+ "data_loader", code="df = pd.read_parquet('new.parquet')"
+ )
+
+ # Update only config (code is preserved)
+ ctx.edit_cell("data_loader", hide_code=False)
+
+ # Update both code and config
+ ctx.edit_cell("data_loader", code="df = load()", disabled=True)
+
+ # Stage new code without executing
+ ctx.edit_cell("my_cell", code="new_code()", draft=True)
+
+ # Rename a cell
+ ctx.edit_cell("old_name", name="new_name")
+ ```
+
+ Args:
+ target (str): Cell ID or cell name.
+ code (str, optional): New Python source code. None keeps existing.
+ hide_code (bool, optional): Collapse the code editor. None keeps existing.
+ disabled (bool, optional): Prevent the cell from executing. None keeps existing.
+ column (int, optional): Column index for multi-column layouts. None keeps existing.
+ draft (bool): Update code without executing. Defaults to False.
+ name (str, optional): New name for the cell. None keeps existing.
+ """
+ self._require_entered()
+ cell_id = self._resolve_target(target)
+
+ # Handle cell-id migration when converting to a setup cell.
+ # Setup is identified by cell_id, not name — clear the name
+ # and migrate to the well-known setup cell_id.
+ new_cell_id: CellId_t | None = None
+ if name == SETUP_CELL_NAME:
+ setup_id = (
+ self._cell_manager.setup_cell_id
+ if self._cell_manager is not None
+ else CellId_t(SETUP_CELL_NAME)
+ )
+ if cell_id != setup_id:
+ # Check that no setup cell already exists.
+ try:
+ self.cells._resolve(SETUP_CELL_NAME)
+ raise ValueError(
+ "A setup cell already exists. Use "
+ 'ctx.edit_cell("setup", code=...) to modify it.'
+ )
+ except KeyError:
+ pass
+ new_cell_id = setup_id
+ # Ensure code is populated — the new cell_id won't
+ # exist in the graph, so _apply_ops needs the code.
+ if code is None and cell_id in self.graph.cells:
+ code = self.graph.cells[cell_id].code
+ # Setup is identified by cell_id alone — don't store a name.
+ name = None
+
+ # Build config only if any config kwarg was explicitly set.
+ config: CellConfig | None = None
+ if hide_code is not None or disabled is not None or column is not None:
+ # Start from existing config and override provided fields.
+ meta = self._kernel.cell_metadata.get(cell_id)
+ existing = meta.config if meta else CellConfig()
+ config = CellConfig(
+ hide_code=hide_code
+ if hide_code is not None
+ else existing.hide_code,
+ disabled=disabled
+ if disabled is not None
+ else existing.disabled,
+ column=column if column is not None else existing.column,
+ )
+
+ self._ops.append(
+ _UpdateOp(
+ cell_id=cell_id,
+ code=code,
+ config=config,
+ draft=draft,
+ name=name,
+ new_cell_id=new_cell_id,
+ )
+ )
+
+ def delete_cell(self, target: str) -> None:
+ """Queue a cell for deletion.
+
+ Examples:
+ ```python
+ ctx.delete_cell("scratch") # by name
+ ctx.delete_cell("a1b2c3d4-...") # by cell ID
+ ```
+
+ Args:
+ target (str): Cell ID or cell name to delete.
+ """
+ self._require_entered()
+ cell_id = self._resolve_target(target)
+ self._ops.append(_DeleteOp(cell_id=cell_id))
+
+ def move_cell(
+ self,
+ target: str,
+ *,
+ before: str | None = None,
+ after: str | None = None,
+ ) -> None:
+ """Queue a cell to be repositioned in the notebook.
+
+ Moves only affect visual ordering — they do not re-execute
+ cells or change the dependency graph.
+
+ Examples:
+ ```python
+ ctx.move_cell("imports", before="analysis")
+ ctx.move_cell("cleanup", after="main_logic")
+ ```
+
+ Args:
+ target (str): Cell ID or cell name to move.
+ before (str, optional): Place before this cell (ID or name).
+ Mutually exclusive with ``after``.
+ after (str, optional): Place after this cell (ID or name).
+ Mutually exclusive with ``before``.
+ """
+ self._require_entered()
+ if before is not None and after is not None:
+ raise ValueError("Cannot specify both 'before' and 'after'")
+ if before is None and after is None:
+ raise ValueError("Must specify either 'before' or 'after'")
+
+ cell_id = self._resolve_target(target)
+ before_id = (
+ self._resolve_target(before) if before is not None else None
+ )
+ after_id = self._resolve_target(after) if after is not None else None
+
+ self._ops.append(
+ _MoveOp(
+ cell_id=cell_id,
+ before=before_id,
+ after=after_id,
+ )
+ )
+
+ # ------------------------------------------------------------------
+ # Apply queued operations
+ # ------------------------------------------------------------------
+
+ def _dry_run_compile(self, ops: list[_Op]) -> None:
+ """Compile and graph-check every op before mutating real state.
+
+ For each op with code:
+ 1. ``compile_cell`` — validates syntax, extracts defs/refs.
+ 2. Temporarily register in the graph to detect multiply-defined
+ names and cycles.
+ 3. Always clean up so the graph is left unchanged.
+
+ Raises ``SyntaxError`` for invalid code or ``RuntimeError`` for
+ graph conflicts (multiply-defined names, cycles).
+ """
+ graph = self.graph
+ registered: list[CellId_t] = []
+ # For updates we must evict the old cell first; remember it
+ # so we can restore on cleanup.
+ evicted: dict[CellId_t, CellImpl] = {}
+
+ # Snapshot cell order before any mutations so we can restore it.
+ # The evict/re-register cycle appends cells to the end of the
+ # dict, which corrupts the ordering that _apply_ops relies on.
+ original_order = list(graph.cells.keys())
+
+ # Snapshot existing problems so we only flag *new* ones.
+ existing_multiply_defined = set(graph.get_multiply_defined())
+ existing_cycles = set(graph.cycles)
+
+ try:
+ for op in ops:
+ # For deletes, evict the cell so its defs don't conflict
+ # with later adds/updates that reuse the same names.
+ if isinstance(op, _DeleteOp):
+ cell_id = op.cell_id
+ if cell_id in graph.cells:
+ evicted[cell_id] = graph.cells[cell_id]
+ graph.delete_cell(cell_id)
+ continue
+
+ code: str | None = getattr(op, "code", None)
+ if code is None:
+ continue
+
+ cell_id = op.cell_id
+
+ # For updates, temporarily remove the existing cell so the
+ # new version can be registered in its place.
+ if isinstance(op, _UpdateOp) and cell_id in graph.cells:
+ evicted[cell_id] = graph.cells[cell_id]
+ graph.delete_cell(cell_id)
+
+ cell = compile_cell(code, cell_id=cell_id)
+ graph.register_cell(cell_id, cell)
+ registered.append(cell_id)
+
+ # Only error on problems *introduced* by these ops.
+ new_multiply_defined = (
+ set(graph.get_multiply_defined()) - existing_multiply_defined
+ )
+ new_cycles = set(graph.cycles) - existing_cycles
+
+ _check_false_hint = (
+ "\n\nTo skip validation, use: "
+ "async with cm.get_context(check=False) as ctx"
+ )
+ if new_multiply_defined:
+ raise RuntimeError(
+ "Multiply-defined names: "
+ f"{sorted(new_multiply_defined)}"
+ f"{_check_false_hint}"
+ )
+ if new_cycles:
+ raise RuntimeError(
+ f"Cycles detected: {new_cycles}{_check_false_hint}"
+ )
+ finally:
+ # Always clean up: remove dry-run cells, restore evicted ones.
+ for cid in registered:
+ if cid in graph.cells:
+ graph.delete_cell(cid)
+ for cid, old_cell in evicted.items():
+ graph.register_cell(cid, old_cell)
+
+ # Restore original cell ordering.
+ if evicted:
+ graph.topology.reorder_nodes(original_order)
+
+ async def _apply_ops(self, ops: list[_Op]) -> None:
+ """Validate, plan, format, and apply a batch of operations."""
+ existing_ids = list(self.graph.cells.keys())
+ plan = _build_plan(existing_ids, ops)
+
+ # Auto-format new/changed code.
+ plan = await self._format_plan(plan)
+
+ # Diff the plan against the current graph.
+ existing_id_set = set(self.graph.cells.keys())
+ existing_code = {
+ cid: self.graph.cells[cid].code for cid in existing_id_set
+ }
+ plan_ids = {e.cell_id for e in plan}
+
+ # Classify each entry.
+ code_entries: list[_PlanEntry] = [] # new or changed code
+ config_entries: list[_PlanEntry] = [] # config-only changes
+ draft_ids: set[CellId_t] = set()
+
+ for entry in plan:
+ is_new = entry.cell_id not in existing_id_set
+ code_changed = (
+ entry.code is not None
+ and entry.code != existing_code.get(entry.cell_id)
+ )
+ if is_new or code_changed:
+ code_entries.append(entry)
+ if entry.draft:
+ draft_ids.add(entry.cell_id)
+ elif entry.config is not None:
+ config_entries.append(entry)
+
+ # Resolve configs before mutate_graph (which may delete metadata).
+ resolved_configs: dict[CellId_t, CellConfig] = {}
+ for entry in code_entries:
+ assert entry.code is not None
+ if entry.cell_id not in existing_id_set:
+ resolved_configs[entry.cell_id] = entry.config or CellConfig(
+ hide_code=True
+ )
+ else:
+ existing_meta = self._kernel.cell_metadata.get(entry.cell_id)
+ resolved_configs[entry.cell_id] = entry.config or (
+ existing_meta.config if existing_meta else CellConfig()
+ )
+
+ # Let mutate_graph handle all graph mutations: it properly
+ # cleans up globals, UI elements, and lifecycle hooks for
+ # deleted/replaced cells via _delete_cell / _deactivate_cell.
+ execution_requests: list[ExecuteCellCommand] = []
+ for e in code_entries:
+ assert e.code is not None
+ execution_requests.append(
+ ExecuteCellCommand(cell_id=e.cell_id, code=e.code)
+ )
+ deletion_requests = [
+ DeleteCellCommand(cell_id=cid)
+ for cid in existing_id_set - plan_ids
+ ]
+ cells_to_run = self._kernel.mutate_graph(
+ execution_requests, deletion_requests
+ )
+
+ # Restore cell ordering in the graph to match the plan.
+ # mutate_graph may reorder cells: _deactivate_cell removes a cell
+ # from the dict and _try_registering_cell re-adds it at the end.
+ target_order = [e.cell_id for e in plan]
+ self.graph.topology.reorder_nodes(target_order)
+
+ # Apply configs to newly registered cells.
+ for cell_id, cfg in resolved_configs.items():
+ if cell_id in self.graph.cells:
+ self.graph.cells[cell_id].configure(cfg.asdict())
+ self._kernel.cell_metadata[cell_id] = CellMetadata(config=cfg)
+
+ # Persist names from ops into the module-level store.
+ for op in ops:
+ op_name = getattr(op, "name", None)
+ if op_name is not None:
+ target_id = getattr(op, "new_cell_id", None) or op.cell_id
+ _cell_names[target_id] = op_name
+ # Clean up stale entry when cell_id was migrated.
+ if (
+ getattr(op, "new_cell_id", None) is not None
+ and op.cell_id in _cell_names
+ ):
+ del _cell_names[op.cell_id]
+
+ # Apply config-only changes.
+ for entry in config_entries:
+ await self.execute_command(
+ UpdateCellConfigCommand(
+ configs={entry.cell_id: entry.config.asdict()} # type: ignore[union-attr]
+ )
+ )
+
+ # Notify frontend of code changes.
+ target_order = [e.cell_id for e in plan]
+
+ by_stale: dict[bool, list[_PlanEntry]] = {}
+ for entry in code_entries:
+ by_stale.setdefault(entry.draft, []).append(entry)
+
+ for is_stale, entries in by_stale.items():
+ names = [_cell_names.get(e.cell_id, "") for e in entries]
+ kwargs: dict[str, Any] = {}
+ if any(names):
+ kwargs["names"] = names
+ self.notify(
+ UpdateCellCodesNotification(
+ cell_ids=[e.cell_id for e in entries],
+ codes=[e.code for e in entries], # type: ignore[misc]
+ code_is_stale=is_stale,
+ configs=[resolved_configs[e.cell_id] for e in entries],
+ **kwargs,
+ )
+ )
+
+ # For name-only updates (no code change), send a notification
+ # with existing code so the frontend picks up the new name.
+ name_only = {
+ cid: n
+ for cid, n in _cell_names.items()
+ if cid not in {e.cell_id for e in code_entries}
+ and cid in self.graph.cells
+ and any(
+ getattr(op, "name", None) is not None and op.cell_id == cid
+ for op in ops
+ )
+ }
+ if name_only:
+ self.notify(
+ UpdateCellCodesNotification(
+ cell_ids=list(name_only.keys()),
+ codes=[self.graph.cells[cid].code for cid in name_only],
+ code_is_stale=False,
+ names=list(name_only.values()),
+ )
+ )
+
+ self.notify(UpdateCellIdsNotification(cell_ids=target_order))
+
+ # Run cells, excluding drafts.
+ cells_to_run -= draft_ids
+ if cells_to_run:
+ await self._kernel._run_cells(cells_to_run)
+
+ # ------------------------------------------------------------------
+ # Formatting helpers
+ # ------------------------------------------------------------------
+
+ async def _format_plan(self, plan: list[_PlanEntry]) -> list[_PlanEntry]:
+ """Format new/changed code in the plan with the default formatter."""
+ existing_code = {
+ cid: self.graph.cells[cid].code for cid in self.graph.cells
+ }
+
+ to_format: dict[CellId_t, str] = {}
+ for entry in plan:
+ if entry.code is not None and entry.code != existing_code.get(
+ entry.cell_id
+ ):
+ to_format[entry.cell_id] = entry.code
+
+ if not to_format:
+ return plan
+
+ try:
+ line_length = self._kernel.user_config["formatting"]["line_length"]
+ formatter = DefaultFormatter(line_length=line_length)
+ formatted = await formatter.format(
+ to_format,
+ stdin_filename=self._kernel.app_metadata.filename,
+ )
+ except Exception:
+ LOGGER.debug("Auto-format skipped: no formatter available")
+ return plan
+
+ for entry in plan:
+ if entry.cell_id in formatted:
+ entry.code = formatted[entry.cell_id]
+ return plan
+
+ # ------------------------------------------------------------------
+ # UI elements
+ # ------------------------------------------------------------------
+
+ def set_ui_value(self, element: Any, value: Any) -> None:
+ """Queue a UI element value update.
+
+ Triggers reactive re-execution the same way a user interaction
+ would. Updates are flushed as a single batch on context exit.
+
+ Examples:
+ ```python
+ slider = ctx.globals["my_slider"]
+ ctx.set_ui_value(slider, 42)
+
+ dropdown = ctx.globals["color_picker"]
+ ctx.set_ui_value(dropdown, "red")
+ ```
+
+ Args:
+ element: A marimo UI element (e.g. ``mo.ui.slider``).
+ value: The new value, matching the type the element expects.
+ """
+ self._require_entered()
+ self._ui_updates.append((UIElementId(element._id), value))
+
+ # ------------------------------------------------------------------
+ # Package management
+ # ------------------------------------------------------------------
+
+ def install_packages(self, *packages: str) -> None:
+ """Queue packages for installation on context exit.
+
+ Installed before cell ops, so newly added cells can import them.
+
+ Examples:
+ ```python
+ ctx.install_packages("pandas")
+ ctx.install_packages("polars>=0.20", "numpy==1.26")
+ ```
+
+ Args:
+ *packages (str): Pip-style package specifiers.
+ """
+ self._require_entered()
+ self._packages_to_install.extend(packages)
+
+ # ------------------------------------------------------------------
+ # Low-level primitives
+ # ------------------------------------------------------------------
+
+ async def execute_command(self, command: CommandMessage) -> None:
+ """Execute a command inline and await completion."""
+ try:
+ await self._kernel.handle_message(command)
+ except Exception:
+ LOGGER.exception(
+ "Failed to execute command: %s",
+ type(command).__name__,
+ )
+
+ def enqueue_command(self, command: CommandMessage) -> None:
+ """Fire-and-forget: runs after the current cell finishes."""
+ try:
+ self._kernel.enqueue_control_request(command)
+ except Exception:
+ LOGGER.exception(
+ "Failed to enqueue command: %s",
+ type(command).__name__,
+ )
+
+ def notify(self, notification: Notification) -> None:
+ """Send a notification to the frontend."""
+ broadcast_notification(notification, stream=self._kernel.stream) # type: ignore[arg-type]
diff --git a/marimo/_code_mode/_plan.py b/marimo/_code_mode/_plan.py
new file mode 100644
index 0000000000..1836d471dd
--- /dev/null
+++ b/marimo/_code_mode/_plan.py
@@ -0,0 +1,187 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""Internal operation types, plan builder, and validation for code mode."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from marimo._ast.cell import CellConfig
+from marimo._types.ids import CellId_t
+
+# ------------------------------------------------------------------
+# Operation types (queued by mutation methods)
+# ------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class _AddOp:
+ cell_id: CellId_t
+ code: str
+ config: CellConfig
+ draft: bool = False
+ before: CellId_t | None = None
+ after: CellId_t | None = None
+ name: str | None = None
+
+
+@dataclass(frozen=True)
+class _UpdateOp:
+ cell_id: CellId_t
+ code: str | None = None
+ config: CellConfig | None = None
+ draft: bool = False
+ name: str | None = None
+ new_cell_id: CellId_t | None = None
+
+
+@dataclass(frozen=True)
+class _DeleteOp:
+ cell_id: CellId_t
+
+
+@dataclass(frozen=True)
+class _MoveOp:
+ cell_id: CellId_t
+ before: CellId_t | None = None
+ after: CellId_t | None = None
+
+
+_Op = _AddOp | _UpdateOp | _DeleteOp | _MoveOp
+
+
+# ------------------------------------------------------------------
+# Plan entry
+# ------------------------------------------------------------------
+
+
+@dataclass
+class _PlanEntry:
+ cell_id: CellId_t
+ code: str | None = None
+ config: CellConfig | None = None
+ draft: bool = False
+ name: str | None = None
+
+
+# ------------------------------------------------------------------
+# Plan builder
+# ------------------------------------------------------------------
+
+
+def _build_plan(
+ existing_cell_ids: list[CellId_t],
+ ops: list[_Op],
+) -> list[_PlanEntry]:
+ """Reduce a list of queued operations into a flat plan.
+
+ Pure function. The returned plan describes the target cell list
+ after all operations are applied sequentially.
+ """
+ plan: list[_PlanEntry] = [
+ _PlanEntry(cell_id=cid) for cid in existing_cell_ids
+ ]
+
+ def _find_index(cell_id: CellId_t) -> int:
+ for i, entry in enumerate(plan):
+ if entry.cell_id == cell_id:
+ return i
+ raise KeyError(f"Cell {cell_id!r} not found in plan")
+
+ for op in ops:
+ if isinstance(op, _AddOp):
+ entry = _PlanEntry(
+ cell_id=op.cell_id,
+ code=op.code,
+ config=op.config,
+ draft=op.draft,
+ name=op.name,
+ )
+ if op.after is not None:
+ idx = _find_index(op.after)
+ plan.insert(idx + 1, entry)
+ elif op.before is not None:
+ idx = _find_index(op.before)
+ plan.insert(idx, entry)
+ else:
+ # Default: append at end
+ plan.append(entry)
+
+ elif isinstance(op, _UpdateOp):
+ idx = _find_index(op.cell_id)
+ entry = plan[idx]
+ if op.new_cell_id is not None:
+ entry.cell_id = op.new_cell_id
+ if op.code is not None:
+ entry.code = op.code
+ if op.config is not None:
+ entry.config = op.config
+ if op.name is not None:
+ entry.name = op.name
+ entry.draft = op.draft
+
+ elif isinstance(op, _DeleteOp):
+ idx = _find_index(op.cell_id)
+ del plan[idx]
+
+ elif isinstance(op, _MoveOp):
+ idx = _find_index(op.cell_id)
+ entry = plan.pop(idx)
+ if op.after is not None:
+ target_idx = _find_index(op.after)
+ plan.insert(target_idx + 1, entry)
+ elif op.before is not None:
+ target_idx = _find_index(op.before)
+ plan.insert(target_idx, entry)
+ else:
+ raise ValueError("move_cell requires before or after")
+
+ else:
+ raise TypeError(f"Unknown op type: {type(op)!r}")
+
+ return plan
+
+
+# ------------------------------------------------------------------
+# Validation
+# ------------------------------------------------------------------
+
+
+def _validate_ops(ops: list[_Op]) -> None:
+ """Check for conflicting operations. Raises ``ValueError`` on conflict."""
+ deleted: set[CellId_t] = set()
+ updated: set[CellId_t] = set()
+ moved: set[CellId_t] = set()
+
+ for op in ops:
+ if isinstance(op, _DeleteOp):
+ if op.cell_id in updated:
+ raise ValueError(
+ f"Cannot delete cell {op.cell_id!r} that is also "
+ f"updated in the same batch"
+ )
+ if op.cell_id in moved:
+ raise ValueError(
+ f"Cannot delete cell {op.cell_id!r} that is also "
+ f"moved in the same batch"
+ )
+ if op.cell_id in deleted:
+ raise ValueError(
+ f"Cell {op.cell_id!r} is deleted more than once"
+ )
+ deleted.add(op.cell_id)
+
+ elif isinstance(op, _UpdateOp):
+ if op.cell_id in deleted:
+ raise ValueError(
+ f"Cannot update cell {op.cell_id!r} that is also "
+ f"deleted in the same batch"
+ )
+ updated.add(op.cell_id)
+
+ elif isinstance(op, _MoveOp):
+ if op.cell_id in deleted:
+ raise ValueError(
+ f"Cannot move cell {op.cell_id!r} that is also "
+ f"deleted in the same batch"
+ )
+ moved.add(op.cell_id)
diff --git a/marimo/_messaging/context.py b/marimo/_messaging/context.py
index ccac980adf..0fbc78ce3d 100644
--- a/marimo/_messaging/context.py
+++ b/marimo/_messaging/context.py
@@ -44,3 +44,17 @@ class http_request_context:
def __exit__(self, *_: Any) -> None:
HTTP_REQUEST_CTX.reset(self.token)
+
+
+def is_headless_request() -> bool:
+ """True when the current request comes from a non-browser client.
+
+ Returns False (not headless) when there is no request context
+ (e.g. websocket/browser) or when the Accept header includes
+ text/html. Returns True for programmatic clients like the
+ ``/execute`` SSE endpoint.
+ """
+ request = HTTP_REQUEST_CTX.get(None)
+ if request is None:
+ return False
+ return "text/html" not in request.headers.get("accept", "")
diff --git a/marimo/_messaging/streams.py b/marimo/_messaging/streams.py
index b029c4c2d3..ba500da41c 100644
--- a/marimo/_messaging/streams.py
+++ b/marimo/_messaging/streams.py
@@ -234,6 +234,11 @@ class ThreadSafeStdout(Stdout):
):
self._stream = stream
self._original_fd = sys.stdout.fileno()
+ # Expose the underlying binary buffer so that code writing to
+ # sys.stdout.buffer (e.g. package installation logging) keeps working.
+ self.buffer: io.BufferedIOBase | None = getattr(
+ sys.stdout, "buffer", None
+ )
self._watcher: Watcher | _NoOpWatcher = (
Watcher(self) if forward_os_streams else _NOOP_WATCHER
)
@@ -304,6 +309,11 @@ class ThreadSafeStderr(Stderr):
):
self._stream = stream
self._original_fd = sys.stderr.fileno()
+ # Expose the underlying binary buffer so that code writing to
+ # sys.stderr.buffer keeps working.
+ self.buffer: io.BufferedIOBase | None = getattr(
+ sys.stderr, "buffer", None
+ )
self._watcher: Watcher | _NoOpWatcher = (
Watcher(self) if forward_os_streams else _NOOP_WATCHER
)
diff --git a/marimo/_messaging/tracebacks.py b/marimo/_messaging/tracebacks.py
index 72f34a549d..bad201b5e6 100644
--- a/marimo/_messaging/tracebacks.py
+++ b/marimo/_messaging/tracebacks.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import sys
-from marimo._messaging.context import HTTP_REQUEST_CTX
+from marimo._messaging.context import is_headless_request
from marimo._messaging.types import Stderr
@@ -22,20 +22,8 @@ def _highlight_traceback(traceback: str) -> str:
return f'<span class="codehilite">{body}</span>'
-def _accepts_html() -> bool:
- """Check if the current request context accepts HTML responses.
-
- Returns True when there is no request context (e.g. websocket/browser)
- or when the Accept header explicitly includes text/html.
- """
- request = HTTP_REQUEST_CTX.get(None)
- if request is None:
- return True
- return "text/html" in request.headers.get("accept", "")
-
-
def write_traceback(traceback: str) -> None:
- if isinstance(sys.stderr, Stderr) and _accepts_html():
+ if isinstance(sys.stderr, Stderr) and not is_headless_request():
# Strip marimo's internal executor.py frame and highlight for the UI
trimmed = _trim_traceback(traceback)
sys.stderr._write_with_mimetype(
diff --git a/marimo/_runtime/dataflow/topology.py b/marimo/_runtime/dataflow/topology.py
index 1aa7862484..1d333dad33 100644
--- a/marimo/_runtime/dataflow/topology.py
+++ b/marimo/_runtime/dataflow/topology.py
@@ -114,6 +114,15 @@ class MutableGraphTopology(GraphTopology):
del self._children[cell_id]
del self._parents[cell_id]
+ def reorder_nodes(self, ordered_ids: list[CellId_t]) -> None:
+ """Reorder the internal cells dict to match the given id order.
+
+ Ids not present in the graph are silently skipped.
+ """
+ self._cells = {
+ cid: self._cells[cid] for cid in ordered_ids if cid in self._cells
+ }
+
def add_edge(self, parent: CellId_t, child: CellId_t) -> None:
"""Add an edge from parent to child."""
self.children[parent].add(child)
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index d03efacb49..bdccada54f 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -45,7 +45,11 @@ from marimo._dependencies.errors import ManyModulesNotFoundError
from marimo._entrypoints.registry import EntryPointRegistry
from marimo._lint.validate_graph import check_for_errors
from marimo._messaging.cell_output import CellChannel
-from marimo._messaging.context import http_request_context, run_id_context
+from marimo._messaging.context import (
+ http_request_context,
+ is_headless_request,
+ run_id_context,
+)
from marimo._messaging.errors import (
Error,
ImportStarError as MarimoImportStarError,
@@ -1745,6 +1749,13 @@ class Kernel:
await runner.run_all()
+ # Flush any state updates queued during scratchpad execution
+ # (e.g., from widget .observe() callbacks that call mo.state
+ # setters). Without this, state updates are queued but never
+ # processed, so downstream cells don't re-run.
+ if self.state_updates:
+ await self._run_cells(set())
+
@kernel_tracer.start_as_current_span("run_stale_cells")
async def run_stale_cells(self) -> None:
cells_to_run: set[CellId_t] = set()
@@ -3105,6 +3116,9 @@ class PackagesCallbacks:
)
)
else:
+ if is_headless_request():
+ return
+
broadcast_notification(
MissingPackageAlertNotification(
packages=packages,
@@ -3573,7 +3587,13 @@ def launch_kernel(
continue
if request is not None:
- await kernel.handle_message(request)
+ try:
+ await kernel.handle_message(request)
+ except Exception:
+ LOGGER.exception(
+ "Failed to handle control request: %s",
+ type(request).__name__,
+ )
# The control loop is asynchronous only because we allow user code to use
# top-level await; nothing else is awaited. Don't introduce async
diff --git a/marimo/_server/api/endpoints/execution.py b/marimo/_server/api/endpoints/execution.py
index d4915b2f71..461b0733d3 100644
--- a/marimo/_server/api/endpoints/execution.py
+++ b/marimo/_server/api/endpoints/execution.py
@@ -273,6 +273,14 @@ async def execute_code(
body = await parse_request(request, cls=ExecuteScratchpadRequest)
session = app_state.require_current_session()
+ # Auto-instantiate so headless /api/execute works without a prior
+ # /api/instantiate call. The kernel no-ops if already instantiated,
+ # and queue ordering guarantees it completes before the scratchpad runs.
+ session.instantiate(
+ InstantiateNotebookRequest(object_ids=[], values=[], auto_run=True),
+ http_request=HTTPRequest.from_request(request),
+ )
+
async def sse_generator() -> AsyncGenerator[str, None]:
listener = ScratchCellListener()
with session.scoped(listener):
diff --git a/marimo/_server/scratchpad.py b/marimo/_server/scratchpad.py
index 5dfe5400a9..c3104130cc 100644
--- a/marimo/_server/scratchpad.py
+++ b/marimo/_server/scratchpad.py
@@ -208,6 +208,14 @@ def build_done_event(session: Session) -> str:
)
if hasattr(err, "exception_type"):
error_data["exception_type"] = err.exception_type
+ if err.exception_type in (
+ "ModuleNotFoundError",
+ "ImportError",
+ ):
+ error_data["msg"] += (
+ "\n\nHint: Use ctx.install_packages(...)"
+ " to install missing packages."
+ )
return _format_sse("done", DoneError(success=False, error=error_data))
# Success case
diff --git a/marimo/_session/session.py b/marimo/_session/session.py
index 3c3db1b926..d203d12378 100644
--- a/marimo/_session/session.py
+++ b/marimo/_session/session.py
@@ -244,7 +244,8 @@ class SessionImpl(Session):
@contextlib.contextmanager
def scoped(
- self, extension: SessionExtension
+ self,
+ extension: SessionExtension,
) -> Iterator[SessionExtension]:
"""Attach an extension for the duration of the context."""
self.extensions.append(extension)
diff --git a/marimo/_session/types.py b/marimo/_session/types.py
index f4ab6a1449..b4ea4a6e7a 100644
--- a/marimo/_session/types.py
+++ b/marimo/_session/types.py
@@ -187,7 +187,8 @@ class Session(Protocol):
@contextlib.contextmanager
def scoped(
- self, extension: SessionExtension
+ self,
+ extension: SessionExtension,
) -> Iterator[SessionExtension]:
"""Attach an extension for the duration of the context."""
...
diff --git a/tests/_code_mode/__init__.py b/tests/_code_mode/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/_code_mode/test_cells_view.py b/tests/_code_mode/test_cells_view.py
new file mode 100644
index 0000000000..790908f4ba
--- /dev/null
+++ b/tests/_code_mode/test_cells_view.py
@@ -0,0 +1,127 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import pytest
+
+from marimo._code_mode._context import AsyncCodeModeContext, NotebookCellData
+from marimo._runtime.commands import ExecuteCellCommand
+from marimo._runtime.runtime import Kernel
+
+
+class TestCellsViewIndex:
+ """Test integer indexing (positive and negative)."""
+
+ async def test_positive_index(self, k: Kernel) -> None:
+ await k.run(
+ [
+ ExecuteCellCommand(cell_id="a", code="x = 1"),
+ ExecuteCellCommand(cell_id="b", code="y = 2"),
+ ExecuteCellCommand(cell_id="c", code="z = 3"),
+ ]
+ )
+ ctx = AsyncCodeModeContext(k)
+
+ assert ctx.cells[0].cell_id == "a"
+ assert ctx.cells[1].cell_id == "b"
+ assert ctx.cells[2].cell_id == "c"
+
+ async def test_negative_index(self, k: Kernel) -> None:
+ await k.run(
+ [
+ ExecuteCellCommand(cell_id="a", code="x = 1"),
+ ExecuteCellCommand(cell_id="b", code="y = 2"),
+ ExecuteCellCommand(cell_id="c", code="z = 3"),
+ ]
+ )
+ ctx = AsyncCodeModeContext(k)
+
+ assert ctx.cells[-1].cell_id == "c"
+ assert ctx.cells[-2].cell_id == "b"
+ assert ctx.cells[-3].cell_id == "a"
+
+ async def test_index_out_of_range(self, k: Kernel) -> None:
+ await k.run([ExecuteCellCommand(cell_id="a", code="x = 1")])
+ ctx = AsyncCodeModeContext(k)
+
+ with pytest.raises(IndexError):
+ ctx.cells[5]
+
+ with pytest.raises(IndexError):
+ ctx.cells[-5]
+
+
+class TestCellsViewCellId:
+ """Test lookup by cell ID string."""
+
+ async def test_lookup_by_cell_id(self, k: Kernel) -> None:
+ await k.run(
+ [
+ ExecuteCellCommand(cell_id="abc", code="x = 1"),
+ ExecuteCellCommand(cell_id="def", code="y = 2"),
+ ]
+ )
+ ctx = AsyncCodeModeContext(k)
+
+ cell = ctx.cells["def"]
+ assert cell.cell_id == "def"
+ assert cell.code == "y = 2"
+
+ async def test_lookup_by_cell_id_not_found(self, k: Kernel) -> None:
+ await k.run([ExecuteCellCommand(cell_id="abc", code="x = 1")])
+ ctx = AsyncCodeModeContext(k)
+
+ with pytest.raises(KeyError):
+ ctx.cells["nonexistent"]
+
+
+class TestCellsViewCellName:
+ """Test lookup by cell name."""
+
+ async def test_name_lookup_without_cell_manager(self, k: Kernel) -> None:
+ await k.run([ExecuteCellCommand(cell_id="a", code="x = 1")])
+ ctx = AsyncCodeModeContext(k)
+
+ # No cell manager → name lookup fails
+ with pytest.raises(KeyError):
+ ctx.cells["my_cell"]
+
+
+class TestCellsViewNameField:
+ """Test that the name field is populated on NotebookCellData."""
+
+ async def test_name_is_none_without_cell_manager(self, k: Kernel) -> None:
+ await k.run([ExecuteCellCommand(cell_id="a", code="x = 1")])
+ ctx = AsyncCodeModeContext(k)
+
+ cell = ctx.cells[0]
+ assert cell.name is None
+
+ async def test_name_field_on_constructed_cell(self) -> None:
+ cell = NotebookCellData(code="x = 1", name="my_cell")
+ assert cell.name == "my_cell"
+
+
+class TestCellsViewIteration:
+ """Test iteration and len."""
+
+ async def test_len(self, k: Kernel) -> None:
+ await k.run(
+ [
+ ExecuteCellCommand(cell_id="a", code="x = 1"),
+ ExecuteCellCommand(cell_id="b", code="y = 2"),
+ ]
+ )
+ ctx = AsyncCodeModeContext(k)
+ assert len(ctx.cells) == 2
+
+ async def test_iteration(self, k: Kernel) -> None:
+ await k.run(
+ [
+ ExecuteCellCommand(cell_id="a", code="x = 1"),
+ ExecuteCellCommand(cell_id="b", code="y = 2"),
+ ]
+ )
+ ctx = AsyncCodeModeContext(k)
+
+ ids = [cell.cell_id for cell in ctx.cells]
+ assert ids == ["a", "b"]
diff --git a/tests/_code_mode/test_context.py b/tests/_code_mode/test_context.py
new file mode 100644
index 0000000000..5c14a2892d
--- /dev/null
+++ b/tests/_code_mode/test_context.py
@@ -0,0 +1,496 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from unittest.mock import AsyncMock, patch
+
+import msgspec
+from inline_snapshot import snapshot
+
+from marimo._code_mode._context import AsyncCodeModeContext
+from marimo._messaging.notification import (
+ UpdateCellCodesNotification,
+ UpdateCellIdsNotification,
+)
+from marimo._runtime.commands import ExecuteCellCommand
+from marimo._runtime.runtime import Kernel
+
+
+def _code_notifs(k: Kernel) -> list[UpdateCellCodesNotification]:
+ return [
+ op
+ for op in k.stream.operations
+ if isinstance(op, UpdateCellCodesNotification)
+ ]
+
+
+def _ids_notifs(k: Kernel) -> list[UpdateCellIdsNotification]:
+ return [
+ op
+ for op in k.stream.operations
+ if isinstance(op, UpdateCellIdsNotification)
+ ]
+
+
+def _clear_messages(k: Kernel) -> None:
+ k.stream.messages.clear()
+
+
+def _graph_codes(k: Kernel) -> dict[str, str]:
+ return {str(cid): cell.code for cid, cell in k.graph.cells.items()}
+
+
+class TestAddCell:
+ async def test_add_into_empty(self, k: Kernel) -> None:
+ ctx = AsyncCodeModeContext(k)
+ _clear_messages(k)
+
+ async with ctx as nb:
+ nb.create_cell("x = 1")
+
+ assert len(k.graph.cells) == 1
+ cell = list(k.graph.cells.values())[0]
+ assert cell.code == "x = 1"
+ assert k.globals["x"] == 1
+
+ code_notifs = msgspec.to_builtins(_code_notifs(k))
+ assert len(code_notifs) == 1
+ assert code_notifs[0]["codes"] == ["x = 1"]
+ assert code_notifs[0]["code_is_stale"] is False
+
+ ids_notifs = msgspec.to_builtins(_ids_notifs(k))
+ assert len(ids_notifs) == 1
+ assert len(ids_notifs[0]["cell_ids"]) == 1
+
+ async def test_add_appends_by_default(self, k: Kernel) -> None:
+ await k.run(
+ [
+ ExecuteCellCommand(cell_id="0", code="a = 10"),
+ ExecuteCellCommand(cell_id="1", code="b = 20"),
+ ]
+ )
+ ctx = AsyncCodeModeContext(k)
+ _clear_messages(k)
+
+ async with ctx as nb:
+ nb.create_cell("c = a + b")
+
+ assert len(k.graph.cells) == 3
+ assert k.globals["c"] == 30
+
+ # New cell should be last in the ordering notification.
+ ids_notifs = _ids_notifs(k)
+ assert len(ids_notifs) == 1
+ cell_ids = ids_notifs[0].cell_ids
+ assert cell_ids[:2] == ["0", "1"]
+ assert len(cell_ids) == 3
+
+ async def test_add_with_after(self, k: Kernel) -> None:
+ await k.run(
+ [
+ ExecuteCellCommand(cell_id="0", code="a = 10"),
+ ExecuteCellCommand(cell_id="1", code="b = 20"),
+ ]
+ )
+ ctx = AsyncCodeModeContext(k)
+ _clear_messages(k)
+
+ async with ctx as nb:
+ nb.create_cell("c = a + b", after="0")
+
+ ids_notifs = _ids_notifs(k)
+ cell_ids = ids_notifs[0].cell_ids
+ assert cell_ids[0] == "0"
+ # New cell should be after "0", before "1".
+ assert cell_ids[2] == "1"
+
+ async def test_add_draft_does_not_execute(self, k: Kernel) -> None:
+ ctx = AsyncCodeModeContext(k)
+ _clear_messages(k)
+
+ async with ctx as nb:
+ nb.create_cell("x = 999", draft=True)
+
+ assert len(k.graph.cells) == 1
+ assert "x" not in k.globals
+
+ code_notifs = msgspec.to_builtins(_code_notifs(k))
+ assert len(code_notifs) == 1
+ assert code_notifs[0]["codes"] == ["x = 999"]
+ assert code_notifs[0]["code_is_stale"] is True
+
+ async def test_add_returns_cell_id(self, k: Kernel) -> None:
+ ctx = AsyncCodeModeContext(k)
+
+ async with ctx as nb:
+ cid = nb.create_cell("x = 1")
+ assert isinstance(cid, str)
+ assert len(cid) > 0
+
+ async def test_add_chain_after(self, k: Kernel) -> None:
+ """Can reference a just-added cell's ID in a subsequent add."""
+ ctx = AsyncCodeModeContext(k)
+
+ async with ctx as nb:
+ cid1 = nb.create_cell("x = 1")
+ nb.create_cell("y = 2", after=cid1)
+
+ assert k.globals["x"] == 1
+ assert k.globals["y"] == 2
+
+
+class TestDeleteCell:
+ async def test_delete_cell(self, k: Kernel) -> None:
+ await k.run(
+ [
+ ExecuteCellCommand(cell_id="0", code="a = 1"),
+ ExecuteCellCommand(cell_id="1", code="b = 2"),
+ ExecuteCellCommand(cell_id="2", code="c = 3"),
+ ]
+ )
+ assert len(k.graph.cells) == 3
+
+ ctx = AsyncCodeModeContext(k)
+ _clear_messages(k)
+
+ async with ctx as nb:
+ nb.delete_cell("1")
+
+ assert _graph_codes(k) == snapshot({"0": "a = 1", "2": "c = 3"})
+
+ assert msgspec.to_builtins(_ids_notifs(k)) == snapshot(
+ [{"op": "update-cell-ids", "cell_ids": ["0", "2"]}]
+ )
+
+ async def test_delete_cleans_globals(self, k: Kernel) -> None:
+ """Deleting a cell removes its defs from kernel globals."""
+ await k.run(
+ [
+ ExecuteCellCommand(cell_id="0", code="a = 1"),
+ ExecuteCellCommand(cell_id="1", code="b = 2"),
+ ]
+ )
+ assert k.globals["a"] == 1
+ assert k.globals["b"] == 2
+
+ ctx = AsyncCodeModeContext(k)
+ async with ctx as nb:
+ nb.delete_cell("1")
+
+ assert k.globals["a"] == 1
+ assert "b" not in k.globals
+
+ async def test_delete_multiple(self, k: Kernel) -> None:
+ await k.run(
+ [
+ ExecuteCellCommand(cell_id="0", code="a = 1"),
+ ExecuteCellCommand(cell_id="1", code="b = 2"),
+ ExecuteCellCommand(cell_id="2", code="c = 3"),
+ ]
+ )
+ ctx = AsyncCodeModeContext(k)
+ _clear_messages(k)
+
+ async with ctx as nb:
+ nb.delete_cell("0")
+ nb.delete_cell("2")
+
+ assert _graph_codes(k) == snapshot({"1": "b = 2"})
+
+
+class TestUpdateCell:
+ async def test_update_code(self, k: Kernel) -> None:
+ await k.run([ExecuteCellCommand(cell_id="0", code="x = 1")])
+ assert k.globals["x"] == 1
+
+ ctx = AsyncCodeModeContext(k)
+ _clear_messages(k)
+
+ async with ctx as nb:
+ nb.edit_cell("0", code="x = 42")
+
+ assert k.globals["x"] == 42
+ assert _graph_codes(k) == snapshot({"0": "x = 42"})
+
+ assert msgspec.to_builtins(_code_notifs(k)) == snapshot(
+ [
+ {
+ "op": "update-cell-codes",
+ "cell_ids": ["0"],
+ "codes": ["x = 42"],
+ "code_is_stale": False,
+ "names": [],
+ "configs": [
+ {
+ "column": None,
+ "disabled": False,
+ "hide_code": False,
+ }
+ ],
+ }
+ ]
+ )
+
+ async def test_update_cleans_stale_globals(self, k: Kernel) -> None:
+ """Updating code removes old defs that are no longer defined."""
+ await k.run([ExecuteCellCommand(cell_id="0", code="x = 1\ny = 2")])
+ assert k.globals["x"] == 1
+ assert k.globals["y"] == 2
+
+ ctx = AsyncCodeModeContext(k)
+ async with ctx as nb:
+ nb.edit_cell("0", code="x = 42")
+
+ assert k.globals["x"] == 42
+ assert "y" not in k.globals
+
+ async def test_update_preserves_config(self, k: Kernel) -> None:
+ """Updating only code preserves the cell's existing config."""
+ await k.run([ExecuteCellCommand(cell_id="0", code="x = 1")])
+
+ # Set hide_code=True on the cell.
+ ctx = AsyncCodeModeContext(k)
+ async with ctx as nb:
+ nb.edit_cell("0", hide_code=True)
+
+ assert k.cell_metadata["0"].config.hide_code is True
+
+ # Update code without touching config — hide_code should stick.
+ ctx = AsyncCodeModeContext(k)
+ async with ctx as nb:
+ nb.edit_cell("0", code="x = 42")
+
+ assert k.globals["x"] == 42
+ assert k.cell_metadata["0"].config.hide_code is True
+
+ async def test_update_config_only(self, k: Kernel) -> None:
+ await k.run([ExecuteCellCommand(cell_id="0", code="x = 1")])
+
+ ctx = AsyncCodeModeContext(k)
+ _clear_messages(k)
+
+ async with ctx as nb:
+ nb.edit_cell("0", hide_code=True)
+
+ assert k.globals["x"] == 1
+ assert _graph_codes(k) == snapshot({"0": "x = 1"})
+ assert msgspec.to_builtins(_code_notifs(k)) == snapshot([])
+
+
+class TestCombined:
+ async def test_delete_and_add(self, k: Kernel) -> None:
+ await k.run(
+ [
+ ExecuteCellCommand(cell_id="0", code="a = 1"),
+ ExecuteCellCommand(cell_id="1", code="b = 2"),
+ ExecuteCellCommand(cell_id="2", code="c = 3"),
+ ]
+ )
+
+ ctx = AsyncCodeModeContext(k)
+ _clear_messages(k)
+
+ async with ctx as nb:
+ nb.delete_cell("1")
+ nb.create_cell("d = a + c", after="0")
+
+ assert k.globals["d"] == 4
+ codes = _graph_codes(k)
+ assert "1" not in codes
+
+ async def test_delete_and_add_same_defs(self, k: Kernel) -> None:
+ """Delete a cell and add a replacement defining the same names."""
+ await k.run(
+ [
+ ExecuteCellCommand(cell_id="0", code="a = 1"),
+ ExecuteCellCommand(cell_id="1", code="b = a + 1"),
+ ]
+ )
+ assert k.globals["b"] == 2
+
+ ctx = AsyncCodeModeContext(k)
+ _clear_messages(k)
+
+ # Delete cell "1" and create a new cell that also defines "b".
+ # This must not raise a multiply-defined error.
+ async with ctx as nb:
+ nb.delete_cell("1")
+ nb.create_cell("b = a + 100")
+
+ assert k.globals["b"] == 101
+ assert "1" not in _graph_codes(k)
+
+ async def test_noop_batch(self, k: Kernel) -> None:
+ """An empty context manager does nothing."""
+ await k.run([ExecuteCellCommand(cell_id="0", code="x = 1")])
+ ctx = AsyncCodeModeContext(k)
+ _clear_messages(k)
+
+ async with ctx as nb: # noqa: B018
+ pass
+
+ assert _graph_codes(k) == snapshot({"0": "x = 1"})
+
+ async def test_exception_discards_ops(self, k: Kernel) -> None:
+ """If an exception occurs, queued ops are discarded."""
+ await k.run([ExecuteCellCommand(cell_id="0", code="x = 1")])
+ ctx = AsyncCodeModeContext(k)
+
+ try:
+ async with ctx as nb:
+ nb.create_cell("y = 2")
+ raise ValueError("oops")
+ except ValueError:
+ pass
+
+ # The add should not have been applied.
+ assert _graph_codes(k) == snapshot({"0": "x = 1"})
+ assert len(k.graph.cells) == 1
+
+
+class TestSummary:
+ async def test_create_prints_summary(
+ self, k: Kernel, capsys: object
+ ) -> None:
+ ctx = AsyncCodeModeContext(k)
+
+ async with ctx as nb:
+ nb.create_cell("x = 1")
+
+ captured = capsys.readouterr() # type: ignore[attr-defined]
+ assert "created cell" in captured.out
+
+ async def test_edit_prints_summary(
+ self, k: Kernel, capsys: object
+ ) -> None:
+ await k.run([ExecuteCellCommand(cell_id="0", code="x = 1")])
+ ctx = AsyncCodeModeContext(k)
+
+ async with ctx as nb:
+ nb.edit_cell("0", code="x = 2")
+
+ captured = capsys.readouterr() # type: ignore[attr-defined]
+ assert "edited code of cell" in captured.out
+
+ async def test_delete_prints_summary(
+ self, k: Kernel, capsys: object
+ ) -> None:
+ await k.run([ExecuteCellCommand(cell_id="0", code="x = 1")])
+ ctx = AsyncCodeModeContext(k)
+
+ async with ctx as nb:
+ nb.delete_cell("0")
+
+ captured = capsys.readouterr() # type: ignore[attr-defined]
+ assert "deleted cell" in captured.out
+
+ async def test_noop_prints_nothing(
+ self, k: Kernel, capsys: object
+ ) -> None:
+ ctx = AsyncCodeModeContext(k)
+
+ async with ctx as nb: # noqa: B018
+ pass
+
+ captured = capsys.readouterr() # type: ignore[attr-defined]
+ assert captured.out == ""
+
+ async def test_mixed_ops_prints_all(
+ self, k: Kernel, capsys: object
+ ) -> None:
+ await k.run(
+ [
+ ExecuteCellCommand(cell_id="0", code="a = 1"),
+ ExecuteCellCommand(cell_id="1", code="b = 2"),
+ ]
+ )
+ ctx = AsyncCodeModeContext(k)
+
+ async with ctx as nb:
+ nb.delete_cell("1")
+ nb.create_cell("c = 3")
+ nb.edit_cell("0", code="a = 10")
+
+ captured = capsys.readouterr() # type: ignore[attr-defined]
+ assert "deleted cell" in captured.out
+ assert "created cell" in captured.out
+ assert "edited code of cell" in captured.out
+
+
+class TestResolveTarget:
+ async def test_create_after_pending_add_by_name(self, k: Kernel) -> None:
+ """Can reference a just-added cell by name in a subsequent add."""
+ ctx = AsyncCodeModeContext(k)
+
+ async with ctx as nb:
+ nb.create_cell("x = 1", name="first")
+ nb.create_cell("y = x + 1", after="first")
+
+ assert k.globals["x"] == 1
+ assert k.globals["y"] == 2
+
+ # "first" should come before the second cell in ordering.
+ ids_notifs = _ids_notifs(k)
+ cell_ids = ids_notifs[0].cell_ids
+ assert len(cell_ids) == 2
+
+ async def test_create_after_renamed_cell(self, k: Kernel) -> None:
+ """Can reference a cell by its new name after edit_cell renames it."""
+ await k.run(
+ [
+ ExecuteCellCommand(cell_id="0", code="a = 1"),
+ ExecuteCellCommand(cell_id="1", code="b = 2"),
+ ]
+ )
+ ctx = AsyncCodeModeContext(k)
+ _clear_messages(k)
+
+ async with ctx as nb:
+ nb.edit_cell("0", name="renamed")
+ nb.create_cell("c = a + b", after="renamed")
+
+ assert k.globals["c"] == 3
+
+ # New cell should be after "0" (renamed), before "1".
+ ids_notifs = _ids_notifs(k)
+ cell_ids = ids_notifs[0].cell_ids
+ assert cell_ids[0] == "0"
+ assert cell_ids[2] == "1"
+
+
+class TestInstallPackages:
+ async def test_install_single(self, k: Kernel) -> None:
+ ctx = AsyncCodeModeContext(k)
+ pm = k.packages_callbacks.package_manager
+ assert pm is not None
+
+ with patch.object(
+ pm, "install", new_callable=AsyncMock, return_value=True
+ ) as mock_install:
+ async with ctx:
+ ctx.install_packages("pandas")
+ # Not installed yet — still queued.
+ assert mock_install.call_count == 0
+
+ assert mock_install.call_count == 1
+ assert mock_install.call_args_list[0].args[0] == "pandas"
+ assert mock_install.call_args_list[0].kwargs["version"] == ""
+
+ async def test_install_multiple_with_specifiers(self, k: Kernel) -> None:
+ ctx = AsyncCodeModeContext(k)
+ pm = k.packages_callbacks.package_manager
+ assert pm is not None
+
+ with patch.object(
+ pm, "install", new_callable=AsyncMock, return_value=True
+ ) as mock_install:
+ async with ctx:
+ ctx.install_packages("pandas", "polars>=0.20", "numpy==1.26")
+
+ # Each package should have been installed one-by-one.
+ installed = {
+ call.args[0]: call.kwargs["version"]
+ for call in mock_install.call_args_list
+ }
+ assert installed["pandas"] == ""
+ assert installed["polars>=0.20"] == ""
+ assert installed["numpy==1.26"] == ""
diff --git a/tests/_code_mode/test_plan_building.py b/tests/_code_mode/test_plan_building.py
new file mode 100644
index 0000000000..62b772af06
--- /dev/null
+++ b/tests/_code_mode/test_plan_building.py
@@ -0,0 +1,260 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import pytest
+from inline_snapshot import snapshot
+
+from marimo._ast.cell import CellConfig
+from marimo._code_mode._plan import (
+ _AddOp,
+ _build_plan,
+ _DeleteOp,
+ _MoveOp,
+ _PlanEntry,
+ _UpdateOp,
+ _validate_ops,
+)
+from marimo._types.ids import CellId_t
+
+
+def ids(*names: str) -> list[CellId_t]:
+ return [CellId_t(n) for n in names]
+
+
+def cell_ids(plan: list[_PlanEntry]) -> list[str]:
+ return [str(e.cell_id) for e in plan]
+
+
+def codes(plan: list[_PlanEntry]) -> list[str | None]:
+ return [e.code for e in plan]
+
+
+class TestAdd:
+ def test_append_at_end(self) -> None:
+ plan = _build_plan(
+ ids("a", "b"),
+ [_AddOp(cell_id=CellId_t("new"), code="x", config=CellConfig())],
+ )
+ assert cell_ids(plan) == snapshot(["a", "b", "new"])
+ assert codes(plan) == snapshot([None, None, "x"])
+
+ def test_add_after(self) -> None:
+ plan = _build_plan(
+ ids("a", "b", "c"),
+ [
+ _AddOp(
+ cell_id=CellId_t("new"),
+ code="x",
+ config=CellConfig(),
+ after=CellId_t("a"),
+ )
+ ],
+ )
+ assert cell_ids(plan) == snapshot(["a", "new", "b", "c"])
+
+ def test_add_before(self) -> None:
+ plan = _build_plan(
+ ids("a", "b", "c"),
+ [
+ _AddOp(
+ cell_id=CellId_t("new"),
+ code="x",
+ config=CellConfig(),
+ before=CellId_t("b"),
+ )
+ ],
+ )
+ assert cell_ids(plan) == snapshot(["a", "new", "b", "c"])
+
+ def test_add_into_empty(self) -> None:
+ plan = _build_plan(
+ [],
+ [_AddOp(cell_id=CellId_t("new"), code="x", config=CellConfig())],
+ )
+ assert cell_ids(plan) == snapshot(["new"])
+
+ def test_add_multiple(self) -> None:
+ plan = _build_plan(
+ ids("a"),
+ [
+ _AddOp(cell_id=CellId_t("x"), code="1", config=CellConfig()),
+ _AddOp(cell_id=CellId_t("y"), code="2", config=CellConfig()),
+ ],
+ )
+ assert cell_ids(plan) == snapshot(["a", "x", "y"])
+
+ def test_add_after_pending(self) -> None:
+ """An add can reference a cell added earlier in the same batch."""
+ plan = _build_plan(
+ ids("a"),
+ [
+ _AddOp(cell_id=CellId_t("x"), code="1", config=CellConfig()),
+ _AddOp(
+ cell_id=CellId_t("y"),
+ code="2",
+ config=CellConfig(),
+ after=CellId_t("x"),
+ ),
+ ],
+ )
+ assert cell_ids(plan) == snapshot(["a", "x", "y"])
+
+
+class TestUpdate:
+ def test_update_code(self) -> None:
+ plan = _build_plan(
+ ids("a", "b", "c"),
+ [_UpdateOp(cell_id=CellId_t("b"), code="new")],
+ )
+ assert cell_ids(plan) == snapshot(["a", "b", "c"])
+ assert codes(plan) == snapshot([None, "new", None])
+
+ def test_update_config_only(self) -> None:
+ cfg = CellConfig(hide_code=True)
+ plan = _build_plan(
+ ids("a"),
+ [_UpdateOp(cell_id=CellId_t("a"), config=cfg)],
+ )
+ assert plan[0].config == cfg
+ assert plan[0].code is None
+
+ def test_update_not_found(self) -> None:
+ with pytest.raises(KeyError):
+ _build_plan(
+ ids("a"),
+ [_UpdateOp(cell_id=CellId_t("missing"), code="x")],
+ )
+
+
+class TestDelete:
+ def test_delete_single(self) -> None:
+ plan = _build_plan(
+ ids("a", "b", "c"),
+ [_DeleteOp(cell_id=CellId_t("b"))],
+ )
+ assert cell_ids(plan) == snapshot(["a", "c"])
+
+ def test_delete_multiple(self) -> None:
+ plan = _build_plan(
+ ids("a", "b", "c"),
+ [
+ _DeleteOp(cell_id=CellId_t("a")),
+ _DeleteOp(cell_id=CellId_t("c")),
+ ],
+ )
+ assert cell_ids(plan) == snapshot(["b"])
+
+ def test_delete_all(self) -> None:
+ plan = _build_plan(
+ ids("a", "b"),
+ [
+ _DeleteOp(cell_id=CellId_t("a")),
+ _DeleteOp(cell_id=CellId_t("b")),
+ ],
+ )
+ assert cell_ids(plan) == snapshot([])
+
+ def test_delete_not_found(self) -> None:
+ with pytest.raises(KeyError):
+ _build_plan(ids("a"), [_DeleteOp(cell_id=CellId_t("missing"))])
+
+
+class TestMove:
+ def test_move_after(self) -> None:
+ plan = _build_plan(
+ ids("a", "b", "c"),
+ [_MoveOp(cell_id=CellId_t("a"), after=CellId_t("c"))],
+ )
+ assert cell_ids(plan) == snapshot(["b", "c", "a"])
+
+ def test_move_before(self) -> None:
+ plan = _build_plan(
+ ids("a", "b", "c"),
+ [_MoveOp(cell_id=CellId_t("c"), before=CellId_t("a"))],
+ )
+ assert cell_ids(plan) == snapshot(["c", "a", "b"])
+
+ def test_move_no_anchor_raises(self) -> None:
+ with pytest.raises(ValueError, match="before or after"):
+ _build_plan(
+ ids("a", "b"),
+ [_MoveOp(cell_id=CellId_t("a"))],
+ )
+
+
+class TestCombined:
+ def test_delete_then_add(self) -> None:
+ plan = _build_plan(
+ ids("a", "b", "c"),
+ [
+ _DeleteOp(cell_id=CellId_t("b")),
+ _AddOp(
+ cell_id=CellId_t("new"),
+ code="d",
+ config=CellConfig(),
+ after=CellId_t("a"),
+ ),
+ ],
+ )
+ assert cell_ids(plan) == snapshot(["a", "new", "c"])
+
+ def test_add_then_update(self) -> None:
+ plan = _build_plan(
+ ids("a"),
+ [
+ _AddOp(
+ cell_id=CellId_t("new"), code="tmp", config=CellConfig()
+ ),
+ _UpdateOp(cell_id=CellId_t("new"), code="final"),
+ ],
+ )
+ assert cell_ids(plan) == snapshot(["a", "new"])
+ assert codes(plan) == snapshot([None, "final"])
+
+
+class TestValidation:
+ def test_delete_and_update_same_cell(self) -> None:
+ with pytest.raises(ValueError, match="delete.*update"):
+ _validate_ops(
+ [
+ _UpdateOp(cell_id=CellId_t("a"), code="x"),
+ _DeleteOp(cell_id=CellId_t("a")),
+ ]
+ )
+
+ def test_update_and_delete_same_cell(self) -> None:
+ with pytest.raises(ValueError, match="update.*delete"):
+ _validate_ops(
+ [
+ _DeleteOp(cell_id=CellId_t("a")),
+ _UpdateOp(cell_id=CellId_t("a"), code="x"),
+ ]
+ )
+
+ def test_delete_and_move_same_cell(self) -> None:
+ with pytest.raises(ValueError, match="delete.*move"):
+ _validate_ops(
+ [
+ _MoveOp(cell_id=CellId_t("a"), after=CellId_t("b")),
+ _DeleteOp(cell_id=CellId_t("a")),
+ ]
+ )
+
+ def test_double_delete(self) -> None:
+ with pytest.raises(ValueError, match="deleted more than once"):
+ _validate_ops(
+ [
+ _DeleteOp(cell_id=CellId_t("a")),
+ _DeleteOp(cell_id=CellId_t("a")),
+ ]
+ )
+
+ def test_valid_ops_pass(self) -> None:
+ # Should not raise.
+ _validate_ops(
+ [
+ _AddOp(cell_id=CellId_t("new"), code="x", config=CellConfig()),
+ _UpdateOp(cell_id=CellId_t("a"), code="y"),
+ _DeleteOp(cell_id=CellId_t("b")),
+ ]
+ )
diff --git a/tests/_messaging/test_tracebacks.py b/tests/_messaging/test_tracebacks.py
index 364e625f2e..48ec9ec7c2 100644
--- a/tests/_messaging/test_tracebacks.py
+++ b/tests/_messaging/test_tracebacks.py
@@ -3,9 +3,8 @@ from __future__ import annotations
from unittest.mock import MagicMock, patch
-from marimo._messaging.context import HTTP_REQUEST_CTX
+from marimo._messaging.context import HTTP_REQUEST_CTX, is_headless_request
from marimo._messaging.tracebacks import (
- _accepts_html,
_highlight_traceback,
_trim_traceback,
is_code_highlighting,
@@ -131,9 +130,9 @@ class TestTracebacks:
HTTP_REQUEST_CTX.reset(token)
-class TestAcceptsHtml:
+class TestIsHeadlessRequest:
def test_no_request_context(self) -> None:
- assert _accepts_html() is True
+ assert is_headless_request() is False
def test_accept_event_stream(self) -> None:
req = HTTPRequest(
@@ -148,7 +147,7 @@ class TestAcceptsHtml:
)
token = HTTP_REQUEST_CTX.set(req)
try:
- assert _accepts_html() is False
+ assert is_headless_request() is True
finally:
HTTP_REQUEST_CTX.reset(token)
@@ -165,7 +164,7 @@ class TestAcceptsHtml:
)
token = HTTP_REQUEST_CTX.set(req)
try:
- assert _accepts_html() is True
+ assert is_headless_request() is False
finally:
HTTP_REQUEST_CTX.reset(token)
@@ -182,7 +181,7 @@ class TestAcceptsHtml:
)
token = HTTP_REQUEST_CTX.set(req)
try:
- assert _accepts_html() is False
+ assert is_headless_request() is True
finally:
HTTP_REQUEST_CTX.reset(token)
@@ -199,7 +198,7 @@ class TestAcceptsHtml:
)
token = HTTP_REQUEST_CTX.set(req)
try:
- assert _accepts_html() is False
+ assert is_headless_request() is True
finally:
HTTP_REQUEST_CTX.reset(token)
diff --git a/tests/_server/test_scratchpad.py b/tests/_server/test_scratchpad.py
index bd650e6b7f..063cc76a4c 100644
--- a/tests/_server/test_scratchpad.py
+++ b/tests/_server/test_scratchpad.py
@@ -299,6 +299,27 @@ class TestBuildDoneEvent:
assert data["error"]["type"] == "MarimoSyntaxError"
assert "exception_type" not in data["error"]
+ @pytest.mark.parametrize(
+ "exception_type",
+ ["ModuleNotFoundError", "ImportError"],
+ )
+ def test_import_error_includes_install_hint(
+ self, exception_type: str
+ ) -> None:
+ err = MarimoExceptionRaisedError(
+ msg=f"{exception_type}: No module named 'pandas'",
+ exception_type=exception_type,
+ raising_cell=None,
+ )
+ notif = CellNotification(
+ cell_id=SCRATCH_CELL_ID,
+ output=CellOutput.errors([err]),
+ status="idle",
+ )
+ _, data = _parse_sse(build_done_event(_make_session(notif)))
+ assert data["success"] is False
+ assert "ctx.install_packages" in data["error"]["msg"]
+
def test_timeout(self) -> None:
_, data = _parse_sse(build_timeout_event(30.0))
assert data["success"] is False