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
Add `ctx.packages` namespace to code mode (#9233)
Trevor Manz9798c585bcea
diff --git a/marimo/_code_mode/_context.py b/marimo/_code_mode/_context.pyindex 6a22fe8849..b01e544223 100644--- a/marimo/_code_mode/_context.py+++ b/marimo/_code_mode/_context.py@@ -37,6 +37,11 @@ from marimo._ast.cell import (from marimo._ast.cell_id import CellIdGeneratorfrom marimo._ast.compiler import compile_cellfrom marimo._ast.names import SETUP_CELL_NAME+from marimo._code_mode._packages import (+ Packages,+ _AddPackage,+ _RemovePackage,+)from marimo._code_mode._plan import (_AddOp,_build_plan,@@ -71,7 +76,6 @@ from marimo._runtime.commands import (CommandMessage,DeleteCellCommand,ExecuteCellCommand,- InstallPackagesCommand,UpdateUIElementCommand,)from marimo._runtime.context import get_context as _get_runtime_context@@ -147,6 +151,10 @@ class CellRuntimeState(Protocol):LOGGER = _loggers.marimo_logger()+# Set the first time `ctx.install_packages` (legacy alias) is used in a+# session, so the nudge is printed once per process instead of every call.+_LEGACY_INSTALL_WARNED = False+# ------------------------------------------------------------------# Entry point@@ -573,7 +581,7 @@ class AsyncCodeModeContext:# document prevents collisions with cells already on disk.self._id_generator = CellIdGenerator(seed=None)self._id_generator.seen_ids = set(document.cell_ids)- self._packages_to_install: list[str] = []+ self._packages = Packages(self)self._ui_updates: list[tuple[UIElementId, Any]] = []self._cells_to_run: set[CellId_t] = set()self._entered = False@@ -589,6 +597,24 @@ class AsyncCodeModeContext:"Without 'async with', operations are silently lost.")+ def __getattr__(self, name: str) -> Any:+ # Legacy alias: `ctx.install_packages(...)` was the pre-namespace+ # API. Kept as a hidden shim for in-flight skills / examples;+ # does not appear in dir() or IDE completion. Prefer+ # `ctx.packages.add(...)` in new code.+ if name == "install_packages":+ global _LEGACY_INSTALL_WARNED+ if not _LEGACY_INSTALL_WARNED:+ _LEGACY_INSTALL_WARNED = True+ sys.stderr.write(+ "note: ctx.install_packages() is a legacy alias — "+ "please update to ctx.packages.add()\n"+ )+ return self.packages.add+ raise AttributeError(+ f"{type(self).__name__!r} object has no attribute {name!r}"+ )+# ------------------------------------------------------------------# Async context manager# ------------------------------------------------------------------@@ -596,7 +622,7 @@ class AsyncCodeModeContext:async def __aenter__(self) -> Self:self._ops = []self._pending_adds = {}- self._packages_to_install = []+ self._packages._reset()self._ui_updates = []self._cells_to_run = set()self._entered = True@@ -609,26 +635,20 @@ class AsyncCodeModeContext:exc_tb: TracebackType | None,) -> None:ops = self._ops- packages = self._packages_to_installui_updates = self._ui_updatescells_to_run = self._cells_to_runself._ops = []self._pending_adds = {}- self._packages_to_install = []self._ui_updates = []self._cells_to_run = set()if exc_type is not None:+ self._packages._reset()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: ""})- )+ # Flush queued package ops before cell ops so newly added+ # cells can import newly installed packages.+ package_ops = await self._packages._flush()if ops:_validate_ops(ops)@@ -658,7 +678,7 @@ class AsyncCodeModeContext:)# Print a summary of what was applied.- self._print_summary(ops, packages, ui_updates, cells_to_run)+ self._print_summary(ops, package_ops, ui_updates, cells_to_run)# ------------------------------------------------------------------# Summary@@ -667,15 +687,18 @@ class AsyncCodeModeContext:def _print_summary(self,ops: list[_Op],- packages: list[str],+ package_ops: list[_AddPackage | _RemovePackage],ui_updates: list[tuple[UIElementId, Any]],cells_to_run: set[CellId_t] | None = None,) -> None:"""Print a human-readable summary of applied operations."""lines: list[str] = []- for pkg in packages:- lines.append(f"installed {pkg}")+ for pkg_op in package_ops:+ if isinstance(pkg_op, _AddPackage):+ lines.append(f"installed {pkg_op.package}")+ else:+ lines.append(f"uninstalled {pkg_op.package}")_run = cells_to_run or set()op_cell_ids: set[CellId_t] = set()@@ -768,6 +791,22 @@ class AsyncCodeModeContext:"""return _CellsView(self)+ @property+ def packages(self) -> Packages:+ """Package management for the notebook's Python environment.++ List currently installed packages::++ ctx.packages.list() # -> list[PackageDescription]++ Queue packages to install or remove; mutations flush on exit+ before cell ops so newly added cells can import them::++ ctx.packages.add("pandas", "numpy>=1.26")+ ctx.packages.remove("old-pkg")+ """+ return self._packages+# ------------------------------------------------------------------# Mutation methods (queue ops, applied on __aexit__)# ------------------------------------------------------------------@@ -1383,35 +1422,6 @@ class AsyncCodeModeContext:self._require_entered()self._ui_updates.append((UIElementId(element._id), value))- # ------------------------------------------------------------------- # Package management- # -------------------------------------------------------------------- def install_packages(- self, *packages: str | list[str] | tuple[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")- ctx.install_packages(["altair", "vega_datasets"])- ```-- Args:- *packages: Pip-style package specifiers. Accepts individual- strings, or a list/tuple of strings.- """- self._require_entered()- for pkg in packages:- if isinstance(pkg, (list, tuple)):- self._packages_to_install.extend(pkg)- else:- self._packages_to_install.append(pkg)-# ------------------------------------------------------------------# Low-level primitives# ------------------------------------------------------------------diff --git a/marimo/_code_mode/_packages.py b/marimo/_code_mode/_packages.pynew file mode 100644index 0000000000..96e5fddd95--- /dev/null+++ b/marimo/_code_mode/_packages.py@@ -0,0 +1,272 @@+# Copyright 2026 Marimo. All rights reserved.+"""Packages: queued package operations for ``AsyncCodeModeContext``.++Accessed via :attr:`AsyncCodeModeContext.packages`. Mutations are+queued during the ``async with`` block and flushed on exit *before*+cell operations.+"""++from __future__ import annotations++import asyncio+from dataclasses import dataclass+from typing import TYPE_CHECKING, Any, Literal, Union++from marimo._config.settings import GLOBAL_SETTINGS+from marimo._messaging.notification import (+ InstallingPackageAlertNotification,+ PackageStatusType,+)+from marimo._messaging.notification_utils import broadcast_notification+from marimo._runtime.packages.package_manager import PackageDescription+from marimo._runtime.packages.utils import split_packages++if TYPE_CHECKING:+ from marimo._code_mode._context import AsyncCodeModeContext+++@dataclass(frozen=True, slots=True)+class _AddPackage:+ package: str+++@dataclass(frozen=True, slots=True)+class _RemovePackage:+ package: str+++PackageOp = Union[_AddPackage, _RemovePackage]+# Alias for `list` used in `Packages` annotations; `Packages.list` shadows the+# builtin inside the class scope.+PackageOpList = list[PackageOp]+++def _flatten_packages(+ packages: tuple[str | list[str] | tuple[str, ...], ...],+) -> list[str]:+ """Flatten a mix of strings and lists/tuples of strings."""+ result: list[str] = []+ for pkg in packages:+ if isinstance(pkg, (list, tuple)):+ result.extend(pkg)+ else:+ result.append(pkg)+ return result+++class Packages:+ """Package management for the running notebook's environment.++ Accessed as :attr:`AsyncCodeModeContext.packages`. Mutations are+ queued during the ``async with`` block and flushed on exit *before*+ cell operations, so newly added cells can import newly installed+ packages.++ Examples:+ ```python+ async with cm.get_context() as ctx:+ ctx.packages.add("pandas", "numpy>=1.26")+ ctx.packages.remove("old-package")+ cid = ctx.create_cell("import pandas as pd")+ ctx.run_cell(cid)+ ```++ :meth:`list` returns the currently installed packages and must be+ called before any :meth:`add` or :meth:`remove` in the same batch.+ """++ __slots__ = ("_ctx", "_ops")++ def __init__(self, ctx: AsyncCodeModeContext) -> None:+ self._ctx = ctx+ self._ops: list[PackageOp] = []++ def add(self, *packages: str | list[str] | tuple[str, ...]) -> None:+ """Queue packages for installation on context exit.++ Packages are installed with streaming UI notifications and the+ script metadata is updated for sandboxed notebooks. Cells are+ *not* automatically re-run — use :meth:`run_cell` for that.++ Examples:+ ```python+ ctx.packages.add("pandas")+ ctx.packages.add("polars>=0.20", "numpy==1.26")+ ctx.packages.add(["altair", "vega_datasets"])+ ```++ Args:+ *packages: Pip-style package specifiers. Accepts individual+ strings, or a list/tuple of strings.+ """+ self._ctx._require_entered()+ for pkg in _flatten_packages(packages):+ self._ops.append(_AddPackage(package=pkg))++ def remove(self, *packages: str | list[str] | tuple[str, ...]) -> None:+ """Queue packages for removal on context exit.++ Updates the script metadata for sandboxed notebooks.++ Examples:+ ```python+ ctx.packages.remove("pandas")+ ctx.packages.remove("old-pkg", "another-pkg")+ ctx.packages.remove(["altair", "vega_datasets"])+ ```++ Args:+ *packages: Package names to uninstall. Accepts individual+ strings, or a list/tuple of strings.+ """+ self._ctx._require_entered()+ for pkg in _flatten_packages(packages):+ self._ops.append(_RemovePackage(package=pkg))++ def list(self) -> list[PackageDescription]:+ """Return currently installed packages.++ Raises:+ RuntimeError: If :meth:`add` or :meth:`remove` has already+ been called in this batch. Queued operations haven't+ executed yet, so listing would return stale state.+ Exit the context to flush them first, then start a new+ batch.+ """+ if self._ops:+ raise RuntimeError(+ "Cannot call ctx.packages.list() after add/remove have "+ "been queued — pending operations have not been applied "+ "yet. Exit the context to flush them first, then start "+ "a new batch."+ )+ pm = self._ctx._kernel.packages_callbacks.package_manager+ if pm is None:+ return []+ return pm.list_packages()++ def _reset(self) -> None:+ self._ops = []++ async def _flush(self) -> PackageOpList:+ """Execute queued ops in order. Returns the ops that ran."""+ if not self._ops:+ return []++ ops = self._ops+ self._ops = []++ pm = self._ctx._kernel.packages_callbacks.package_manager+ if pm is None:+ return ops++ if not pm.is_manager_installed():+ pm.alert_not_installed()+ return ops++ source: Literal["kernel", "server"] = "kernel"+ statuses: PackageStatusType = {}+ for op in ops:+ if isinstance(op, _AddPackage):+ statuses[op.package] = "queued"++ if statuses:+ broadcast_notification(+ InstallingPackageAlertNotification(+ packages=statuses, source=source+ ),+ stream=self._ctx._kernel.stream,+ )++ filename = self._ctx._kernel.app_metadata.filename+ manage_metadata = (+ GLOBAL_SETTINGS.MANAGE_SCRIPT_METADATA is True+ and filename is not None+ )++ for op in ops:+ if isinstance(op, _AddPackage):+ await self._run_add(op, pm, statuses, source, manage_metadata)+ else:+ await self._run_remove(op, pm, manage_metadata)++ return ops++ async def _run_add(+ self,+ op: _AddPackage,+ pm: Any,+ statuses: PackageStatusType,+ source: Literal["kernel", "server"],+ manage_metadata: bool,+ ) -> None:+ pkg = op.package+ statuses[pkg] = "installing"+ broadcast_notification(+ InstallingPackageAlertNotification(+ packages=statuses, source=source+ ),+ stream=self._ctx._kernel.stream,+ )+ broadcast_notification(+ InstallingPackageAlertNotification(+ packages=statuses,+ logs={pkg: f"Installing {pkg}...\n"},+ log_status="start",+ source=source,+ ),+ stream=self._ctx._kernel.stream,+ )++ def log_callback(log_line: str) -> None:+ broadcast_notification(+ InstallingPackageAlertNotification(+ packages=statuses,+ logs={pkg: log_line},+ log_status="append",+ source=source,+ ),+ stream=self._ctx._kernel.stream,+ )++ success = await pm.install(+ pkg, version=None, log_callback=log_callback+ )+ if success:+ statuses[pkg] = "installed"+ final_log = f"Successfully installed {pkg}\n"+ if manage_metadata:+ await asyncio.to_thread(+ pm.update_notebook_script_metadata,+ filepath=self._ctx._kernel.app_metadata.filename,+ packages_to_add=split_packages(pkg),+ upgrade=False,+ )+ else:+ statuses[pkg] = "failed"+ final_log = f"Failed to install {pkg}\n"++ broadcast_notification(+ InstallingPackageAlertNotification(+ packages=statuses,+ logs={pkg: final_log},+ log_status="done",+ source=source,+ ),+ stream=self._ctx._kernel.stream,+ )++ async def _run_remove(+ self,+ op: _RemovePackage,+ pm: Any,+ manage_metadata: bool,+ ) -> None:+ success = await pm.uninstall(op.package)+ if success and manage_metadata:+ await asyncio.to_thread(+ pm.update_notebook_script_metadata,+ filepath=self._ctx._kernel.app_metadata.filename,+ packages_to_remove=split_packages(op.package),+ upgrade=False,+ )diff --git a/tests/_code_mode/test_context.py b/tests/_code_mode/test_context.pyindex 9e3c5b758d..2a8f5be5bd 100644--- a/tests/_code_mode/test_context.py+++ b/tests/_code_mode/test_context.py@@ -24,6 +24,7 @@ from marimo._messaging.notification import (NotebookDocumentTransactionNotification,)from marimo._runtime.commands import ExecuteCellCommand+from marimo._runtime.packages.package_manager import PackageDescriptionfrom marimo._runtime.runtime import Kernelfrom marimo._types.ids import CellId_t@@ -586,8 +587,15 @@ class TestResolveTarget:assert reorder["cellIds"][2] == "1"-class TestInstallPackages:- async def test_install_single(self, k: Kernel) -> None:+class TestPackages:+ """Tests for the ctx.packages namespace (Packages class)."""++ async def test_packages_property_exists(self, k: Kernel) -> None:+ with _ctx(k) as ctx:+ async with ctx as nb:+ assert nb.packages is not None++ async def test_add_single(self, k: Kernel) -> None:with _ctx(k) as ctx:pm = k.packages_callbacks.package_managerassert pm is not None@@ -595,16 +603,105 @@ class TestInstallPackages:with patch.object(pm, "install", new_callable=AsyncMock, return_value=True) as mock_install:- async with ctx:- ctx.install_packages("pandas")+ async with ctx as nb:+ nb.packages.add("pandas")# Not installed yet — still queued.assert mock_install.call_count == 0assert mock_install.call_count == 1assert 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:+ async def test_add_multiple(self, k: Kernel) -> None:+ with _ctx(k) as ctx:+ 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 as nb:+ nb.packages.add("pandas", "numpy>=1.26")++ assert mock_install.call_count == 2+ installed = [call.args[0] for call in mock_install.call_args_list]+ assert "pandas" in installed+ assert "numpy>=1.26" in installed++ async def test_add_queued_before_cell_ops(self, k: Kernel) -> None:+ """Packages are installed before cell ops so imports work."""+ with _ctx(k) as ctx:+ pm = k.packages_callbacks.package_manager+ assert pm is not None++ call_order: list[str] = []++ async def tracking_install(+ package: str, **_kwargs: object+ ) -> bool:+ del package+ call_order.append("install")+ return True++ with patch.object(pm, "install", side_effect=tracking_install):+ async with ctx as nb:+ nb.packages.add("pandas")+ cid = nb.create_cell("import pandas")+ nb.run_cell(cid)++ # install should have been called (packages flush before cells)+ assert "install" in call_order++ async def test_remove_single(self, k: Kernel) -> None:+ with _ctx(k) as ctx:+ pm = k.packages_callbacks.package_manager+ assert pm is not None++ with patch.object(+ pm, "uninstall", new_callable=AsyncMock, return_value=True+ ) as mock_uninstall:+ async with ctx as nb:+ nb.packages.remove("pandas")+ # Not removed yet — still queued.+ assert mock_uninstall.call_count == 0++ assert mock_uninstall.call_count == 1+ assert mock_uninstall.call_args_list[0].args[0] == "pandas"++ async def test_remove_multiple(self, k: Kernel) -> None:+ with _ctx(k) as ctx:+ pm = k.packages_callbacks.package_manager+ assert pm is not None++ with patch.object(+ pm, "uninstall", new_callable=AsyncMock, return_value=True+ ) as mock_uninstall:+ async with ctx as nb:+ nb.packages.remove("pandas", "numpy")++ assert mock_uninstall.call_count == 2+ removed = [call.args[0] for call in mock_uninstall.call_args_list]+ assert "pandas" in removed+ assert "numpy" in removed++ async def test_add_accepts_list(self, k: Kernel) -> None:+ """add() accepts a list of package names."""+ with _ctx(k) as ctx:+ 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 as nb:+ nb.packages.add(["pandas", "numpy>=1.26"])++ assert mock_install.call_count == 2+ installed = [call.args[0] for call in mock_install.call_args_list]+ assert "pandas" in installed+ assert "numpy>=1.26" in installed++ async def test_add_mixes_strings_and_lists(self, k: Kernel) -> None:+ """add() accepts a mix of strings and lists."""with _ctx(k) as ctx:pm = k.packages_callbacks.package_managerassert pm is not None@@ -612,19 +709,184 @@ class TestInstallPackages: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"] == ""+ async with ctx as nb:+ nb.packages.add("polars", ["pandas", "numpy"])++ assert mock_install.call_count == 3+ installed = [call.args[0] for call in mock_install.call_args_list]+ assert set(installed) == {"polars", "pandas", "numpy"}++ async def test_remove_accepts_list(self, k: Kernel) -> None:+ """remove() accepts a list of package names."""+ with _ctx(k) as ctx:+ pm = k.packages_callbacks.package_manager+ assert pm is not None++ with patch.object(+ pm, "uninstall", new_callable=AsyncMock, return_value=True+ ) as mock_uninstall:+ async with ctx as nb:+ nb.packages.remove(["pandas", "numpy"])++ assert mock_uninstall.call_count == 2+ removed = [call.args[0] for call in mock_uninstall.call_args_list]+ assert "pandas" in removed+ assert "numpy" in removed++ async def test_list_returns_installed_packages(self, k: Kernel) -> None:+ with _ctx(k) as ctx:+ pm = k.packages_callbacks.package_manager+ assert pm is not None++ mock_packages = [+ PackageDescription(name="pandas", version="2.1.0"),+ PackageDescription(name="numpy", version="1.26.0"),+ ]+ with patch.object(pm, "list_packages", return_value=mock_packages):+ async with ctx as nb:+ result = nb.packages.list()++ assert len(result) == 2+ assert result[0].name == "pandas"+ assert result[1].name == "numpy"++ async def test_list_errors_after_add(self, k: Kernel) -> None:+ """list() raises after add() has been called in the same batch."""+ with _ctx(k) as ctx:+ async with ctx as nb:+ nb.packages.add("pandas")+ with pytest.raises(RuntimeError):+ nb.packages.list()++ async def test_list_errors_after_remove(self, k: Kernel) -> None:+ """list() raises after remove() has been called in the same batch."""+ with _ctx(k) as ctx:+ async with ctx as nb:+ nb.packages.remove("pandas")+ with pytest.raises(RuntimeError):+ nb.packages.list()++ async def test_add_and_remove_in_same_batch(self, k: Kernel) -> None:+ """add and remove can coexist in the same batch, executed in order."""+ with _ctx(k) as ctx:+ pm = k.packages_callbacks.package_manager+ assert pm is not None++ call_order: list[tuple[str, str]] = []++ async def track_install(package: str, **_kwargs: object) -> bool:+ call_order.append(("add", package))+ return True++ async def track_uninstall(package: str, **_kwargs: object) -> bool:+ call_order.append(("remove", package))+ return True++ with (+ patch.object(pm, "install", side_effect=track_install),+ patch.object(pm, "uninstall", side_effect=track_uninstall),+ ):+ async with ctx as nb:+ nb.packages.add("polars")+ nb.packages.remove("pandas")++ assert call_order == [("add", "polars"), ("remove", "pandas")]++ async def test_exception_discards_package_ops(self, k: Kernel) -> None:+ """If an exception occurs, queued package ops are discarded."""+ with _ctx(k) as ctx:+ 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:+ try:+ async with ctx as nb:+ nb.packages.add("pandas")+ raise ValueError("oops")+ except ValueError:+ pass++ assert mock_install.call_count == 0++ async def test_noop_packages(self, k: Kernel) -> None:+ """No package ops means nothing happens."""+ with _ctx(k) as ctx:+ pm = k.packages_callbacks.package_manager+ assert pm is not None++ with (+ patch.object(+ pm, "install", new_callable=AsyncMock+ ) as mock_install,+ patch.object(+ pm, "uninstall", new_callable=AsyncMock+ ) as mock_uninstall,+ ):+ async with ctx as nb:+ pass++ assert mock_install.call_count == 0+ assert mock_uninstall.call_count == 0++ async def test_legacy_install_packages_alias(+ self, k: Kernel, capsys: pytest.CaptureFixture[str]+ ) -> None:+ """ctx.install_packages() still works as a hidden alias for+ ctx.packages.add() and nudges the caller on first use per+ session, so skills referencing the old name keep working."""+ from marimo._code_mode import _context as _ctx_mod++ # Reset the once-per-session flag so this test sees the nudge.+ _ctx_mod._LEGACY_INSTALL_WARNED = False++ with _ctx(k) as ctx:+ 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 as nb:+ # Invoked via __getattr__+ nb.install_packages("pandas", ["numpy", "polars"])+ # Second call in the same session — should not nudge+ # again.+ nb.install_packages("requests")++ assert mock_install.call_count == 4+ installed = [call.args[0] for call in mock_install.call_args_list]+ assert set(installed) == {"pandas", "numpy", "polars", "requests"}++ # The nudge is written to stderr exactly once.+ captured = capsys.readouterr()+ assert captured.err.count("legacy alias") == 1+ assert "ctx.packages.add()" in captured.err++ async def test_legacy_install_packages_not_in_dir(self, k: Kernel) -> None:+ """The alias is reachable via attribute access but hidden from+ dir() so it doesn't pollute IDE completion or the public API."""+ with _ctx(k) as ctx:+ async with ctx as nb:+ assert "install_packages" not in dir(nb)++ async def test_summary_includes_packages(+ self, k: Kernel, capsys: object+ ) -> None:+ """Package operations appear in the printed summary."""+ with _ctx(k) as ctx:+ pm = k.packages_callbacks.package_manager+ assert pm is not None++ with patch.object(+ pm, "install", new_callable=AsyncMock, return_value=True+ ):+ async with ctx as nb:+ nb.packages.add("pandas")++ captured = capsys.readouterr() # type: ignore[attr-defined]+ assert "pandas" in captured.outclass TestAutorunStaleState: