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
Fix console output routing for code_mode run_cell (#8790)
Trevor Manz928a2e2268a7
diff --git a/marimo/_runtime/redirect_streams.py b/marimo/_runtime/redirect_streams.pyindex 08639cdb32..2ab7371f39 100644--- a/marimo/_runtime/redirect_streams.py+++ b/marimo/_runtime/redirect_streams.py@@ -13,6 +13,7 @@ from marimo._messaging.thread_local_streams import (set_thread_local_streams,)from marimo._messaging.types import Stderr, Stdin, Stdout, Stream+from marimo._runtime.scratch import SCRATCH_CELL_IDfrom marimo._types.ids import CellId_tif TYPE_CHECKING:@@ -60,12 +61,17 @@ def redirect_streams() -> Iterator[None]:cell_id_old = stream.cell_id- # In a nested context; NOOP so messages still reach the top-level cell.+ # In a nested context, generally NOOP so messages reach the top-level+ # cell. The exception is the scratchpad: when code_mode runs cells+ # from within __scratch__, we must swap cell_id so console output+ # routes to the real cell, not the scratchpad.if cell_id_old is not None:+ if cell_id_old == SCRATCH_CELL_ID:+ stream.cell_id = cell_idtry:yieldfinally:- ...+ stream.cell_id = cell_id_oldreturnstream.cell_id = cell_iddiff --git a/tests/_runtime/test_redirect_streams.py b/tests/_runtime/test_redirect_streams.pynew file mode 100644index 0000000000..1aefe81772--- /dev/null+++ b/tests/_runtime/test_redirect_streams.py@@ -0,0 +1,19 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++from marimo._runtime.redirect_streams import redirect_streams+from marimo._runtime.scratch import SCRATCH_CELL_ID+from marimo._types.ids import CellId_t+from tests.conftest import _MockStream+++def test_nested_from_scratch_swaps_cell_id() -> None:+ """When code_mode runs cells from the scratchpad, the inner cell's+ console output must be tagged with its own cell_id, not __scratch__."""+ stream = _MockStream()+ inner_id = CellId_t("real_cell")++ with redirect_streams(SCRATCH_CELL_ID, stream, None, None, None):+ with redirect_streams(inner_id, stream, None, None, None):+ assert stream.cell_id == inner_id+ assert stream.cell_id == SCRATCH_CELL_ID