A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
Expose cell outputs to code_mode (#9653)
Trevor Manzcc17b68f286a
diff --git a/marimo/_ast/pytest.py b/marimo/_ast/pytest.pyindex 809f3f8c96..48d201d31d 100644--- a/marimo/_ast/pytest.py+++ b/marimo/_ast/pytest.py@@ -13,7 +13,6 @@ from typing import TYPE_CHECKING, Any, NoReturn, TypeVar, castfrom marimo._ast.cell import Cellfrom marimo._ast.fast_stack import fast_stackfrom marimo._ast.parse import ast_parse-from marimo._runtime.context import ContextNotInitializedError, get_contextif TYPE_CHECKING:from collections.abc import Mapping@@ -359,6 +358,16 @@ def build_test_class(except ImportError:pass+ # Deferred to module-load time: importing marimo._runtime.context at+ # the top of this file closes a cycle through+ # commands → outputs → cell_output → errors → dataflow → compiler →+ # pytest → context. Pulling the import inside the function keeps+ # commands.py free to top-import the new outputs module.+ from marimo._runtime.context import (+ ContextNotInitializedError,+ get_context,+ )+# Try to get context globals, or fall back to frame localstry:base_local.update(get_context().globals)diff --git a/marimo/_code_mode/_context.py b/marimo/_code_mode/_context.pyindex 40fed04fa6..9948a9ff21 100644--- a/marimo/_code_mode/_context.py+++ b/marimo/_code_mode/_context.py@@ -54,6 +54,7 @@ from marimo._code_mode._plan import (_UpdateOp,_validate_ops,)+from marimo._messaging.cell_output import CellOutputfrom marimo._messaging.errors import Errorfrom marimo._messaging.notebook.changes import (CreateCell,@@ -69,6 +70,10 @@ from marimo._messaging.notebook.document import (NotebookCell as _NotebookCell,NotebookDocument,)+from marimo._messaging.notebook.outputs import (+ CellOutputs,+ get_current_outputs,+)from marimo._messaging.notification import (NotebookDocumentTransactionNotification,Notification,@@ -280,19 +285,30 @@ class NotebookCell:`exception` fields. Covers both runtime exceptions(e.g. `NameError`) and graph errors (multiply-definedvariables, cycles, etc.).+ output : CellOutput | None+ The cell's last main (rich display) output, or `None` if no+ output was captured. **Frozen snapshot** — taken at+ scratchpad-start, not refreshed when `ctx.run_cell` produces+ new outputs in the same batch. Re-enter `cm.get_context()` to+ see fresh outputs.+ console_outputs : list[CellOutput]+ Buffered stdout/stderr outputs from the cell's last execution.+ Same frozen-snapshot caveat as `output`."""- __slots__ = ("_cell", "_graph_errors", "_impl")+ __slots__ = ("_cell", "_graph_errors", "_impl", "_outputs")def __init__(self,cell: _NotebookCell,cell_impl: CellRuntimeState | None,graph_errors: tuple[Error, ...] = (),+ outputs: CellOutputs | None = None,) -> None:self._cell = cellself._impl = cell_implself._graph_errors = graph_errors+ self._outputs = outputs# -- document properties (delegated) --@@ -397,6 +413,29 @@ class NotebookCell:)return result+ @property+ def output(self) -> CellOutput | None:+ """The cell's last main (rich display) output, or `None`.++ Frozen at scratchpad-start — does not reflect outputs produced+ by `ctx.run_cell` in the same batch. Re-enter+ `cm.get_context()` to see fresh outputs.+ """+ if self._outputs is None:+ return None+ return self._outputs.output.get(self._cell.id)++ @property+ def console_outputs(self) -> list[CellOutput]:+ """Buffered stdout/stderr outputs from the last execution.++ Returns an empty list when no console output was captured.+ Same frozen-snapshot semantics as `output`.+ """+ if self._outputs is None:+ return []+ return list(self._outputs.console_outputs.get(self._cell.id, ()))+# -- display --def __repr__(self) -> str:@@ -455,10 +494,17 @@ class _CellsView:graph = self._ctx.graphimpl = graph.cells.get(cell.id)graph_errors = self._ctx._kernel.errors.get(cell.id, ())+ outputs = self._ctx._outputsexcept AttributeError:impl = Nonegraph_errors = ()- return NotebookCell(cell, impl, graph_errors=graph_errors)+ outputs = None+ return NotebookCell(+ cell,+ impl,+ graph_errors=graph_errors,+ outputs=outputs,+ )def _cell_ids(self) -> list[CellId_t]:return list(self._doc)@@ -642,6 +688,11 @@ class AsyncCodeModeContext:)self._kernel = kernelself._document = document+ # Output snapshot is optional — callers that don't pass one+ # (e.g. the MCP code server) get ``cell.output is None`` and+ # ``cell.console_outputs == []`` for every cell, same as cells+ # that genuinely produced no output.+ self._outputs: CellOutputs | None = get_current_outputs()self._cell_manager = cell_managerself._skip_validation = skip_validationself._skip_staleness_check = skip_staleness_checkdiff --git a/marimo/_messaging/notebook/outputs.py b/marimo/_messaging/notebook/outputs.pynew file mode 100644index 0000000000..f52b2ba8da--- /dev/null+++ b/marimo/_messaging/notebook/outputs.py@@ -0,0 +1,69 @@+# Copyright 2026 Marimo. All rights reserved.+"""Snapshot of cell outputs delivered to the kernel for a scratchpad execution.++Sibling to `marimo._messaging.notebook.document`. Kept separate+because `NotebookDocument` is structural-only — cell ordering,+code, names, and configs — while outputs are *execution* state produced+by the kernel and aggregated on the session side. Bundling outputs+onto the document would muddy that line; two parallel ContextVars keep+each layer's concerns crisp.++The snapshot is *frozen* at the start of a scratchpad invocation. It+will not reflect outputs produced by `ctx.run_cell` calls in the same+batch — agents that need fresh outputs should re-enter+`cm.get_context()`.+"""++from __future__ import annotations++from contextlib import contextmanager+from contextvars import ContextVar+from typing import TYPE_CHECKING++import msgspec++from marimo._messaging.cell_output import CellOutput+from marimo._types.ids import CellId_t++if TYPE_CHECKING:+ from collections.abc import Generator+++class CellOutputs(msgspec.Struct):+ """Per-cell output snapshot delivered alongside the document snapshot.++ `output` carries the cell's last main (rich display) output;+ `console_outputs` carries the buffered stdout/stderr stream from+ its last execution. Both are keyed by cell id; missing keys mean+ "no output captured" (the cell never ran, or produced nothing on+ that channel).+ """++ output: dict[CellId_t, CellOutput]+ console_outputs: dict[CellId_t, list[CellOutput]]+++#: Output snapshot for the current scratchpad execution. Set by the+#: kernel before running code_mode so `AsyncCodeModeContext` can read+#: cell outputs without the kernel keeping a live reference to the+#: session view.+_current_outputs: ContextVar[CellOutputs | None] = ContextVar(+ "_current_outputs", default=None+)+++def get_current_outputs() -> CellOutputs | None:+ """Return the output snapshot for the current execution, if any."""+ return _current_outputs.get()+++@contextmanager+def notebook_outputs_context(+ outputs: CellOutputs | None,+) -> Generator[None, None, None]:+ """Context manager for setting and resetting the current output snapshot."""+ token = _current_outputs.set(outputs)+ try:+ yield+ finally:+ _current_outputs.reset(token)diff --git a/marimo/_runtime/commands.py b/marimo/_runtime/commands.pyindex 7173ee7446..32d6397a7b 100644--- a/marimo/_runtime/commands.py+++ b/marimo/_runtime/commands.py@@ -23,6 +23,7 @@ from marimo._ast.app_config import _AppConfigfrom marimo._config.config import MarimoConfigfrom marimo._data.models import DataTableSourcefrom marimo._messaging.notebook.document import NotebookCell+from marimo._messaging.notebook.outputs import CellOutputsfrom marimo._types.encodable import Encodablefrom marimo._types.ids import CellId_t, RequestId, UIElementId, WidgetModelId@@ -360,6 +361,11 @@ class ExecuteScratchpadCommand(Command):notebook_cells: Snapshot of notebook cells from the session document.Used to populate the document ContextVar so code_mode can readcell ordering, code, names, and configs.+ cell_outputs: Snapshot of per-cell outputs (main + console) from the+ session view. Populates a parallel ContextVar so code_mode can+ expose `cell.output` and `cell.console_outputs`. Frozen at+ scratchpad start — not refreshed when `ctx.run_cell` produces+ new outputs in the same batch.run_id: Optional correlation ID. When set, the`CompletedRunNotification` emitted at the end of this commandcarries the same `run_id` so a caller holding a@@ -373,6 +379,8 @@ class ExecuteScratchpadCommand(Command):request: HTTPRequest | None = None# Document snapshot — set by the execution endpoint from session.document.notebook_cells: tuple[NotebookCell, ...] | None = None+ # Output snapshot — set by the execution endpoint from session.session_view.+ cell_outputs: CellOutputs | None = Nonerun_id: str | None = Nonediff --git a/marimo/_runtime/kernel_request_handlers.py b/marimo/_runtime/kernel_request_handlers.pyindex d271b75c21..b2b76aab39 100644--- a/marimo/_runtime/kernel_request_handlers.py+++ b/marimo/_runtime/kernel_request_handlers.py@@ -9,6 +9,7 @@ from marimo._messaging.notebook.document import (NotebookDocument,notebook_document_context,)+from marimo._messaging.notebook.outputs import notebook_outputs_contextfrom marimo._messaging.notification import (CompletedRunNotification,FunctionCallResultNotification,@@ -103,6 +104,7 @@ class KernelRequestHandlers:try:with (notebook_document_context(doc),+ notebook_outputs_context(request.cell_outputs),http_request_context(request.request),):await self._kernel.run_scratchpad(request.code)diff --git a/marimo/_server/api/endpoints/execution.py b/marimo/_server/api/endpoints/execution.pyindex e4aa718fbc..7117ca968a 100644--- a/marimo/_server/api/endpoints/execution.py+++ b/marimo/_server/api/endpoints/execution.py@@ -9,6 +9,7 @@ from starlette.authentication import requiresfrom starlette.responses import JSONResponse, StreamingResponsefrom marimo import _loggers+from marimo._messaging.notebook.outputs import CellOutputsfrom marimo._messaging.notification import AlertNotificationfrom marimo._runtime.commands import HTTPRequest, UpdateUIElementCommandfrom marimo._server.api.deps import AppState@@ -325,11 +326,21 @@ async def execute_code(http_req.meta["screenshot_server_url"] = (f"{scheme}://{app_state.host}:{app_state.port}{base_url}")+ cell_ids = session.document.cell_ids+ cell_outputs = CellOutputs(+ output=session.session_view.get_cell_outputs(cell_ids),+ console_outputs=(+ session.session_view.get_cell_console_outputs(+ cell_ids+ )+ ),+ )session.put_control_request(ExecuteScratchpadCommand(code=body.code,request=http_req,notebook_cells=tuple(session.document.cells),+ cell_outputs=cell_outputs,run_id=run_id,),from_consumer_id=None,diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yamlindex ab6028fd35..91ca46def5 100644--- a/packages/openapi/api.yaml+++ b/packages/openapi/api.yaml@@ -511,6 +511,28 @@ components:- datatitle: CellOutputtype: object+ CellOutputs:+ description: "Per-cell output snapshot delivered alongside the document snapshot.\n\+ \n `output` carries the cell's last main (rich display) output;\n `console_outputs`\+ \ carries the buffered stdout/stderr stream from\n its last execution.\+ \ Both are keyed by cell id; missing keys mean\n \"no output captured\"\+ \ (the cell never ran, or produced nothing on\n that channel)."+ properties:+ console_outputs:+ additionalProperties:+ items:+ $ref: '#/components/schemas/CellOutput'+ type: array+ type: object+ output:+ additionalProperties:+ $ref: '#/components/schemas/CellOutput'+ type: object+ required:+ - output+ - console_outputs+ title: CellOutputs+ type: objectChatAttachment:properties:content_type:@@ -1511,13 +1533,22 @@ components:\ request: HTTP request context if available.\n notebook_cells:\\ Snapshot of notebook cells from the session document.\n Used\\ to populate the document ContextVar so code_mode can read\n cell\- \ ordering, code, names, and configs.\n run_id: Optional correlation\- \ ID. When set, the\n `CompletedRunNotification` emitted at the\- \ end of this command\n carries the same `run_id` so a caller holding\- \ a\n `ScratchCellListener` can filter for *its* completion and\n\- \ ignore `CompletedRun` events from unrelated commands on the\n\- \ same session."+ \ ordering, code, names, and configs.\n cell_outputs: Snapshot of per-cell\+ \ outputs (main + console) from the\n session view. Populates a\+ \ parallel ContextVar so code_mode can\n expose `cell.output` and\+ \ `cell.console_outputs`. Frozen at\n scratchpad start \u2014 not\+ \ refreshed when `ctx.run_cell` produces\n new outputs in the same\+ \ batch.\n run_id: Optional correlation ID. When set, the\n \+ \ `CompletedRunNotification` emitted at the end of this command\n \+ \ carries the same `run_id` so a caller holding a\n `ScratchCellListener`\+ \ can filter for *its* completion and\n ignore `CompletedRun` events\+ \ from unrelated commands on the\n same session."properties:+ cellOutputs:+ anyOf:+ - type: 'null'+ - $ref: '#/components/schemas/CellOutputs'+ default: nullcode:type: stringnotebookCells:@@ -1547,6 +1578,11 @@ components:type: objectExecuteScratchpadRequest:properties:+ cellOutputs:+ anyOf:+ - type: 'null'+ - $ref: '#/components/schemas/CellOutputs'+ default: nullcode:type: stringnotebookCells:diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.tsindex 9439fc0a3c..3cf49d2107 100644--- a/packages/openapi/src/api.ts+++ b/packages/openapi/src/api.ts@@ -3691,6 +3691,24 @@ export interface components {| "video/mpeg";timestamp?: number;};+ /**+ * CellOutputs+ * @description Per-cell output snapshot delivered alongside the document snapshot.+ *+ * `output` carries the cell's last main (rich display) output;+ * `console_outputs` carries the buffered stdout/stderr stream from+ * its last execution. Both are keyed by cell id; missing keys mean+ * "no output captured" (the cell never ran, or produced nothing on+ * that channel).+ */+ CellOutputs: {+ console_outputs: {+ [key: string]: components["schemas"]["CellOutput"][];+ };+ output: {+ [key: string]: components["schemas"]["CellOutput"];+ };+ };/** ChatAttachment */ChatAttachment: {/** @default null */@@ -4278,6 +4296,11 @@ export interface components {* notebook_cells: Snapshot of notebook cells from the session document.* Used to populate the document ContextVar so code_mode can read* cell ordering, code, names, and configs.+ * cell_outputs: Snapshot of per-cell outputs (main + console) from the+ * session view. Populates a parallel ContextVar so code_mode can+ * expose `cell.output` and `cell.console_outputs`. Frozen at+ * scratchpad start — not refreshed when `ctx.run_cell` produces+ * new outputs in the same batch.* run_id: Optional correlation ID. When set, the* `CompletedRunNotification` emitted at the end of this command* carries the same `run_id` so a caller holding a@@ -4286,6 +4309,8 @@ export interface components {* same session.*/ExecuteScratchpadCommand: {+ /** @default null */+ cellOutputs?: null | components["schemas"]["CellOutputs"];code: string;/** @default null */notebookCells?: components["schemas"]["NotebookCell"][] | null;@@ -4298,6 +4323,8 @@ export interface components {};/** ExecuteScratchpadRequest */ExecuteScratchpadRequest: {+ /** @default null */+ cellOutputs?: null | components["schemas"]["CellOutputs"];code: string;/** @default null */notebookCells?: components["schemas"]["NotebookCell"][] | null;diff --git a/tests/_code_mode/test_cells_view.py b/tests/_code_mode/test_cells_view.pyindex 71c65b5313..b4698aed36 100644--- a/tests/_code_mode/test_cells_view.py+++ b/tests/_code_mode/test_cells_view.py@@ -20,11 +20,13 @@ from marimo._code_mode._context import (NotebookCell as EnrichedCell,_CellsView,)+from marimo._messaging.cell_output import CellChannel, CellOutputfrom marimo._messaging.notebook.document import (NotebookCell,NotebookDocument,notebook_document_context,)+from marimo._messaging.notebook.outputs import CellOutputsfrom marimo._runtime.commands import ExecuteCellCommandfrom marimo._runtime.runtime import Kernelfrom marimo._types.ids import CellId_t@@ -518,6 +520,47 @@ class TestEnrichedCellStatus:assert enriched.errors == []+class TestEnrichedCellOutputs:+ """The frozen output snapshot is sliced per-cell in the properties."""++ def test_no_snapshot_returns_defaults(self) -> None:+ cell = _cell("a", "x = 1")+ enriched = EnrichedCell(cell, None)+ assert enriched.output is None+ assert enriched.console_outputs == []++ def test_populated_snapshot_returns_per_cell_slice(self) -> None:+ cell = _cell("a", "print('hi'); x = 1")+ out = CellOutput(+ channel=CellChannel.OUTPUT, mimetype="text/plain", data="1"+ )+ console = [CellOutput.stdout("hi\n"), CellOutput.stderr("warn\n")]+ snap = CellOutputs(+ output={CellId_t("a"): out},+ console_outputs={CellId_t("a"): console},+ )+ enriched = EnrichedCell(cell, None, outputs=snap)+ assert enriched.output is out+ assert enriched.console_outputs == console++ def test_cell_missing_from_snapshot_returns_defaults(self) -> None:+ """Cell created mid-batch isn't in the frozen snapshot."""+ cell = _cell("new", "y = 2")+ snap = CellOutputs(+ output={+ CellId_t("a"): CellOutput(+ channel=CellChannel.OUTPUT,+ mimetype="text/plain",+ data="1",+ )+ },+ console_outputs={CellId_t("a"): [CellOutput.stdout("hi\n")]},+ )+ enriched = EnrichedCell(cell, None, outputs=snap)+ assert enriched.output is None+ assert enriched.console_outputs == []++class TestEnrichedCellRepr:def test_repr_no_impl_with_code(self) -> None:cell = _cell("a1", "x = 1")diff --git a/tests/_server/api/endpoints/test_execution.py b/tests/_server/api/endpoints/test_execution.pyindex 316bb32afb..28c50cc664 100644--- a/tests/_server/api/endpoints/test_execution.py+++ b/tests/_server/api/endpoints/test_execution.py@@ -211,6 +211,75 @@ class TestExecutionRoutes_EditMode:# Mock server uses host="localhost", port=1234, base_url=""assert meta["screenshot_server_url"] == "http://localhost:1234"+ @staticmethod+ @with_session(SESSION_ID)+ def test_execute_attaches_cell_outputs_snapshot(+ client: TestClient,+ ) -> None:+ """`/api/kernel/execute` must populate `cell_outputs` from the+ session view so code_mode can expose `cell.output` and+ `cell.console_outputs`. Regression guard: removing the+ construction line in the endpoint should fail this test.+ """+ from unittest.mock import patch++ from marimo._messaging.cell_output import CellChannel, CellOutput+ from marimo._messaging.notification import CellNotification+ from marimo._runtime.commands import ExecuteScratchpadCommand+ from marimo._server import scratchpad as scratchpad_mod++ session = get_session_manager(client).get_session(SESSION_ID)+ assert session is not None++ # Seed the session view with an output for an existing cell so+ # we can assert it survives the round-trip to the command.+ cell_id = first(session.document.cell_ids)+ sample = CellOutput(+ channel=CellChannel.OUTPUT,+ mimetype="text/plain",+ data="42",+ )+ sample_console = CellOutput.stdout("hello\n")+ session.session_view.cell_notifications[cell_id] = CellNotification(+ cell_id=cell_id,+ output=sample,+ console=[sample_console],+ )++ captured: list[object] = []++ def capture(req: object, from_consumer_id: object) -> None: # noqa: ARG001+ captured.append(req)++ async def empty_stream(self: object): # noqa: ARG001+ if False:+ yield ""++ with (+ patch.object(session, "put_control_request", side_effect=capture),+ patch.object(+ scratchpad_mod.ScratchCellListener,+ "stream",+ empty_stream,+ ),+ ):+ response = client.post(+ "/api/kernel/execute",+ headers=HEADERS,+ json={"code": "x = 1"},+ )++ assert response.status_code == 200, response.text++ scratchpad_cmds = [+ c for c in captured if isinstance(c, ExecuteScratchpadCommand)+ ]+ assert len(scratchpad_cmds) == 1+ cell_outputs = scratchpad_cmds[0].cell_outputs+ assert cell_outputs is not None+ assert cell_outputs.output[cell_id] is sample+ assert cell_outputs.console_outputs[cell_id] == [sample_console]+@staticmethod@with_session(SESSION_ID)def test_takeover_no_file_key(client: TestClient) -> None: