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.

fix: let marimo-lens decide when to mount (#11024)

Péter Gyarmatibd1e03920071
diff --git a/frontend/src/components/app-config/optional-features.tsx b/frontend/src/components/app-config/optional-features.tsx
index cc9602779d..e0c43579c3 100644
--- a/frontend/src/components/app-config/optional-features.tsx
+++ b/frontend/src/components/app-config/optional-features.tsx
@@ -107,7 +107,7 @@ const OPTIONAL_DEPENDENCIES: OptionalFeature[] = [
},
{
id: "lens",
- packagesRequired: [{ name: "marimo-lens", minVersion: "0.2.0" }],
+ packagesRequired: [{ name: "marimo-lens", minVersion: "0.2.3" }],
additionalPackageInstalls: [],
description: "Select outputs for agents",
},
diff --git a/marimo/_runtime/runner/hooks_lens.py b/marimo/_runtime/runner/hooks_lens.py
index 91a8439780..be43466ba3 100644
--- a/marimo/_runtime/runner/hooks_lens.py
+++ b/marimo/_runtime/runner/hooks_lens.py
@@ -5,8 +5,6 @@ from typing import TYPE_CHECKING
from marimo import _loggers
from marimo._runtime import output
-from marimo._runtime.context.utils import running_in_notebook
-from marimo._utils.flatten import contains_instance
if TYPE_CHECKING:
from marimo._ast.cell import CellImpl
@@ -17,31 +15,28 @@ LOGGER = _loggers.marimo_logger()
# Imports are cached before notebook execution; mount in the importing cell.
+# marimo-lens decides whether the notebook needs a Lens.
def mount_lens(
cell: CellImpl, ctx: PostExecutionHookContext, result: RunResult
) -> None:
- if (
- not result.success()
- or not running_in_notebook()
- or cell.namespace_to_variable("marimo") is None
- ):
+ del ctx
+ if not result.success() or cell.namespace_to_variable("marimo") is None:
return
try:
try:
- from marimo_lens import Lens # type: ignore[import-not-found]
- except ModuleNotFoundError as exc:
+ from marimo_lens import ( # type: ignore[import-not-found]
+ automatic_lens,
+ )
+ except ImportError as exc:
+ # Also covers a marimo-lens release without automatic_lens.
if exc.name != "marimo_lens":
raise
return
- if any(
- contains_instance(other.output, Lens)
- for other in ctx.graph.cells.values()
- ):
+ lens = automatic_lens()
+ if lens is None:
return
-
- lens = Lens()
cell.set_output((cell.output, lens))
if result.output is not None:
output.append(result.output)
diff --git a/pyproject.toml b/pyproject.toml
index c0878a6c48..d154df3a5f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -104,7 +104,7 @@ sandbox = [
recommended = [
"marimo[sql]",
"marimo[sandbox]", # For `marimo edit --sandbox DIRECTORY`
- "marimo-lens>=0.2.0", # Inspect and select notebook outputs
+ "marimo-lens>=0.2.3", # Inspect and select notebook outputs
"cryptography>=42.0.0", # Ed25519 signing of persistent cache manifests
"altair>=5.4.0", # Plotting in datasource viewer
"pydantic-ai-slim[openai]>=1.107.0,<3.0.0", # AI features
diff --git a/tests/_runtime/test_lens_autoload.py b/tests/_runtime/test_lens_autoload.py
index 46fff5a93b..3115263cff 100644
--- a/tests/_runtime/test_lens_autoload.py
+++ b/tests/_runtime/test_lens_autoload.py
@@ -1,6 +1,10 @@
# Copyright 2026 Marimo. All rights reserved.
+import gc
import sys
-from unittest.mock import patch
+import weakref
+from importlib.machinery import ModuleSpec
+from types import ModuleType
+from unittest.mock import Mock, patch
import pytest
@@ -8,39 +12,81 @@ from marimo._runtime.commands import ExecuteCellCommand
from tests._runtime._helpers.session import mocked_kernel_session
+class Lens:
+ def _repr_html_(self):
+ return "<span>Lens</span>"
+
+
+def _lens_module(automatic_lens=None) -> ModuleType:
+ module = ModuleType("marimo_lens")
+ module.__spec__ = ModuleSpec("marimo_lens", loader=None)
+ if automatic_lens is not None:
+ module.automatic_lens = automatic_lens
+ return module
+
+
+def _outputs(session, cell_id):
+ return [
+ op.output.data
+ for op in session.streams.stream.cell_notifications
+ if op.cell_id == cell_id and op.output is not None
+ ]
+
+
@pytest.mark.parametrize("expression", ["", "mo.md('hello')"])
-async def test_lens_mount_and_rerun(expression):
- lens = pytest.importorskip("marimo_lens")
+async def test_lens_shows_the_automatic_lens_after_the_marimo_import(
+ expression,
+):
+ automatic_lens = Mock(side_effect=Lens)
with mocked_kernel_session() as session:
kernel = session.kernel
command = ExecuteCellCommand(
cell_id="lens", code=f"import marimo as mo\n{expression}"
)
- await kernel.run([command])
- assert not kernel.errors
- first_lens = kernel.graph.cells["lens"].output[1]
- assert isinstance(first_lens, lens.Lens)
- outputs = [
- op.output.data
- for op in session.streams.stream.cell_notifications
- if op.cell_id == "lens" and op.output is not None
- ]
- if expression:
- assert "hello" in outputs[-1]
- assert "marimo-anywidget" in outputs[-1]
- await kernel.run([command])
- assert not kernel.errors
- assert kernel.graph.cells["lens"].output[1] is not first_lens
- await kernel.run(
- [ExecuteCellCommand(cell_id="other", code="mo.md('other')")]
- )
+ with patch.dict(sys.modules, marimo_lens=_lens_module(automatic_lens)):
+ await kernel.run([command])
+ assert not kernel.errors
+ first_lens = kernel.graph.cells["lens"].output[1]
+ assert isinstance(first_lens, Lens)
+ if expression:
+ assert "hello" in _outputs(session, "lens")[-1]
+ assert "<span>Lens</span>" in _outputs(session, "lens")[-1]
+
+ await kernel.run([command])
+ assert kernel.graph.cells["lens"].output[1] is not first_lens
+
+ await kernel.run(
+ [ExecuteCellCommand(cell_id="other", code="mo.md('other')")]
+ )
assert kernel.graph.cells["other"].output is None
+ assert automatic_lens.call_count == 2
+
+
+async def test_lens_keeps_the_cell_output_when_lens_declines():
+ automatic_lens = Mock(return_value=None)
+ with mocked_kernel_session() as session:
+ with patch.dict(sys.modules, marimo_lens=_lens_module(automatic_lens)):
+ await session.kernel.run(
+ [
+ ExecuteCellCommand(
+ cell_id="lens",
+ code="import marimo as mo\nmo.md('original')",
+ )
+ ]
+ )
+ output = _outputs(session, "lens")[-1]
+ assert "original" in output
+ assert "<span>Lens</span>" not in output
+ automatic_lens.assert_called_once_with()
-async def test_lens_absent():
[email protected]("installed", [False, True])
+async def test_lens_absent(installed):
+ # An installed module without automatic_lens is an older marimo-lens.
+ module = _lens_module() if installed else None
with mocked_kernel_session() as session:
with (
- patch.dict(sys.modules, marimo_lens=None),
+ patch.dict(sys.modules, marimo_lens=module),
patch(
"marimo._runtime.runner.hooks_lens.LOGGER.warning"
) as warning,
@@ -53,34 +99,21 @@ async def test_lens_absent():
]
)
assert not session.kernel.errors
+ assert session.kernel.graph.cells["lens"].output is None
warning.assert_not_called()
- "failure",
- ["import", "dependency", "constructor", "constructor_missing_module"],
-)
[email protected]("failure", ["dependency", "automatic_lens"])
async def test_broken_lens_does_not_interrupt_notebook(failure):
- import sys
- from importlib.machinery import ModuleSpec
- from types import ModuleType
- from unittest.mock import Mock
-
- broken_lens = ModuleType("marimo_lens")
- broken_lens.__spec__ = ModuleSpec("marimo_lens", loader=None)
+ broken_lens = _lens_module()
if failure == "dependency":
broken_lens.__getattr__ = Mock(
side_effect=ModuleNotFoundError(name="anywidget")
)
- elif failure in {"constructor", "constructor_missing_module"}:
-
- class BrokenLens:
- def __init__(self):
- if failure == "constructor":
- raise RuntimeError("broken Lens")
- raise ModuleNotFoundError(name="marimo_lens")
-
- broken_lens.Lens = BrokenLens
+ else:
+ broken_lens.automatic_lens = Mock(
+ side_effect=RuntimeError("broken Lens")
+ )
with mocked_kernel_session() as session:
with (
@@ -103,39 +136,22 @@ async def test_broken_lens_does_not_interrupt_notebook(failure):
)
assert not session.kernel.errors
assert "answer" in session.kernel.globals
- outputs = [
- op.output.data
- for op in session.streams.stream.cell_notifications
- if op.cell_id == "import" and op.output is not None
- ]
- assert "original output" in outputs[-1]
+ assert "original output" in _outputs(session, "import")[-1]
warning.assert_called_once()
async def test_lens_lifetime_preserves_cell_output():
- import gc
- import sys
- import weakref
- from importlib.machinery import ModuleSpec
- from types import ModuleType
-
from marimo._plugins.ui._core.ui_element import UIElement
instances = []
- class Lens:
- def __init__(self):
- instances.append(weakref.ref(self))
-
- def _repr_html_(self):
- return "<span>Lens</span>"
-
- module = ModuleType("marimo_lens")
- module.__spec__ = ModuleSpec("marimo_lens", loader=None)
- module.Lens = Lens
+ def automatic_lens():
+ lens = Lens()
+ instances.append(weakref.ref(lens))
+ return lens
with mocked_kernel_session() as session:
- with patch.dict(sys.modules, marimo_lens=module):
+ with patch.dict(sys.modules, marimo_lens=_lens_module(automatic_lens)):
await session.kernel.run(
[
ExecuteCellCommand(
@@ -158,32 +174,46 @@ async def test_lens_lifetime_preserves_cell_output():
assert previous_output() is None
-async def test_lens_mounts_once_per_notebook():
- lens = pytest.importorskip("marimo_lens")
- from marimo._runtime.commands import DeleteCellCommand
+async def test_installed_lens_keeps_one_lens_per_notebook():
+ marimo_lens = pytest.importorskip("marimo_lens")
+ with mocked_kernel_session() as session:
+ kernel = session.kernel
+ await kernel.run(
+ [
+ ExecuteCellCommand(
+ cell_id="first", code="import marimo as mo"
+ ),
+ ExecuteCellCommand(
+ cell_id="second", code="import marimo as other_mo"
+ ),
+ ]
+ )
+ automatic = kernel.graph.cells["first"].output[1]
+ assert isinstance(automatic, marimo_lens.Lens)
+ assert kernel.graph.cells["second"].output is None
+ assert marimo_lens.notebook_lens() is automatic
- # Separate kernels must each mount their own Lens.
- for _ in range(2):
- with mocked_kernel_session() as session:
- kernel = session.kernel
- first = ExecuteCellCommand(
- cell_id="first", code="import marimo as mo"
- )
- second = ExecuteCellCommand(
- cell_id="second", code="import marimo as other_mo"
- )
- await kernel.run([first])
- mounted = kernel.graph.cells["first"].output[1]
- assert isinstance(mounted, lens.Lens)
-
- await kernel.run([second])
- await kernel.run([second])
- assert kernel.graph.cells["second"].output is None
- assert kernel.graph.cells["first"].output[1] is mounted
-
- await kernel.delete_cell(DeleteCellCommand(cell_id="first"))
- await kernel.run([second])
- replacement = kernel.graph.cells["second"].output[1]
- assert isinstance(replacement, lens.Lens)
- assert replacement is not mounted
- assert not kernel.errors
+ await kernel.run(
+ [
+ ExecuteCellCommand(
+ cell_id="authored",
+ code="from marimo_lens import Lens\n"
+ "lens = Lens(dom_selector='main')",
+ )
+ ]
+ )
+ assert not kernel.errors
+ assert marimo_lens.notebook_lens() is kernel.globals["lens"]
+
+
+async def test_installed_lens_stays_out_of_apps():
+ marimo_lens = pytest.importorskip("marimo_lens")
+ from marimo._session.model import SessionMode
+
+ with mocked_kernel_session(mode=SessionMode.RUN) as session:
+ await session.kernel.run(
+ [ExecuteCellCommand(cell_id="app", code="import marimo as mo")]
+ )
+ assert not session.kernel.errors
+ assert session.kernel.graph.cells["app"].output is None
+ assert marimo_lens.notebook_lens() is None
diff --git a/tests/snapshots/optional-dependencies-recommended.txt b/tests/snapshots/optional-dependencies-recommended.txt
index d20b202daf..9f1b6fed65 100644
--- a/tests/snapshots/optional-dependencies-recommended.txt
+++ b/tests/snapshots/optional-dependencies-recommended.txt
@@ -1,6 +1,6 @@
altair>=5.4.0
cryptography>=42.0.0
-marimo-lens>=0.2.0
+marimo-lens>=0.2.3
marimo[sandbox]
marimo[sql]
nbformat>=5.7.0