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: tag install location on ModuleNotFound to distinguish installation on server vs kernel (#8619)
Dylan Madisetti04842a364d9d
diff --git a/frontend/src/components/editor/package-alert.tsx b/frontend/src/components/editor/package-alert.tsxindex 9323b53ff7..35f3e1bece 100644--- a/frontend/src/components/editor/package-alert.tsx+++ b/frontend/src/components/editor/package-alert.tsx@@ -174,6 +174,7 @@ export const PackageAlert: React.FC = () => {})}versions={desiredPackageVersions}clearPackageAlert={() => clearPackageAlert(packageAlert.id)}+ source={packageAlert.source}/>{!isWasm() && (@@ -323,11 +324,13 @@ const InstallPackagesButton = ({packages,versions,clearPackageAlert,+ source,}: {manager: PackageManagerName;packages: string[];versions: Record<string, string>;clearPackageAlert: () => void;+ source?: "kernel" | "server";}) => {const { sendInstallMissingPackages } = useRequestClient();return (@@ -347,6 +350,7 @@ const InstallPackagesButton = ({await sendInstallMissingPackages({manager,versions: completePackages,+ source,}).catch((error) => {Logger.error(error);});diff --git a/frontend/src/core/alerts/state.ts b/frontend/src/core/alerts/state.tsindex fdb0e0ffc5..663056e05f 100644--- a/frontend/src/core/alerts/state.ts+++ b/frontend/src/core/alerts/state.ts@@ -11,6 +11,7 @@ export interface MissingPackageAlert {kind: "missing";packages: string[];isolated: boolean;+ source?: "kernel" | "server";}export interface InstallingPackageAlert {diff --git a/marimo/_cli/export/commands.py b/marimo/_cli/export/commands.pyindex 54d3868d74..36bf887059 100644--- a/marimo/_cli/export/commands.py+++ b/marimo/_cli/export/commands.py@@ -681,6 +681,7 @@ def pdf("for PDF export",DependencyManager.nbformat,DependencyManager.nbconvert,+ source="server",)except ManyModulesNotFoundError as e:sandbox_rerun_command = (diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.pyindex ba14355739..a3637b633a 100644--- a/marimo/_dependencies/dependencies.py+++ b/marimo/_dependencies/dependencies.py@@ -6,6 +6,7 @@ import importlib.utilimport shutilimport sysfrom dataclasses import dataclass+from typing import Literalfrom marimo._dependencies.errors import ManyModulesNotFoundError@@ -284,7 +285,11 @@ class DependencyManager:return shutil.which(pkg) is not None@staticmethod- def require_many(why: str, *dependencies: Dependency) -> None:+ def require_many(+ why: str,+ *dependencies: Dependency,+ source: Literal["kernel", "server"],+ ) -> None:missing = [dep.pkg_name_to_installfor dep in dependencies@@ -294,4 +299,5 @@ class DependencyManager:raise ManyModulesNotFoundError(missing,f"The following packages are required {why}: {', '.join(missing)}",+ source=source,)diff --git a/marimo/_dependencies/errors.py b/marimo/_dependencies/errors.pyindex 1723efaf3f..27021bba30 100644--- a/marimo/_dependencies/errors.py+++ b/marimo/_dependencies/errors.py@@ -1,6 +1,8 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations+from typing import Literal+class ManyModulesNotFoundError(ModuleNotFoundError):"""@@ -8,7 +10,14 @@ class ManyModulesNotFoundError(ModuleNotFoundError):"""package_names: list[str]+ source: Literal["kernel", "server"]- def __init__(self, package_names: list[str], msg: str) -> None:+ def __init__(+ self,+ package_names: list[str],+ msg: str,+ source: Literal["kernel", "server"],+ ) -> None:self.package_names = package_names+ self.source = sourcesuper().__init__(msg)diff --git a/marimo/_messaging/notification.py b/marimo/_messaging/notification.pyindex 57f52fa53d..94fb16d71d 100644--- a/marimo/_messaging/notification.py+++ b/marimo/_messaging/notification.py@@ -336,12 +336,16 @@ class MissingPackageAlertNotification(Attributes:packages: Missing package names.- isolated: Whether in isolated environment.+ isolated: Whether auto-install is possible in this environment.+ source: Which Python environment to install into. "kernel" (default)+ installs in the kernel's venv; "server" installs in the+ server's own Python env (e.g. for formatter tools like ruff)."""name: ClassVar[str] = "missing-package-alert"packages: list[str]isolated: bool+ source: Literal["kernel", "server"] = "kernel"# package name => installation statusdiff --git a/marimo/_runtime/commands.py b/marimo/_runtime/commands.pyindex e0243d7219..2c92acbf50 100644--- a/marimo/_runtime/commands.py+++ b/marimo/_runtime/commands.py@@ -9,6 +9,7 @@ from dataclasses import dataclassfrom typing import (TYPE_CHECKING,Any,+ Literal,Optional,TypeVar,Union,@@ -555,6 +556,10 @@ class InstallPackagesCommand(Command):manager: Package manager to use ('pip', 'conda', 'uv', etc.).versions: Package names mapped to version specifiers. Empty versionmeans install latest.+ source: Where to install. "kernel" (default) dispatches to the kernel+ subprocess; "server" installs directly into the server's Python+ environment (sys.executable), used when the server itself needs+ a package (e.g. nbformat for IPYNB auto-export in sandbox mode)."""# TODO: index URL (index/channel/...)@@ -565,6 +570,8 @@ class InstallPackagesCommand(Command):# will be installedversions: dict[str, str]+ source: Literal["kernel", "server"] = "kernel"+class PreviewDatasetColumnCommand(Command):"""Preview a dataset column.diff --git a/marimo/_server/ai/providers.py b/marimo/_server/ai/providers.pyindex 34bd355421..f3a72c86e1 100644--- a/marimo/_server/ai/providers.py+++ b/marimo/_server/ai/providers.py@@ -96,7 +96,10 @@ class PydanticProvider(ABC, Generic[ProviderT]):deps: The dependencies to require."""DependencyManager.require_many(- "for AI assistance", DependencyManager.pydantic_ai, *(deps or [])+ "for AI assistance",+ DependencyManager.pydantic_ai,+ *(deps or []),+ source="server",)self.model = modeldiff --git a/marimo/_server/api/endpoints/editing.py b/marimo/_server/api/endpoints/editing.pyindex cd701f50dd..25dacf035b 100644--- a/marimo/_server/api/endpoints/editing.py+++ b/marimo/_server/api/endpoints/editing.py@@ -8,7 +8,12 @@ from starlette.authentication import requiresfrom marimo._cli.sandbox import SandboxModefrom marimo._messaging.notification import UpdateCellIdsNotificationfrom marimo._server.api.deps import AppState-from marimo._server.api.utils import dispatch_control_request, parse_request+from marimo._server.api.utils import (+ dispatch_control_request,+ install_packages_on_server,+ notify_server_missing_packages,+ parse_request,+)from marimo._server.models.models import (BaseResponse,CodeCompletionRequest,@@ -146,13 +151,25 @@ async def format_cell(request: Request) -> FormatResponse:))except ModuleNotFoundError:- # Installation occurs in the kernel which is not useful for multi mode.+ # In multi-sandbox mode each kernel has its own venv, so installing+ # ruff into the server wouldn't help the kernel. Just surface the+ # error without an install prompt.if app_state.session_manager.sandbox_mode is SandboxMode.MULTI:- # Re-raise without name so error handler won't send install notificationraise ModuleNotFoundError("Server does not have a formatter. Please install ruff") from None- raise+ # For single-sandbox and non-sandbox modes the server *is* the+ # formatting environment, so offer to install ruff there.+ notify_server_missing_packages(+ app_state.get_current_session(),+ app_state.get_current_session_id(),+ ["ruff"],+ )+ # Re-raise without .name so the error handler returns 500 without+ # sending a duplicate notification.+ raise ModuleNotFoundError(+ "Server does not have a formatter. Please install ruff"+ ) from None@router.post("/set_cell_config")@@ -234,4 +251,17 @@ async def install_missing_packages(request: Request) -> BaseResponse:schema:$ref: "#/components/schemas/SuccessResponse""""- return await dispatch_control_request(request, InstallPackagesRequest)+ body = await parse_request(request, cls=InstallPackagesRequest)+ cmd = body.as_command()++ if cmd.source == "server":+ # Install into the server's own Python environment (sys.executable).+ # Used when the server itself needs a package (e.g. nbformat for+ # IPYNB auto-export when running with --sandbox).+ app_state = AppState(request)+ app_state.require_current_session()+ await install_packages_on_server(cmd.manager, cmd.versions)+ return SuccessResponse()++ # Default ("kernel"): dispatch to kernel via ZeroMQ control queue.+ return await dispatch_control_request(request, cmd)diff --git a/marimo/_server/api/endpoints/export.py b/marimo/_server/api/endpoints/export.pyindex 0833f18352..1500f79f70 100644--- a/marimo/_server/api/endpoints/export.py+++ b/marimo/_server/api/endpoints/export.py@@ -23,7 +23,10 @@ from marimo._convert.script import convert_from_ir_to_scriptfrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._messaging.msgspec_encoder import asdictfrom marimo._server.api.deps import AppState-from marimo._server.api.utils import parse_request+from marimo._server.api.utils import (+ notify_server_missing_packages,+ parse_request,+)from marimo._server.export.exporter import AutoExporter, Exporterfrom marimo._server.models.export import (ExportAsHTMLRequest,@@ -457,12 +460,19 @@ async def auto_export_as_ipynb(LOGGER.debug("Already auto-exported to IPYNB")return PlainTextResponse(status_code=HTTPStatus.NOT_MODIFIED)- async def _background_export() -> None:- # Check has nbformat installed- if not DependencyManager.nbformat.has():- LOGGER.error("Cannot snapshot to IPYNB: nbformat not installed")- return+ # Check nbformat before scheduling background task. Alert at most once+ # per session so the notification doesn't keep popping up on every save.+ if not DependencyManager.nbformat.has():+ LOGGER.warning("Cannot snapshot to IPYNB: nbformat not installed")+ if "nbformat" not in session_view.notified_server_packages:+ notify_server_missing_packages(+ session, app_state.get_current_session_id(), ["nbformat"]+ )+ session_view.notified_server_packages.add("nbformat")+ session_view.mark_auto_export_ipynb()+ return PlainTextResponse(status_code=HTTPStatus.NOT_MODIFIED)+ async def _background_export() -> None:# Reload the file manager to get the latest statesession.app_file_manager.reload()diff --git a/marimo/_server/api/utils.py b/marimo/_server/api/utils.pyindex 94694fc817..3df658cdd1 100644--- a/marimo/_server/api/utils.py+++ b/marimo/_server/api/utils.py@@ -23,6 +23,8 @@ from marimo._utils.parse_dataclass import parse_rawif TYPE_CHECKING:from starlette.requests import Request+ from marimo._session.session import Session+async def parse_request(request: Request, cls: type[T], allow_unknown_keys: bool = False@@ -104,3 +106,52 @@ def open_url_in_browser(browser: str, url: str) -> None:T = TypeVar("T")+++async def install_packages_on_server(+ manager: str,+ versions: dict[str, str],+) -> None:+ """Install packages into the server's own Python environment.++ Used when the server itself needs a package (e.g. nbformat for+ IPYNB auto-export when running with --sandbox).+ """+ import sys++ from marimo._runtime.packages.package_managers import (+ create_package_manager,+ )++ pkg_manager = create_package_manager(manager, python_exe=sys.executable)+ if not pkg_manager.is_manager_installed():+ pkg_manager.alert_not_installed()+ return+ for pkg, version in versions.items():+ await pkg_manager.install(pkg, version=version or None)+++def notify_server_missing_packages(+ session: Session | None,+ session_id: str | None,+ packages: list[str],+) -> None:+ """Send a missing-package alert for a server-side package.++ Uses isolated=True so the install button always appears regardless of+ whether the server is in a virtual environment.+ """+ if session_id is None or session is None:+ return+ from marimo._messaging.notification import MissingPackageAlertNotification+ from marimo._session.utils import send_message_to_consumer++ send_message_to_consumer(+ session=session,+ operation=MissingPackageAlertNotification(+ packages=packages,+ isolated=True,+ source="server",+ ),+ consumer_id=ConsumerId(session_id),+ )diff --git a/marimo/_server/errors.py b/marimo/_server/errors.pyindex a83e9f69cf..66a6b6398b 100644--- a/marimo/_server/errors.py+++ b/marimo/_server/errors.py@@ -88,17 +88,23 @@ async def handle_error(request: Request, response: Any) -> Any:):if isinstance(response, ManyModulesNotFoundError):packages = response.package_names+ source = response.sourceelif isinstance(response, ModuleNotFoundError):if not response.name:return JSONResponse({"detail": str(response)}, status_code=500)packages = [response.name]+ source = "kernel"+ # TODO(dmadisetti): Consider checking if the server is in a virtual environment+ # and if so, set isolated to False.+ isolated = True if source == "server" else is_python_isolated()send_message_to_consumer(session=session,operation=MissingPackageAlertNotification(packages=packages,- isolated=is_python_isolated(),+ isolated=isolated,+ source=source,),consumer_id=ConsumerId(session_id),)diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.pyindex e410ad36c2..192a14d846 100644--- a/marimo/_server/export/exporter.py+++ b/marimo/_server/export/exporter.py@@ -346,6 +346,7 @@ class Exporter:DependencyManager.nbformat,DependencyManager.nbconvert,DependencyManager.playwright,+ source="server",)ipynb_json_str = self.export_as_ipynb(@@ -449,6 +450,7 @@ class Exporter:DependencyManager.nbformat,DependencyManager.nbconvert,DependencyManager.playwright,+ source="server",)ipynb_json_str = self.export_as_ipynb(diff --git a/marimo/_server/models/models.py b/marimo/_server/models/models.pyindex a4060ee48f..edb861b4a3 100644--- a/marimo/_server/models/models.py+++ b/marimo/_server/models/models.py@@ -170,7 +170,7 @@ class DeleteCellRequest(DeleteCellCommand, tag=False):class InstallPackagesRequest(InstallPackagesCommand, tag=False):def as_command(self) -> InstallPackagesCommand:return InstallPackagesCommand(- manager=self.manager, versions=self.versions+ manager=self.manager, versions=self.versions, source=self.source)diff --git a/marimo/_session/managers/ipc.py b/marimo/_session/managers/ipc.pyindex c4d8b11ae8..3af4e93232 100644--- a/marimo/_session/managers/ipc.py+++ b/marimo/_session/managers/ipc.py@@ -11,6 +11,7 @@ import osimport signalimport subprocessimport sys+from pathlib import Pathfrom typing import TYPE_CHECKING, Optional, Union, castfrom marimo import _loggers@@ -128,6 +129,52 @@ class IPCQueueManagerImpl(QueueManager):self.input_queue.put(text)+def construct_kernel_env(+ base_env: dict[str, str],+ venv_python: str,+ *,+ is_ephemeral_sandbox: bool,+ writable: bool,+ kernel_pythonpath: str | None = None,+) -> dict[str, str]:+ """Build environment variables for a kernel subprocess.++ Args:+ base_env: Starting environment (typically ``os.environ.copy()``).+ venv_python: Path to the Python executable in the target venv.+ is_ephemeral_sandbox: Whether this is an ephemeral sandbox venv+ built by ``build_sandbox_venv``.+ writable: Whether the kernel venv supports package installs.+ kernel_pythonpath: Extra PYTHONPATH entries for read-only+ configured venvs that don't have marimo installed.++ Returns:+ A **new** dict with the appropriate overrides applied.+ """+ env = dict(base_env)++ if kernel_pythonpath is not None:+ existing = env.get("PYTHONPATH", "")+ if existing:+ env["PYTHONPATH"] = f"{kernel_pythonpath}{os.pathsep}{existing}"+ else:+ env["PYTHONPATH"] = kernel_pythonpath++ if is_ephemeral_sandbox:+ # Override UV env vars so the kernel subprocess sees the sandbox+ # venv as its environment, not the outer uv project.+ env["VIRTUAL_ENV"] = str(Path(venv_python).parent.parent)+ env.pop("UV_PROJECT_ENVIRONMENT", None)++ if writable:+ # Setting this attempts to make auto-installations work even if+ # other normally detected criteria are not true.+ # IPC by itself does not seem to trigger them.+ env["MARIMO_MANAGE_SCRIPT_METADATA"] = "true"++ return env++class IPCKernelManagerImpl(KernelManager):"""IPC-based kernel manager to spawn sandboxed kernels.@@ -177,8 +224,6 @@ class IPCKernelManagerImpl(KernelManager):redirect_console_to_browser=self.redirect_console_to_browser,)- env = os.environ.copy()-venv_config = _get_venv_config(self.config_manager)try:configured_python = get_configured_venv_python(@@ -190,6 +235,8 @@ class IPCKernelManagerImpl(KernelManager):# Ephemeral sandboxes are always writable; configured venvs respect the# flag.writable = True+ is_ephemeral_sandbox = False+ kernel_pythonpath: str | None = None# An explicitly configured venv takes precedence over an ephemeral# sandbox.@@ -233,18 +280,14 @@ class IPCKernelManagerImpl(KernelManager):# Inject PYTHONPATH for marimo and dependencies from the# current runtime as a last chance effort to expose marimo# to the kernel.- kernel_path = get_kernel_pythonpath()- existing = env.get("PYTHONPATH", "")- if existing:- env["PYTHONPATH"] = f"{kernel_path}{os.pathsep}{existing}"- else:- env["PYTHONPATH"] = kernel_path+ kernel_pythonpath = get_kernel_pythonpath()else:# Fall back to building ephemeral sandbox venv# with IPC dependencies.# NB. "Ephemeral" sandboxes (or rather tmp sandboxes built by uv)# are always writable, and as such install marimo as a default,# making them much easier than a configured venv we cannot manage.+ is_ephemeral_sandbox = Truetry:self._sandbox_dir, venv_python = build_sandbox_venv(self.app_metadata.filename,@@ -264,12 +307,15 @@ class IPCKernelManagerImpl(KernelManager):# Store the venv python for package manager targetingself._venv_python = venv_python+ env = construct_kernel_env(+ base_env=os.environ.copy(),+ venv_python=venv_python,+ is_ephemeral_sandbox=is_ephemeral_sandbox,+ writable=writable,+ kernel_pythonpath=kernel_pythonpath,+ )+cmd = [venv_python, "-m", "marimo._ipc.launch_kernel"]- if writable:- # Setting this attempts to make auto-installations work even if- # other normally detected criteria are not true.- # IPC by itself does not seem to trigger them.- env["MARIMO_MANAGE_SCRIPT_METADATA"] = "true"LOGGER.debug(f"Launching kernel: {' '.join(cmd)}")diff --git a/marimo/_session/state/session_view.py b/marimo/_session/state/session_view.pyindex efd713e92c..7a1608aed5 100644--- a/marimo/_session/state/session_view.py+++ b/marimo/_session/state/session_view.py@@ -186,6 +186,10 @@ class SessionView:str, str] = {} # package name -> accumulated logs+ # Server-side missing-package alerts already sent this session.+ # NOT reset by _touch() — once alerted we don't re-alert.+ self.notified_server_packages: set[str] = set()+# Auto-savingself.auto_export_state = AutoExportState()diff --git a/marimo/_smoke_tests/server_package_alerts.py b/marimo/_smoke_tests/server_package_alerts.pynew file mode 100644index 0000000000..ee3a0f00a6--- /dev/null+++ b/marimo/_smoke_tests/server_package_alerts.py@@ -0,0 +1,91 @@+# /// script+# requires-python = ">=3.13"+# dependencies = [+# "marimo>=0.20.4",+# ]+# ///++# Copyright 2026 Marimo. All rights reserved.+"""Smoke test for server-side package alerts (PR #8619).++Tests that missing-package alerts for server-side tools (ruff, nbformat)+correctly show the Install button and fire at most once per save.++SETUP:+ pip uninstall ruff nbformat -y++SCENARIOS:+ 1. Format alert - press Shift+Enter (format) → expect "Missing packages: ruff" banner with Install+ 2. IPYNB alert - enable auto-export IPYNB, save (Ctrl+S) → expect "Missing packages: nbformat" banner+ 3. Once per save - save again immediately → banner should NOT appear a second time++TEARDOWN:+ pip install ruff nbformat+"""++import marimo++__generated_with = "0.20.4"+app = marimo.App(auto_download=["ipynb"])+++def _():+ import marimo as mo++ return (mo,)+++def _():+ import matplotlib.pyplot as plt++ return+++def _(mo):+ mo.md("""+ # Server Package Alert Smoke Test++ ## What to verify++ ### Scenario 1 — ruff missing alert+ 1. Uninstall ruff: run `pip uninstall ruff -y` in your shell+ 2. Click **Format** (Shift+Enter) on this cell+ 3. ✅ Expect: red "Missing packages" banner appears with **ruff** listed and an **Install** button+ 4. ✅ The Install button should always appear (regardless of whether you're in a venv)++ ### Scenario 2 — nbformat missing, alert appears automatically+ 1. Uninstall nbformat: run `pip uninstall nbformat -y` in your shell+ 2. Wait up to 5 seconds (auto-export runs on a 5-second interval)+ 3. ✅ Expect: "Missing packages: nbformat" banner with Install button appears++ ### Scenario 3 — install into server env+ 1. From the nbformat alert banner, click **Install**+ 2. ✅ Expect: nbformat installs into the *server* Python environment+ 3. Save again (Ctrl+S)+ 4. ✅ Expect: auto-export to `.marimo/server_package_alerts.ipynb` succeeds (no more banner)++ ### Scenario 4 — sandbox mode+ ```+ marimo edit --sandbox marimo/_smoke_tests/server_package_alerts.py+ ```+ 1. Uninstall nbformat inside the sandbox: `uv pip uninstall nbformat`+ 2. Save → ✅ Expect: nbformat banner with Install button appears+ 3. Click Install → ✅ Expect: installs into the sandbox env successfully+ """)+ return+++def _(mo):+ # A cell with code to format — press Shift+Enter to trigger the ruff alert+ x = 1 + 1+ y = x * 2+ mo.md(f"Result: {y}")+ return+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_sql/sql.py b/marimo/_sql/sql.pyindex 8603faaac9..6d8d3b284c 100644--- a/marimo/_sql/sql.py+++ b/marimo/_sql/sql.py@@ -65,6 +65,7 @@ def sql("to execute sql",DependencyManager.duckdb,DependencyManager.sqlglot,+ source="kernel",)sql_engine = DuckDBEngine(connection=None)else:diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yamlindex af13d064af..39a3af0d92 100644--- a/packages/openapi/api.yaml+++ b/packages/openapi/api.yaml@@ -2020,10 +2020,20 @@ components:\ the specified package manager. Triggered\n automatically on import errors\\ or manually by the user.\n\n Attributes:\n manager: Package manager\\ to use ('pip', 'conda', 'uv', etc.).\n versions: Package names mapped\- \ to version specifiers. Empty version\n means install latest."+ \ to version specifiers. Empty version\n means install latest.\n\+ \ source: Where to install. \"kernel\" (default) dispatches to the\+ \ kernel\n subprocess; \"server\" installs directly into the\+ \ server's Python\n environment (sys.executable), used when\+ \ the server itself needs\n a package (e.g. nbformat for IPYNB\+ \ auto-export in sandbox mode)."properties:manager:type: string+ source:+ default: kernel+ enum:+ - kernel+ - servertype:enum:- install-packages@@ -2041,6 +2051,11 @@ components:properties:manager:type: string+ source:+ default: kernel+ enum:+ - kernel+ - serverversions:additionalProperties:type: string@@ -3053,8 +3068,11 @@ components:type: objectMissingPackageAlertNotification:description: "Alert for missing packages with install option.\n\n Attributes:\n\- \ packages: Missing package names.\n isolated: Whether in isolated\- \ environment."+ \ packages: Missing package names.\n isolated: Whether auto-install\+ \ is possible in this environment.\n source: Which Python environment\+ \ to install into. \"kernel\" (default)\n installs in the kernel's\+ \ venv; \"server\" installs in the\n server's own Python env\+ \ (e.g. for formatter tools like ruff)."properties:isolated:type: boolean@@ -3065,6 +3083,11 @@ components:items:type: stringtype: array+ source:+ default: kernel+ enum:+ - kernel+ - serverrequired:- op- packagesdiff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.tsindex bc44193ee5..c222776aa1 100644--- a/packages/openapi/src/api.ts+++ b/packages/openapi/src/api.ts@@ -4419,9 +4419,18 @@ export interface components {* manager: Package manager to use ('pip', 'conda', 'uv', etc.).* versions: Package names mapped to version specifiers. Empty version* means install latest.+ * source: Where to install. "kernel" (default) dispatches to the kernel+ * subprocess; "server" installs directly into the server's Python+ * environment (sys.executable), used when the server itself needs+ * a package (e.g. nbformat for IPYNB auto-export in sandbox mode).*/InstallPackagesCommand: {manager: string;+ /**+ * @default kernel+ * @enum {unknown}+ */+ source?: "kernel" | "server";/** @enum {unknown} */type: "install-packages";versions: {@@ -4431,6 +4440,11 @@ export interface components {/** InstallPackagesRequest */InstallPackagesRequest: {manager: string;+ /**+ * @default kernel+ * @enum {unknown}+ */+ source?: "kernel" | "server";versions: {[key: string]: string;};@@ -5006,13 +5020,21 @@ export interface components {** Attributes:* packages: Missing package names.- * isolated: Whether in isolated environment.+ * isolated: Whether auto-install is possible in this environment.+ * source: Which Python environment to install into. "kernel" (default)+ * installs in the kernel's venv; "server" installs in the+ * server's own Python env (e.g. for formatter tools like ruff).*/MissingPackageAlertNotification: {isolated: boolean;/** @enum {unknown} */op: "missing-package-alert";packages: string[];+ /**+ * @default kernel+ * @enum {unknown}+ */+ source?: "kernel" | "server";};/*** ModelClosediff --git a/tests/_dependencies/test_dependencies.py b/tests/_dependencies/test_dependencies.pyindex c5b002c9b0..967182dada 100644--- a/tests/_dependencies/test_dependencies.py+++ b/tests/_dependencies/test_dependencies.py@@ -244,6 +244,7 @@ def test_require_many() -> None:"for testing multiple dependencies",missing1,missing2,+ source="kernel",)assert excinfo.value.package_names == ["missing1", "missing2"]@@ -264,6 +265,7 @@ def test_require_many_uses_package_name() -> None:"for testing package names",missing1,missing2,+ source="kernel",)# Should use package_name, not pkg@@ -279,6 +281,7 @@ def test_require_many_uses_package_name() -> None:"for testing mixed dependencies",DependencyManager.pandas,missing1,+ source="kernel",)assert excinfo.value.package_names == ["missing-package-1"]@@ -286,6 +289,8 @@ def test_require_many_uses_package_name() -> None:# Test with all dependencies availableresult = DependencyManager.require_many(- "for testing available dependencies", DependencyManager.pandas+ "for testing available dependencies",+ DependencyManager.pandas,+ source="kernel",)assert result is Nonediff --git a/tests/_runtime/test_manage_script_metadata.py b/tests/_runtime/test_manage_script_metadata.pyindex d20d4b0781..c57ccbcd2d 100644--- a/tests/_runtime/test_manage_script_metadata.py+++ b/tests/_runtime/test_manage_script_metadata.py@@ -341,6 +341,7 @@ async def test_missing_packages_hook("cell3": ManyModulesNotFoundError(package_names=["grouped-one", "grouped-two"],msg="Missing one and two",+ source="kernel",),}diff --git a/tests/_server/api/endpoints/test_editing.py b/tests/_server/api/endpoints/test_editing.pyindex 678601b296..de276dc239 100644--- a/tests/_server/api/endpoints/test_editing.py+++ b/tests/_server/api/endpoints/test_editing.py@@ -1,8 +1,9 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations+import sysfrom typing import TYPE_CHECKING-from unittest.mock import AsyncMock, patch+from unittest.mock import AsyncMock, MagicMock, patchimport pytest@@ -113,6 +114,54 @@ def test_install_missing_packages(client: TestClient) -> None:assert "success" in response.json()+def _mock_server_install(+ client: TestClient, *, manager_installed: bool = True+) -> tuple[MagicMock, MagicMock]:+ """POST install_missing_packages with source="server" using a mocked+ package manager. Returns (mock_create, mock_pkg_manager)."""+ mock_pkg_manager = MagicMock()+ mock_pkg_manager.is_manager_installed.return_value = manager_installed+ mock_pkg_manager.install = AsyncMock()++ with patch(+ "marimo._runtime.packages.package_managers.create_package_manager",+ return_value=mock_pkg_manager,+ ) as mock_create:+ response = client.post(+ "/api/kernel/install_missing_packages",+ headers=HEADERS,+ json={+ "manager": "pip",+ "versions": {"nbformat": ""},+ "source": "server",+ },+ )+ assert response.status_code == 200, response.text+ assert "success" in response.json()++ return mock_create, mock_pkg_manager+++@with_session(SESSION_ID)+def test_install_missing_packages_server_source(client: TestClient) -> None:+ # source="server" routes the install to the server's Python env directly+ # rather than dispatching to the kernel.+ mock_create, mock_pkg_manager = _mock_server_install(client)+ mock_create.assert_called_once_with("pip", python_exe=sys.executable)+ mock_pkg_manager.install.assert_awaited_once_with("nbformat", version=None)+++@with_session(SESSION_ID)+def test_install_missing_packages_server_source_manager_not_installed(+ client: TestClient,+) -> None:+ # When the package manager is not installed, alert_not_installed is called+ # and no packages are installed.+ _, mock_pkg_manager = _mock_server_install(client, manager_installed=False)+ mock_pkg_manager.alert_not_installed.assert_called_once()+ mock_pkg_manager.install.assert_not_awaited()++@with_session(SESSION_ID)def test_set_cell_config(client: TestClient) -> None:response = client.post(diff --git a/tests/_server/api/endpoints/test_export.py b/tests/_server/api/endpoints/test_export.pyindex 176f45e455..aeb0a4ec14 100644--- a/tests/_server/api/endpoints/test_export.py+++ b/tests/_server/api/endpoints/test_export.py@@ -444,6 +444,47 @@ def test_auto_export_ipynb()+@with_session(SESSION_ID)+def test_auto_export_ipynb_missing_nbformat_notifies_once(+ client: TestClient, *, temp_marimo_file: str+) -> None:+ """Missing-nbformat alert fires at most once per session."""+ from unittest.mock import patch++ session = get_session_manager(client).get_session(SESSION_ID)+ assert session+ session.app_file_manager.filename = temp_marimo_file++ with (+ patch(+ "marimo._server.api.endpoints.export.DependencyManager"+ ) as mock_dm,+ patch(+ "marimo._server.api.endpoints.export.notify_server_missing_packages"+ ) as mock_notify,+ ):+ mock_dm.nbformat.has.return_value = False++ # First call — should notify+ response = client.post(+ "/api/export/auto_export/ipynb",+ headers=HEADERS,+ json={"download": False},+ )+ assert response.status_code == 304+ assert mock_notify.call_count == 1++ # Second call in same session — should NOT notify again+ session.session_view.needs_export = lambda _: True # reset guard+ response = client.post(+ "/api/export/auto_export/ipynb",+ headers=HEADERS,+ json={"download": False},+ )+ assert response.status_code == 304+ assert mock_notify.call_count == 1 # still 1, not 2++@pytest.mark.skipif(not DependencyManager.nbformat.has() or is_windows(),reason="nbformat not installed or on Windows",diff --git a/tests/_server/test_errors.py b/tests/_server/test_errors.pyindex 7cbdd7d0f0..98c383a90a 100644--- a/tests/_server/test_errors.py+++ b/tests/_server/test_errors.py@@ -156,6 +156,7 @@ async def test_many_modules_not_found_error_in_edit_mode():exc = ManyModulesNotFoundError(["numpy", "pandas", "scipy"],"No modules named: numpy, pandas, scipy",+ source="kernel",)response = await handle_error(Request({"type": "http"}), exc)diff --git a/tests/_session/managers/test_ipc.py b/tests/_session/managers/test_ipc.pyindex 8689429cfd..e937accf85 100644--- a/tests/_session/managers/test_ipc.py+++ b/tests/_session/managers/test_ipc.py@@ -1,10 +1,13 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations+import osimport timeimport pytest+from marimo._session.managers.ipc import construct_kernel_env+@pytest.mark.requires("zmq")class TestIPCConnection:@@ -146,3 +149,83 @@ class TestIPCQueueManagerImpl:# Clean upvia_factory.close_queues()+++class TestConstructKernelEnv:+ """Tests for construct_kernel_env, the pure-function that builds the+ environment dict for a kernel subprocess.++ Three scenarios are covered matching the real call-sites in+ IPCKernelManagerImpl.start_kernel():+ 1. Ephemeral sandbox (is_ephemeral_sandbox=True, writable=True)+ 2. Configured writable venv (is_ephemeral_sandbox=False, writable=True)+ 3. Configured read-only venv with PYTHONPATH injection+ """++ BASE_ENV: dict[str, str] = {"PATH": "/usr/bin"}+ SANDBOX_PYTHON = "/tmp/sandbox/.venv/bin/python"+ CONFIGURED_PYTHON = "/home/user/.venvs/nb/bin/python"++ # -- ephemeral sandbox -------------------------------------------------++ def test_ephemeral_sandbox(self) -> None:+ env = construct_kernel_env(+ base_env={**self.BASE_ENV, "UV_PROJECT_ENVIRONMENT": "/old"},+ venv_python=self.SANDBOX_PYTHON,+ is_ephemeral_sandbox=True,+ writable=True,+ )+ # VIRTUAL_ENV points to the venv root (two parents above python)+ assert env["VIRTUAL_ENV"] == "/tmp/sandbox/.venv"+ # UV_PROJECT_ENVIRONMENT must be removed so the kernel doesn't+ # inherit the outer uv project.+ assert "UV_PROJECT_ENVIRONMENT" not in env+ # Ephemeral sandboxes are always writable.+ assert env["MARIMO_MANAGE_SCRIPT_METADATA"] == "true"++ # -- configured venvs --------------------------------------------------++ def test_configured_readonly_venv_with_pythonpath(self) -> None:+ env = construct_kernel_env(+ base_env=self.BASE_ENV,+ venv_python=self.CONFIGURED_PYTHON,+ is_ephemeral_sandbox=False,+ writable=False,+ kernel_pythonpath="/usr/lib/python3.11/site-packages",+ )+ assert env["PYTHONPATH"] == "/usr/lib/python3.11/site-packages"+ # Should NOT touch sandbox-only vars.+ assert "VIRTUAL_ENV" not in env+ assert "MARIMO_MANAGE_SCRIPT_METADATA" not in env++ def test_pythonpath_merges_with_existing(self) -> None:+ env = construct_kernel_env(+ base_env={**self.BASE_ENV, "PYTHONPATH": "/existing"},+ venv_python=self.CONFIGURED_PYTHON,+ is_ephemeral_sandbox=False,+ writable=False,+ kernel_pythonpath="/new",+ )+ assert env["PYTHONPATH"] == f"/new{os.pathsep}/existing"++ def test_writable_sets_manage_script_metadata(self) -> None:+ env = construct_kernel_env(+ base_env=self.BASE_ENV,+ venv_python=self.CONFIGURED_PYTHON,+ is_ephemeral_sandbox=False,+ writable=True,+ )+ assert env["MARIMO_MANAGE_SCRIPT_METADATA"] == "true"++ # -- safety ------------------------------------------------------------++ def test_does_not_mutate_base_env(self) -> None:+ base = {**self.BASE_ENV, "UV_PROJECT_ENVIRONMENT": "/old"}+ construct_kernel_env(+ base_env=base,+ venv_python=self.SANDBOX_PYTHON,+ is_ephemeral_sandbox=True,+ writable=True,+ )+ assert "UV_PROJECT_ENVIRONMENT" in base+ assert "VIRTUAL_ENV" not in base