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
feat: move matplotlib interactive to use marimo comm instead of over WS (#8612)
Myles Scolnick45e12f306d41
diff --git a/frontend/src/plugins/impl/mpl-interactive/MplInteractivePlugin.tsx b/frontend/src/plugins/impl/mpl-interactive/MplInteractivePlugin.tsxnew file mode 100644index 0000000000..849eb967a2--- /dev/null+++ b/frontend/src/plugins/impl/mpl-interactive/MplInteractivePlugin.tsx@@ -0,0 +1,309 @@+/* Copyright 2026 Marimo. All rights reserved. */+/* eslint-disable @typescript-eslint/no-explicit-any */++import { useCallback, useEffect, useRef } from "react";+import { z } from "zod";+import { useEventListener } from "@/hooks/useEventListener";+import { createPlugin } from "@/plugins/core/builder";+import { MODEL_MANAGER, type Model } from "@/plugins/impl/anywidget/model";+import type { ModelState, WidgetModelId } from "@/plugins/impl/anywidget/types";+import type { IPluginProps } from "@/plugins/types";+import { downloadBlob } from "@/utils/download";+import { Logger } from "@/utils/Logger";+import { MplCommWebSocket } from "./mpl-websocket-shim";++const MPL_SCOPE_CLASS = "mpl-interactive-figure";++interface Data {+ mplJsUrl: string;+ cssUrl: string;+ toolbarImages: Record<string, string>;+ width: number;+ height: number;+}++interface ModelIdRef {+ model_id: WidgetModelId;+}++declare global {+ interface Window {+ mpl: {+ figure: new (+ id: string,+ ws: MplCommWebSocket,+ ondownload: (figure: MplFigure, format: string) => void,+ element: HTMLElement,+ ) => MplFigure;+ toolbar_items: [+ string | null,+ string | null,+ string | null,+ string | null,+ ][];+ };+ }+}++interface MplFigure {+ id: string;+ ws: MplCommWebSocket;+ root: HTMLElement;+ send_message: (type: string, properties: Record<string, unknown>) => void;+}++export const MplInteractivePlugin = createPlugin<ModelIdRef>(+ "marimo-mpl-interactive",+)+ .withData(+ z.object({+ mplJsUrl: z.string(),+ cssUrl: z.string(),+ toolbarImages: z.record(z.string(), z.string()),+ width: z.number(),+ height: z.number(),+ }),+ )+ .withFunctions({})+ .renderer((props) => <MplInteractiveSlot {...props} />);++let mplJsLoading: Promise<void> | null = null;++async function ensureMplJs(jsUrl: string): Promise<void> {+ if (window.mpl) {+ return;+ }+ if (mplJsLoading) {+ return mplJsLoading;+ }+ mplJsLoading = new Promise<void>((resolve, reject) => {+ const script = document.createElement("script");+ script.src = jsUrl;+ script.onload = () => resolve();+ script.onerror = () => {+ mplJsLoading = null;+ reject(new Error("Failed to load mpl.js"));+ };+ document.head.append(script);+ });+ return mplJsLoading;+}++/**+ * Patch mpl.js toolbar image references to use inline data URIs.+ *+ * mpl.js sets `icon_img.src = '_images/' + image + '.png'` and+ * `icon_img.srcset = '_images/' + image + '_large.png 2x'`.+ *+ * We observe the container for new <img> elements and rewrite their+ * src/srcset to the inlined base64 data URIs.+ */+function patchToolbarImages(+ container: HTMLElement,+ toolbarImages: Record<string, string>,+): () => void {+ const patchImg = (img: HTMLImageElement) => {+ const src = img.getAttribute("src") || "";+ const match = src.match(/_images\/(.+)\.png$/);+ if (match) {+ const name = match[1];+ const dataUri = toolbarImages[name];+ if (dataUri) {+ img.src = dataUri;+ }+ }+ const srcset = img.getAttribute("srcset") || "";+ const srcsetMatch = srcset.match(/_images\/(.+)\.png\s+2x$/);+ if (srcsetMatch) {+ const name = srcsetMatch[1];+ const dataUri = toolbarImages[name];+ if (dataUri) {+ img.srcset = `${dataUri} 2x`;+ }+ }+ };++ // Patch any existing images+ for (const img of container.querySelectorAll("img")) {+ patchImg(img);+ }++ // Observe for new images added by mpl.js+ const observer = new MutationObserver((mutations) => {+ for (const mutation of mutations) {+ for (const node of mutation.addedNodes) {+ if (node instanceof HTMLImageElement) {+ patchImg(node);+ } else if (node instanceof HTMLElement) {+ for (const img of node.querySelectorAll("img")) {+ patchImg(img);+ }+ }+ }+ }+ });++ observer.observe(container, { childList: true, subtree: true });+ return () => observer.disconnect();+}++function injectCss(container: HTMLElement, cssUrl: string): () => void {+ const link = document.createElement("link");+ link.rel = "stylesheet";+ link.href = cssUrl;+ container.append(link);+ return () => link.remove();+}++const MplInteractiveSlot = (props: IPluginProps<ModelIdRef, Data>) => {+ const { mplJsUrl, cssUrl, toolbarImages, width, height } = props.data;+ const { model_id: modelId } = props.value;+ const containerRef = useRef<HTMLDivElement>(null);+ const figureRef = useRef<MplFigure | null>(null);+ const wsRef = useRef<MplCommWebSocket | null>(null);++ const setupFigure = useCallback(+ async (container: HTMLElement) => {+ // Load mpl.js globally (only once, via <script src>)+ await ensureMplJs(mplJsUrl);++ if (!window.mpl) {+ Logger.error("mpl.js failed to load");+ return;+ }++ // Get the model from MODEL_MANAGER+ let model: Model<ModelState>;+ try {+ model = await MODEL_MANAGER.get(modelId);+ } catch {+ Logger.error("Failed to get model for mpl interactive", modelId);+ return;+ }++ // Create the fake WebSocket+ const fakeWs = new MplCommWebSocket((msg: unknown) => {+ // Send from frontend → backend via model custom message+ model.send(msg);+ });+ wsRef.current = fakeWs;++ // Listen for backend → frontend messages via model custom events+ const handleCustomMessage = (+ content: { type: string; data?: unknown; format?: string },+ buffers?: readonly DataView[],+ ) => {+ if (!content) {+ return;+ }++ if (content.type === "json") {+ fakeWs.receiveJson(content.data);+ } else if (content.type === "binary" && buffers && buffers.length > 0) {+ fakeWs.receiveBinary(buffers[0]);+ } else if (+ content.type === "download" &&+ buffers &&+ buffers.length > 0+ ) {+ const fmt = content.format || "png";+ const dv = buffers[0];+ const ab = dv.buffer.slice(+ dv.byteOffset,+ dv.byteOffset + dv.byteLength,+ ) as ArrayBuffer;+ downloadBlob(+ new Blob([ab], { type: `image/${fmt}` }),+ `figure.${fmt}`,+ );+ }+ };++ model.on("msg:custom", handleCustomMessage as any);++ // Create the mpl figure+ const figId = modelId;+ const ondownload = (_figure: MplFigure, format: string) => {+ // Send download request to backend+ model.send({ type: "download", format });+ };++ const fig = new window.mpl.figure(figId, fakeWs, ondownload, container);+ figureRef.current = fig;++ // Set the canvas_div to the backend's figure size so the+ // ResizeObserver doesn't trigger an immediate resize cycle.+ // mpl.js creates: fig.root > [titlebar, canvas_div, toolbar]+ const canvasDiv = fig.root.querySelector<HTMLElement>("div[tabindex]");+ if (canvasDiv) {+ canvasDiv.style.width = `${width}px`;+ canvasDiv.style.height = `${height}px`;+ }++ // Trigger the onopen callback to start communication+ // mpl.js sends initial messages in onopen+ setTimeout(() => {+ fakeWs.onopen?.();+ }, 0);++ return () => {+ model.off("msg:custom", handleCustomMessage as any);+ fakeWs.close();+ };+ },+ [modelId, mplJsUrl, width, height],+ );++ useEffect(() => {+ const container = containerRef.current;+ if (!container) {+ return;+ }++ // Clear any previous content (handles re-render / cell re-run)+ container.innerHTML = "";++ // Inject CSS+ const removeCss = injectCss(container, cssUrl);++ // Patch toolbar images+ const removeImageObserver = patchToolbarImages(container, toolbarImages);++ let cleanup: (() => void) | undefined;+ let cancelled = false;++ setupFigure(container)+ .then((cleanupFn) => {+ if (cancelled) {+ cleanupFn?.();+ return;+ }+ cleanup = cleanupFn;+ })+ .catch((error) => {+ if (!cancelled) {+ Logger.error("Failed to set up MPL interactive figure", error);+ }+ });++ return () => {+ cancelled = true;+ removeCss();+ removeImageObserver();+ cleanup?.();+ // Clear DOM on unmount so stale content doesn't linger+ container.innerHTML = "";+ };+ }, [modelId, cssUrl, toolbarImages, setupFigure]);++ // Re-request figure when tab becomes visible+ useEventListener(document, "visibilitychange", () => {+ const fig = figureRef.current;+ if (!document.hidden && fig?.ws?.readyState === WebSocket.OPEN) {+ fig.send_message("refresh", {});+ }+ });++ // Must match _MPL_SCOPE in from_mpl_interactive.py+ return <div ref={containerRef} className={MPL_SCOPE_CLASS} />;+};diff --git a/frontend/src/plugins/impl/mpl-interactive/__tests__/mpl-websocket-shim.test.ts b/frontend/src/plugins/impl/mpl-interactive/__tests__/mpl-websocket-shim.test.tsnew file mode 100644index 0000000000..28e83b905b--- /dev/null+++ b/frontend/src/plugins/impl/mpl-interactive/__tests__/mpl-websocket-shim.test.ts@@ -0,0 +1,110 @@+/* Copyright 2026 Marimo. All rights reserved. */+import { describe, expect, it, vi } from "vitest";+import { MplCommWebSocket } from "../mpl-websocket-shim";++describe("MplCommWebSocket", () => {+ it("starts in OPEN state", () => {+ const ws = new MplCommWebSocket(vi.fn());+ expect(ws.readyState).toBe(WebSocket.OPEN);+ });++ it("send() parses JSON and calls sendFn with parsed object", () => {+ const sendFn = vi.fn();+ const ws = new MplCommWebSocket(sendFn);++ ws.send(JSON.stringify({ type: "resize", width: 640, height: 480 }));++ expect(sendFn).toHaveBeenCalledOnce();+ expect(sendFn).toHaveBeenCalledWith({+ type: "resize",+ width: 640,+ height: 480,+ });+ });++ it("receiveJson() dispatches MessageEvent with JSON string data", () => {+ const ws = new MplCommWebSocket(vi.fn());+ const handler = vi.fn();+ ws.onmessage = handler;++ ws.receiveJson({ type: "figure_size", size: [640, 480] });++ expect(handler).toHaveBeenCalledOnce();+ const event: MessageEvent = handler.mock.calls[0][0];+ expect(event).toBeInstanceOf(MessageEvent);+ expect(event.type).toBe("message");+ expect(JSON.parse(event.data as string)).toEqual({+ type: "figure_size",+ size: [640, 480],+ });+ });++ it("receiveJson() is a no-op if onmessage is not set", () => {+ const ws = new MplCommWebSocket(vi.fn());+ ws.receiveJson({ type: "test" });+ expect(ws.onmessage).toBeNull();+ });++ it("receiveBinary() dispatches MessageEvent with Blob data", () => {+ const ws = new MplCommWebSocket(vi.fn());+ const handler = vi.fn();+ ws.onmessage = handler;++ // Simulate a PNG-like binary buffer+ const bytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0, 1, 2, 3]);+ const dv = new DataView(bytes.buffer);++ ws.receiveBinary(dv);++ expect(handler).toHaveBeenCalledOnce();+ const event: MessageEvent = handler.mock.calls[0][0];+ expect(event).toBeInstanceOf(MessageEvent);+ expect(event.data).toBeInstanceOf(Blob);+ expect((event.data as Blob).size).toBe(8);+ });++ it("receiveBinary() handles DataView with offset", () => {+ const ws = new MplCommWebSocket(vi.fn());+ const handler = vi.fn();+ ws.onmessage = handler;++ // Create a DataView that's a slice of a larger buffer+ const fullBuffer = new ArrayBuffer(16);+ const fullView = new Uint8Array(fullBuffer);+ fullView.set([0, 0, 0, 0, 0x89, 0x50, 0x4e, 0x47, 0, 1, 2, 3, 0, 0, 0, 0]);+ const dv = new DataView(fullBuffer, 4, 8);++ ws.receiveBinary(dv);++ expect(handler).toHaveBeenCalledOnce();+ const blob = handler.mock.calls[0][0].data as Blob;+ expect(blob.size).toBe(8);+ });++ it("close() sets readyState to CLOSED and fires onclose", () => {+ const ws = new MplCommWebSocket(vi.fn());+ const closeHandler = vi.fn();+ ws.onclose = closeHandler;++ ws.close();++ expect(ws.readyState).toBe(WebSocket.CLOSED);+ expect(closeHandler).toHaveBeenCalledOnce();+ });++ it("close() does not throw if onclose is not set", () => {+ const ws = new MplCommWebSocket(vi.fn());+ ws.close();+ expect(ws.readyState).toBe(WebSocket.CLOSED);+ });++ it("onopen can be triggered externally", () => {+ const ws = new MplCommWebSocket(vi.fn());+ const openHandler = vi.fn();+ ws.onopen = openHandler;++ ws.onopen?.();++ expect(openHandler).toHaveBeenCalledOnce();+ });+});diff --git a/frontend/src/plugins/impl/mpl-interactive/mpl-websocket-shim.ts b/frontend/src/plugins/impl/mpl-interactive/mpl-websocket-shim.tsnew file mode 100644index 0000000000..ed4ca0b49b--- /dev/null+++ b/frontend/src/plugins/impl/mpl-interactive/mpl-websocket-shim.ts@@ -0,0 +1,57 @@+/* Copyright 2026 Marimo. All rights reserved. */++/**+ * Fake WebSocket that routes messages through MarimoComm / MODEL_MANAGER+ * instead of a real network WebSocket.+ *+ * mpl.js expects a WebSocket-like object with:+ * - readyState+ * - send(data: string)+ * - onopen / onmessage / onclose callbacks+ */+export class MplCommWebSocket {+ readyState: number = WebSocket.OPEN;+ private sendFn: (msg: unknown) => void;++ onopen: (() => void) | null = null;+ onmessage: ((evt: MessageEvent) => void) | null = null;+ onclose: (() => void) | null = null;++ constructor(sendFn: (msg: unknown) => void) {+ this.sendFn = sendFn;+ }++ /**+ * Called by mpl.js to send a message to the backend.+ * mpl.js always sends JSON strings.+ */+ send(data: string): void {+ this.sendFn(JSON.parse(data));+ }++ /**+ * Called when the backend pushes a JSON message via the model custom event.+ */+ receiveJson(data: unknown): void {+ this.onmessage?.(+ new MessageEvent("message", { data: JSON.stringify(data) }),+ );+ }++ /**+ * Called when the backend pushes binary data (PNG render) via model custom event.+ */+ receiveBinary(buffer: DataView): void {+ const ab = buffer.buffer.slice(+ buffer.byteOffset,+ buffer.byteOffset + buffer.byteLength,+ ) as ArrayBuffer;+ const blob = new Blob([ab]);+ this.onmessage?.(new MessageEvent("message", { data: blob }));+ }++ close(): void {+ this.readyState = WebSocket.CLOSED;+ this.onclose?.();+ }+}diff --git a/frontend/src/plugins/plugins.ts b/frontend/src/plugins/plugins.tsindex aea158f4a4..811919c4dc 100644--- a/frontend/src/plugins/plugins.ts+++ b/frontend/src/plugins/plugins.ts@@ -26,6 +26,7 @@ import { MatrixPlugin } from "./impl/MatrixPlugin";import { MicrophonePlugin } from "./impl/MicrophonePlugin";import { MultiselectPlugin } from "./impl/MultiselectPlugin";import { MatplotlibPlugin } from "./impl/matplotlib/MatplotlibPlugin";+import { MplInteractivePlugin } from "./impl/mpl-interactive/MplInteractivePlugin";import { NumberPlugin } from "./impl/NumberPlugin";import { PanelPlugin } from "./impl/panel/PanelPlugin";import { PlotlyPlugin } from "./impl/plotly/PlotlyPlugin";@@ -92,6 +93,7 @@ export const UI_PLUGINS: IPlugin<any, unknown>[] = [AnyWidgetPlugin,DataEditorPlugin,PanelPlugin,+ MplInteractivePlugin,];// List of output / layout pluginsdiff --git a/frontend/vite.config.mts b/frontend/vite.config.mtsindex 622e171024..3eeb6ec1cb 100644--- a/frontend/vite.config.mts+++ b/frontend/vite.config.mts@@ -295,6 +295,18 @@ export default defineConfig({build: {minify: isDev ? false : "oxc", // default is "oxc"sourcemap: isDev,+ rollupOptions: {+ onwarn(warning, warn) {+ if (+ warning.message?.includes(+ "has been externalized for browser compatibility",+ )+ ) {+ return;+ }+ warn(warning);+ },+ },},resolve: {tsconfigPaths: true,diff --git a/marimo/_plugins/stateless/mpl/_mpl.py b/marimo/_plugins/stateless/mpl/_mpl.pyindex d820a66556..072bf57d93 100644--- a/marimo/_plugins/stateless/mpl/_mpl.py+++ b/marimo/_plugins/stateless/mpl/_mpl.py@@ -7,422 +7,24 @@ Adapted from https://matplotlib.org/stable/gallery/user_interfaces/embedding_webfrom __future__ import annotations-import asyncio-import htmlimport io-import mimetypes-import os-import threading-import time-from pathlib import Path-from typing import TYPE_CHECKING, Any, Optional, Union+from typing import TYPE_CHECKING, Any, Unionfrom marimo import _loggersfrom marimo._messaging.mimetypes import KnownMimeType-from marimo._output.builder import hfrom marimo._output.formatting import as_htmlfrom marimo._output.hypertext import Htmlfrom marimo._output.rich_help import mddoc-from marimo._runtime.cell_lifecycle_item import CellLifecycleItemfrom marimo._runtime.context import (- RuntimeContext,get_context,)from marimo._runtime.context.kernel_context import KernelRuntimeContext-from marimo._runtime.runtime import app_meta-from marimo._utils.platform import is_pyodideLOGGER = _loggers.marimo_logger()if TYPE_CHECKING:from matplotlib.axes import Axes- from matplotlib.backends.backend_webagg_core import FigureManagerWebAggfrom matplotlib.figure import Figure, SubFigure- from starlette.applications import Starlette- from starlette.requests import Request- from starlette.responses import HTMLResponse, Response- from starlette.websockets import WebSocket---class FigureManagers:- def __init__(self) -> None:- self.figure_managers: dict[str, FigureManagerWebAgg] = {}-- def add(self, manager: FigureManagerWebAgg) -> None:- self.figure_managers[str(manager.num)] = manager-- def get(self, figure_id: str) -> FigureManagerWebAgg:- if figure_id not in self.figure_managers:- raise RuntimeError(f"Figure {figure_id} not found.") # noqa: E501- return self.figure_managers[str(figure_id)]-- def remove(self, manager: FigureManagerWebAgg) -> None:- try:- del self.figure_managers[str(manager.num)]- except KeyError:- # Figure already removed, this can happen during server restart- LOGGER.debug(f"Figure {manager.num} already removed from manager")---figure_managers = FigureManagers()---class MplServerManager:- """Manages the matplotlib server lifecycle with lazy recovery."""-- def __init__(self) -> None:- self.process: Optional[threading.Thread] = None- self._restart_lock = threading.Lock()-- def is_running(self) -> bool:- """Check if the server thread is still running."""- if self.process is None:- return False- # Check if the thread is still alive- return self.process.is_alive()-- def start(- self,- app_host: Optional[str] = None,- free_port: Optional[int] = None,- secure_host: Optional[bool] = None,- ) -> Starlette:- """Start the matplotlib server and return the Starlette app."""- import uvicorn-- host = app_host if app_host is not None else _get_host()- secure = secure_host if secure_host is not None else _get_secure()-- # Find a free port, with some randomization to avoid conflicts- import random-- from marimo._utils.net import find_free_port-- base_port = 10_000 + random.randint(0, 1000) # Add some randomization- port = (- free_port if free_port is not None else find_free_port(base_port)- )- app = create_application()- app.state.host = host- app.state.port = port- app.state.secure = secure-- def start_server() -> None:- # Don't try to set signal handlers in background thread- # The original signal handlers will remain in place- server = uvicorn.Server(- uvicorn.Config(- app=app,- port=port,- host=host,- log_level="critical",- )- )- try:- server.run()- except Exception as e:- LOGGER.error(f"Matplotlib server failed: {e}")- # Thread will exit, making is_running() return False- # This allows for automatic restart on next use-- # Start server in background thread- thread = threading.Thread(target=start_server, daemon=True)- thread.start()-- # Store thread reference to track server- self.process = thread-- # TODO: Consider if we need this sleep from original code- # Original comment: "arbitrary wait 200ms for the server to start"- # With lazy recovery, this may no longer be necessary- time.sleep(0.02)-- LOGGER.info(f"Started matplotlib server at {host}:{port}")- return app-- def stop(self) -> None:- """Stop the server process."""- if self.process is not None:- # Note: We can't easily terminate uvicorn server from here,- # but marking process as None will cause is_running() to return False- # and trigger a restart on next use- self.process = None- LOGGER.debug("Marked matplotlib server for restart")---_server_manager = MplServerManager()---def _get_host() -> str:- """- Get the host from environment variable or fall back to localhost.- """- host = os.environ.get("MARIMO_MPL_HOST", "localhost")- if not host or not isinstance(host, str):- return "localhost"- if "://" in host:- raise ValueError(- f"Invalid host '{host}': should not include protocol (http:// or https://)"- )- if "/" in host:- raise ValueError(f"Invalid host '{host}': should not include paths")- if ":" in host:- raise ValueError(- f"Invalid host '{host}': should not include port numbers"- )- return host---def _get_secure() -> bool:- """- Get the secure status from environment variable or fall back to False.- """- secure = os.environ.get("MARIMO_MPL_SECURE", "false")- if not secure or not isinstance(secure, str):- return False- secure = secure.lower().strip()- if secure in ("true", "1", "yes", "on"):- return True- if secure in ("false", "0", "no", "off"):- return False-- raise ValueError(- f"Invalid secure value '{secure}': should be 'true' or 'false'"- )---def _get_remote_url() -> str:- request = app_meta().request- if not request:- return ""-- base_url = request.headers.get("x-runtime-url")- if not base_url:- return ""- return base_url.rstrip("/")---def _convert_scheme_to_ws(url: str) -> str:- if url.startswith("http://"):- return url.replace("http://", "ws://")- if url.startswith("https://"):- return url.replace("https://", "wss://")- return url---def _template(fig_id: str, port: int) -> str:- base_url = _get_remote_url() or f"http://localhost:{port}/"- base_url_and_path = f"{base_url}/mpl/{fig_id}"- base_url_and_path_ws = f"{base_url}/mpl/{port}"- ws_base_url = _convert_scheme_to_ws(base_url_and_path_ws)-- return html_content % {- "ws_uri": f"{ws_base_url}/ws?figure={fig_id}",- "fig_id": fig_id,- "base_url": base_url_and_path,- }---# Toplevel for reuse in endpoints.-async def mpl_js(request: Request) -> Response:- from matplotlib.backends.backend_webagg_core import (- FigureManagerWebAgg,- )- from starlette.responses import Response-- del request- return Response(- content=patch_javascript(FigureManagerWebAgg.get_javascript()), # type: ignore[no-untyped-call]- media_type="application/javascript",- )---async def mpl_custom_css(request: Request) -> Response:- from starlette.responses import Response-- del request- return Response(- content=css_content,- media_type="text/css",- )---# Over all application for handling figures on a per kernel basis-def create_application() -> Starlette:- import matplotlib as mpl- from matplotlib.backends.backend_webagg_core import (- FigureManagerWebAgg,- )- from starlette.applications import Starlette- from starlette.responses import HTMLResponse, Response- from starlette.routing import Mount, Route, WebSocketRoute- from starlette.staticfiles import StaticFiles- from starlette.websockets import (- WebSocketDisconnect,- WebSocketState,- )-- async def main_page(request: Request) -> HTMLResponse:- figure_id = request.query_params.get("figure")- assert figure_id is not None- port = request.app.state.port- content = _template(figure_id, port)- return HTMLResponse(content=content)-- async def download(request: Request) -> Response:- figure_id = request.query_params.get("figure")- assert figure_id is not None- fmt = request.path_params["fmt"]- mime_type = mimetypes.types_map.get(fmt, "binary")- buff = io.BytesIO()- figure_manager = figure_managers.get(figure_id)- figure_manager.canvas.figure.savefig(- buff, format=fmt, bbox_inches="tight"- )- return Response(content=buff.getvalue(), media_type=mime_type)-- async def websocket_endpoint(websocket: WebSocket) -> None:- await websocket.accept()- queue: asyncio.Queue[tuple[Any, str]] = asyncio.Queue()-- class SyncWebSocket:- def send_json(self, content: str) -> None:- queue.put_nowait((content, "json"))-- def send_binary(self, blob: Any) -> None:- queue.put_nowait((blob, "binary"))-- figure_id = websocket.query_params.get("figure")- if not figure_id:- await websocket.send_json(- {"type": "error", "message": "No figure ID provided"}- )- await websocket.close()- return-- try:- figure_manager = figure_managers.get(figure_id)- except RuntimeError:- await websocket.send_json(- {- "type": "error",- "message": f"Figure with id '{figure_id}' not found. The matplotlib server may have restarted. Please re-run the cell containing this plot.",- }- )- await websocket.close()- return-- figure_manager.add_web_socket(SyncWebSocket()) # type: ignore[no-untyped-call]-- async def receive() -> None:- try:- while True:- data = await websocket.receive_json()- if data["type"] == "supports_binary":- # We always support binary- # and we don't need to pass this message- # to the figure manager- pass- else:- figure_manager.handle_json(data) # type: ignore[no-untyped-call]- except WebSocketDisconnect:- pass- except Exception as e:- if websocket.application_state != WebSocketState.DISCONNECTED:- await websocket.send_json(- {- "type": "error",- "message": f"WebSocket receive error: {str(e)}. The matplotlib server may have restarted. Please refresh this plot.",- }- )- finally:- if websocket.application_state != WebSocketState.DISCONNECTED:- await websocket.close()-- async def send() -> None:- try:- while True:- (data, mode) = await queue.get()- if mode == "json":- await websocket.send_json(data)- else:- await websocket.send_bytes(data)- except WebSocketDisconnect:- # Client disconnected normally- pass- except Exception as e:- if websocket.application_state != WebSocketState.DISCONNECTED:- await websocket.send_json(- {- "type": "error",- "message": f"WebSocket send error: {str(e)}. The matplotlib server may have restarted. Please refresh this plot.",- }- )- finally:- if websocket.application_state != WebSocketState.DISCONNECTED:- await websocket.close()-- try:- await asyncio.gather(receive(), send())- except Exception as e:- if websocket.application_state != WebSocketState.DISCONNECTED:- await websocket.send_json(- {- "type": "error",- "message": f"WebSocket connection error: {str(e)}. The matplotlib server may have restarted. Please refresh this plot.",- }- )- await websocket.close()-- return Starlette(- routes=[- Route("/", main_page, methods=["GET"]),- Route("/mpl.js", mpl_js, methods=["GET"]),- Route("/custom.css", mpl_custom_css, methods=["GET"]),- Route("/download.{fmt}", download, methods=["GET"]),- WebSocketRoute("/ws", websocket_endpoint),- Mount(- "/_static",- StaticFiles(- directory=FigureManagerWebAgg.get_static_file_path() # type: ignore[no-untyped-call]- ),- name="mpl_static",- ),- Mount(- "/_images",- StaticFiles(directory=Path(mpl.get_data_path(), "images")),- name="mpl_images",- ),- ],- )---_app: Optional[Starlette] = None---def get_or_create_application(- app_host: Optional[str] = None,- free_port: Optional[int] = None,- secure_host: Optional[bool] = None,-) -> Starlette:- global _app-- # Thread-safe lazy restart logic- with _server_manager._restart_lock:- if _app is None or not _server_manager.is_running():- if _app is not None:- LOGGER.info(- "Matplotlib server appears to have died, restarting..."- )- _server_manager.stop()- # Clear existing figure managers to prevent stale state- figure_managers.figure_managers.clear()- _app = None-- # Start new server- _app = _server_manager.start(app_host, free_port, secure_host)-- return _appdef new_figure_manager_given_figure(@@ -472,18 +74,6 @@ class NonInteractiveMplHtml(Html):return ("image/png", png_bytes(self._figure).decode())-class InteractiveMplHtml(Html):- """Html subclass that provides PNG fallback for ipynb export."""-- def __init__(self, text: str, figure: Union[Figure, SubFigure]) -> None:- self._figure = figure- super().__init__(text)-- def _repr_png_(self) -> bytes:- """Return base64-encoded PNG bytes for ipynb export fallback."""- return png_bytes(self._figure)--@mddocdef interactive(figure: Union[Figure, SubFigure, Axes]) -> Html:"""Render a matplotlib figure using an interactive viewer.@@ -513,14 +103,6 @@ def interactive(figure: Union[Figure, SubFigure, Axes]) -> Html:assert maybe_figure is not None, "Axes object does not have a Figure"figure = maybe_figure- # We can't support interactive plots in Pyodide- # since they require a WebSocket connection- if is_pyodide():- LOGGER.warning(- "Interactive plots are not supported in Pyodide/WebAssembly"- )- return NonInteractiveMplHtml(figure)-ctx = get_context()if not isinstance(ctx, KernelRuntimeContext):return NonInteractiveMplHtml(figure)@@ -530,116 +112,13 @@ def interactive(figure: Union[Figure, SubFigure, Axes]) -> Html:if not ctx.virtual_files_supported:return NonInteractiveMplHtml(figure)- # Figure Manager, Any type because matplotlib doesn't have typings- figure_manager = new_figure_manager_given_figure(id(figure), figure)-- # TODO(akshayka): Proxy this server through the marimo server to help with- # deployment.- app = get_or_create_application()- port = app.state.port-- class CleanupHandle(CellLifecycleItem):- def create(self, context: RuntimeContext) -> None:- del context-- def dispose(self, context: RuntimeContext, deletion: bool) -> bool:- del context- del deletion- figure_managers.remove(figure_manager)- return True-- figure_managers.add(figure_manager)- assert ctx.execution_context is not None- ctx.cell_lifecycle_registry.add(CleanupHandle())- ctx.stream.cell_id = ctx.execution_context.cell_id-- content = _template(str(figure_manager.num), port)-- return InteractiveMplHtml(- h.iframe(- srcdoc=html.escape(content),- width="100%",- height="550px",- onload="__resizeIframe(this)",- ),- figure,- )+ from marimo._plugins.ui._impl.from_mpl_interactive import mpl_interactive+ return mpl_interactive(figure)-html_content = """-<!DOCTYPE html>-<html lang="en">- <head>- <base href='%(base_url)s/' />- <link rel="stylesheet" href="%(base_url)s/_static/css/page.css" type="text/css" />- <link rel="stylesheet" href="%(base_url)s/_static/css/boilerplate.css" type="text/css" />- <link rel="stylesheet" href="%(base_url)s/_static/css/fbm.css" type="text/css" />- <link rel="stylesheet" href="%(base_url)s/_static/css/mpl.css" type="text/css" />- <link rel="stylesheet" href="%(base_url)s/custom.css" type="text/css" />- <script src="%(base_url)s/mpl.js"></script>-- <script>- function ondownload(figure, format) {- window.open('download.' + format + '?figure=' + figure.id, '_blank');- };-- function ready(fn) {- if (document.readyState != "loading") {- fn();- } else {- document.addEventListener("DOMContentLoaded", fn);- }- }-- ready(- function() {- var websocket_type = mpl.get_websocket_type();- var websocket = new websocket_type("%(ws_uri)s");-- // mpl.figure creates a new figure on the webpage.- var fig = new mpl.figure(- // A unique numeric identifier for the figure- %(fig_id)s,- // A websocket object- websocket,- // A function called when a file type is selected for download- ondownload,- // The HTML element in which to place the figure- document.getElementById("figure"));-- // When the browser tab is hidden (minimized or switched away),- // browsers throttle or skip canvas rendering. Any canvas updates- // sent by matplotlib while hidden are effectively lost, leaving- // blank plots. Re-request the full figure when the tab returns.- document.addEventListener("visibilitychange", function() {- if (!document.hidden && fig.ws.readyState === 1) {- fig.send_message("refresh", {});- }- });- }- );- </script>-- <title>marimo</title>- </head>-- <body>- <div id="figure"></div>- </body>-</html>-""".strip() # noqa: E501# Custom CSS to make the mpl toolbar fit the marimo UI-# We do not support dark mode at the moment as the iframe does not know-# the theme of the parent page.css_content = """-body {- background-color: transparent;- width: 100%;-}-#figure, mlp-canvas {- width: 100%;-}.ui-dialog-titlebar + div {border-radius: 4px;}diff --git a/marimo/_plugins/ui/_impl/from_mpl_interactive.py b/marimo/_plugins/ui/_impl/from_mpl_interactive.pynew file mode 100644index 0000000000..458e784198--- /dev/null+++ b/marimo/_plugins/ui/_impl/from_mpl_interactive.py@@ -0,0 +1,309 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++import base64+import functools+import io+from pathlib import Path+from typing import TYPE_CHECKING, Any, Union+from uuid import uuid4++from marimo import _loggers+from marimo._messaging.mimetypes import KnownMimeType+from marimo._plugins.stateless.mpl._mpl import (+ css_content,+ new_figure_manager_given_figure,+ patch_javascript,+ png_bytes,+)+from marimo._plugins.ui._core.ui_element import InitializationArgs, UIElement+from marimo._plugins.ui._impl.anywidget.init import WIDGET_COMM_MANAGER+from marimo._plugins.ui._impl.comm import MarimoComm+from marimo._runtime.cell_lifecycle_item import CellLifecycleItem+from marimo._runtime.context import RuntimeContext+from marimo._runtime.virtual_file.virtual_file import VirtualFile+from marimo._types.ids import WidgetModelId++if TYPE_CHECKING:+ from matplotlib.figure import Figure, SubFigure++LOGGER = _loggers.marimo_logger()++# Must match the className on the container div in MplInteractivePlugin.tsx+_MPL_SCOPE = ".mpl-interactive-figure"+++class _SyncWebSocket:+ """Adapter passed to FigureManagerWebAgg.add_web_socket().++ Translates send_json/send_binary calls into MarimoComm messages+ that travel through the model-lifecycle notification channel.++ Implements the interface expected by FigureManagerWebAgg:+ https://github.com/matplotlib/matplotlib/blob/9d83ca60096f313dfc9f144288501af18c770a4e/lib/matplotlib/backends/backend_webagg_core.py#L459+ """++ def __init__(self, comm: MarimoComm) -> None:+ self._comm = comm++ def send_json(self, content: Any) -> None:+ self._comm.send(+ data={+ "method": "custom",+ "content": {"type": "json", "data": content},+ },+ )++ def send_binary(self, blob: bytes) -> None:+ self._comm.send(+ data={+ "method": "custom",+ "content": {"type": "binary"},+ },+ buffers=[blob],+ )+++def _get_mpl_css() -> str:+ """Collect safe matplotlib WebAgg CSS files and our custom CSS.++ We skip boilerplate.css and page.css because they contain global+ selectors (body, html, div, span, etc.) designed for a standalone+ page / iframe that would leak into the host page. Only mpl.css and+ fbm.css have properly scoped class-based selectors.++ All rules are wrapped inside a ``.mpl-interactive-figure`` scope so+ that any remaining broad selectors (e.g. ``body``, ``#figure``) do+ not leak into the host page when loaded as a ``<link>`` stylesheet.+ """+ from matplotlib.backends.backend_webagg_core import (+ FigureManagerWebAgg,+ )++ _SKIP = {"boilerplate.css", "page.css"}+ static_path = Path(+ FigureManagerWebAgg.get_static_file_path() # type: ignore[no-untyped-call]+ )+ parts: list[str] = []+ for css_file in sorted(static_path.glob("css/*.css")):+ if css_file.name in _SKIP:+ continue+ parts.append(css_file.read_text())+ # Our own overrides+ parts.append(css_content)+ raw_css = "\n".join(parts)+ return _scope_css(raw_css, _MPL_SCOPE)+++def _scope_css(css: str, scope: str) -> str:+ """Scope CSS rules using native CSS nesting.++ Wraps all rules inside a ``<scope> { … }`` block so that child+ selectors are implicitly prefixed. This replaces the previous+ regex-based rewriter and correctly handles ``@keyframes``,+ ``@media``, and any other at-rules or complex selectors.++ Requires browser support for CSS Nesting (Chrome 120+, Firefox 117+,+ Safari 17.2+).+ """+ return f"{scope} {{\n{css}\n}}"++[email protected]_cache(maxsize=1)+def _get_mpl_css_vfile() -> VirtualFile:+ """Get or create a cached virtual file for the combined CSS."""+ return VirtualFile.create_and_register(+ _get_mpl_css().encode("utf-8"), "css"+ )++[email protected]_cache(maxsize=1)+def _get_toolbar_images() -> dict[str, str]:+ """Return a dict of {filename: data-URI} for all toolbar PNGs."""+ import matplotlib as mpl++ img_dir = Path(mpl.get_data_path(), "images")+ images: dict[str, str] = {}+ for png in img_dir.glob("*.png"):+ data = base64.b64encode(png.read_bytes()).decode("ascii")+ images[png.stem] = f"data:image/png;base64,{data}"+ return images+++def _get_patched_mpl_js() -> str:+ """Get the mpl.js source with focus-stealing patches applied."""+ from matplotlib.backends.backend_webagg_core import (+ FigureManagerWebAgg,+ )++ return patch_javascript(+ FigureManagerWebAgg.get_javascript() # type: ignore[no-untyped-call]+ )++[email protected]_cache(maxsize=1)+def _get_mpl_js_vfile() -> VirtualFile:+ """Get or create a cached virtual file for the patched mpl.js."""+ return VirtualFile.create_and_register(+ _get_patched_mpl_js().encode("utf-8"), "js"+ )+++class ModelIdRef(dict): # type: ignore[type-arg]+ """Wire-format value: just a model_id reference."""++ pass+++class mpl_interactive(UIElement[ModelIdRef, dict[str, Any]]):+ """UIElement wrapping an interactive matplotlib figure.++ Uses MarimoComm for bidirectional communication instead of a+ separate WebSocket server, enabling support in WASM/Pyodide.+ """++ def __init__(self, figure: Union[Figure, SubFigure]) -> None:+ self._figure = figure++ # Create FigureManagerWebAgg+ self._figure_manager = new_figure_manager_given_figure(+ id(figure), figure+ )++ # Get figure dimensions in CSS pixels for initial sizing.+ # get_width_height() returns device pixels (includes DPI scaling).+ # Divide by the device-to-logical DPI ratio to get CSS pixels.+ import matplotlib++ w_px, h_px = self._figure_manager.canvas.get_width_height()+ logical_dpi: float = matplotlib.rcParams["figure.dpi"]+ actual_dpi: float = self._figure_manager.canvas.figure.dpi+ ratio = actual_dpi / logical_dpi if logical_dpi > 0 else 1+ css_w = int(w_px / ratio)+ css_h = int(h_px / ratio)++ # Generate a model id for the comm+ model_id = WidgetModelId(uuid4().hex)++ # Create the MarimoComm+ self._comm = MarimoComm(+ comm_id=model_id,+ comm_manager=WIDGET_COMM_MANAGER,+ target_name="marimo.mpl_interactive",+ data={"state": {}, "method": "open"},+ )++ # Register message handler: frontend → backend+ self._comm.on_msg(self._handle_comm_msg)++ # Create the SyncWebSocket adapter+ self._sync_ws = _SyncWebSocket(self._comm)++ # Connect the websocket to the figure manager+ self._figure_manager.add_web_socket(self._sync_ws) # type: ignore[no-untyped-call]++ super().__init__(+ component_name="marimo-mpl-interactive",+ initial_value=ModelIdRef(model_id=model_id),+ label=None,+ args={+ "mpl-js-url": _get_mpl_js_vfile().url,+ "css-url": _get_mpl_css_vfile().url,+ "toolbar-images": _get_toolbar_images(),+ "width": css_w,+ "height": css_h,+ },+ on_change=None,+ )++ def _initialize(+ self,+ initialization_args: InitializationArgs[ModelIdRef, dict[str, Any]],+ ) -> None:+ super()._initialize(initialization_args)+ # Link the comm to this UIElement for proper lifecycle+ self._comm.ui_element_id = self._id++ # Register cleanup so the comm is closed and the+ # figure manager is cleaned up on cell re-run+ from marimo._runtime.context import (+ ContextNotInitializedError,+ get_context,+ )++ try:+ ctx = get_context()+ ctx.cell_lifecycle_registry.add(_MplCleanupHandle(self._comm))+ except ContextNotInitializedError:+ pass++ def _handle_comm_msg(self, msg: dict[str, Any]) -> None:+ """Handle messages from frontend → backend.++ The comm payload structure from ModelCommand.into_comm_payload() is:+ {"content": {"data": {"method": "custom", "content": <mpl_event>}},+ "buffers": [...]}++ The actual mpl event (with "type" key) is at+ msg["content"]["data"]["content"].+ """+ content = msg.get("content", {})+ data = content.get("data", {})+ # For custom messages, the actual payload is nested under "content"+ event = data.get("content", data)++ msg_type = event.get("type")+ if msg_type == "supports_binary":+ # Acknowledgement, no action needed+ return+ elif msg_type == "download":+ # Handle download request+ fmt = event.get("format", "png")+ self._handle_download(fmt)+ return+ else:+ # Forward to figure manager (mouse events, toolbar actions, etc.)+ self._figure_manager.handle_json(event) # type: ignore[no-untyped-call]++ def _handle_download(self, fmt: str) -> None:+ """Render figure to the requested format and send back via comm."""+ buf = io.BytesIO()+ self._figure_manager.canvas.figure.savefig(+ buf, format=fmt, bbox_inches="tight"+ )+ blob = buf.getvalue()+ self._comm.send(+ data={+ "method": "custom",+ "content": {"type": "download", "format": fmt},+ },+ buffers=[blob],+ )++ def _convert_value(+ self, value: ModelIdRef | dict[str, Any]+ ) -> dict[str, Any]:+ del value+ return {}++ def _repr_png_(self) -> bytes:+ """PNG fallback for ipynb export."""+ return png_bytes(self._figure)++ def _mime_(self) -> tuple[KnownMimeType, str]:+ return super()._mime_()+++class _MplCleanupHandle(CellLifecycleItem):+ """Closes the MarimoComm when the cell is re-run or deleted."""++ def __init__(self, comm: MarimoComm) -> None:+ self._comm = comm++ def create(self, context: RuntimeContext) -> None:+ del context++ def dispose(self, context: RuntimeContext, deletion: bool) -> bool:+ del context, deletion+ self._comm.close()+ return Truediff --git a/marimo/_server/api/endpoints/mpl.py b/marimo/_server/api/endpoints/mpl.pydeleted file mode 100644index f6002491f1..0000000000--- a/marimo/_server/api/endpoints/mpl.py+++ /dev/null@@ -1,305 +0,0 @@-# Copyright 2026 Marimo. All rights reserved.-from __future__ import annotations--import asyncio-from functools import wraps-from pathlib import Path-from typing import TYPE_CHECKING, Any, Callable, Optional--import websockets--if TYPE_CHECKING:- from collections.abc import Awaitable-- from starlette.requests import Request- from starlette.responses import Response- from starlette.websockets import WebSocket---from marimo import _loggers-from marimo._server.api.auth import validate_auth-from marimo._server.router import APIRouter--LOGGER = _loggers.marimo_logger()--router = APIRouter()--figure_endpoints: dict[int, str] = {}--# Maximum size for WebSocket messages received from the matplotlib server.-# Matplotlib's WebAgg backend sends rendered figure PNGs over WebSocket,-# which can exceed the websockets library's default 1 MB limit at higher-# DPI settings or larger figure sizes.-WS_MAX_SIZE = 20 * 1024 * 1024 # 20 MB---def mpl_fallback_handler(- path_prefix: str = "",-) -> Callable[- [Callable[[Request], Awaitable[Response]]],- Callable[[Request], Awaitable[Response]],-]:- """- Args:- path_prefix: Prefix to add to path when calling _mpl_handler (default "")- """- from starlette.responses import Response-- def decorator(- func: Callable[[Request], Awaitable[Response]],- ) -> Callable[[Request], Awaitable[Response]]:- @wraps(func)- async def wrapper(request: Request) -> Response:- figure_num = request.path_params["figure"]- path = request.path_params.get("path", "")- response: Optional[Response] = None-- if figure_num in figure_endpoints:- full_path = path_prefix + path if path_prefix else path- response = await _mpl_handler(request, full_path, figure_num)-- # Fallback if no response or non-200 status- if response is None or response.status_code != 200:- try:- response = await func(request)- except Exception as e:- LOGGER.error(f"Error in fallback handler: {e}")- response = Response(- content="Internal server error",- status_code=500,- media_type="text/plain",- )-- return response-- return wrapper-- return decorator--[email protected]("/mpl/{figure:int}/_static/{path:path}")-@mpl_fallback_handler("_static/")-async def mpl_static(request: Request) -> Response:- """Fallback for static files from matplotlib."""- path = request.path_params["path"]- from matplotlib.backends.backend_webagg_core import (- FigureManagerWebAgg,- )- from starlette.staticfiles import StaticFiles-- static_app = StaticFiles(- directory=FigureManagerWebAgg.get_static_file_path() # type: ignore[no-untyped-call]- )- return await static_app.get_response(path, request.scope)--[email protected]("/mpl/{figure:int}/_images/{path:path}")-@mpl_fallback_handler(path_prefix="_images/")-async def mpl_images(request: Request) -> Response:- """Fallback for image files from matplotlib."""- path = request.path_params["path"]- import matplotlib as mpl- from starlette.staticfiles import StaticFiles-- static_app = StaticFiles(directory=Path(mpl.get_data_path(), "images"))- return await static_app.get_response(path, request.scope)--[email protected]("/mpl/{figure:int}/mpl.js")-@mpl_fallback_handler()-async def mpl_js(request: Request) -> Response:- """Fallback for mpl.js from marimo's internal handler."""- from marimo._plugins.stateless.mpl._mpl import mpl_js-- return await mpl_js(request)--[email protected]("/mpl/{figure:int}/custom.css")-@mpl_fallback_handler()-async def mpl_custom_css(request: Request) -> Response:- """Fallback for custom.css from marimo's internal handler."""- from marimo._plugins.stateless.mpl._mpl import mpl_custom_css-- return await mpl_custom_css(request)---async def _mpl_handler(- request: Request, path: str, figurenum: int-) -> Response:- """- Unified proxy function for matplotlib server requests.-- Args:- request: The incoming request- path: The remaining path to proxy- figurenum: The figure number-- Returns:- Response from the matplotlib server or error response- """- from starlette.responses import Response-- # Validate authentication before proxying - prevents SSRF- if not validate_auth(request):- return Response(- content="Unauthorized",- status_code=401,- media_type="text/plain",- )-- # Proxy to matplotlib server- # Determine the target port- port = figure_endpoints.get(figurenum, None)-- if port is None:- LOGGER.info(- f"Security violation: Attempt to access unauthorized figure {figurenum}"- )- return Response(- content="Unauthorized access",- status_code=403,- media_type="text/plain",- )-- # Construct target URL- target_url = f"http://localhost:{port}/{path}"- LOGGER.debug(f"Proxying {request.method} -> {target_url}")-- # Prepare headers (exclude problematic headers)- headers = {- k: v- for k, v in request.headers.items()- if k.lower() not in ("host", "content-length")- }-- try:- import urllib.parse- import urllib.request- from urllib.error import URLError-- # Construct full URL with query parameters- if request.query_params:- query_string = urllib.parse.urlencode(request.query_params)- full_url = f"{target_url}?{query_string}"- else:- full_url = target_url-- # Prepare request data- data = None- if request.method in ("POST", "PUT", "PATCH"):- data = await request.body()-- # Create urllib request- req = urllib.request.Request(- full_url, data=data, headers=headers, method=request.method- )-- # Execute request in thread pool to avoid blocking- def _make_request() -> dict[str, Any]:- try:- with urllib.request.urlopen(req, timeout=30.0) as response:- return {- "status": response.status,- "headers": dict(response.headers),- "content": response.read(),- }- except URLError as e:- raise ConnectionError() from e-- loop = asyncio.get_event_loop()- response_data = await loop.run_in_executor(None, _make_request)-- return Response(- content=response_data["content"],- status_code=response_data["status"],- headers=response_data["headers"],- media_type=response_data["headers"].get("content-type"),- )-- except ConnectionError:- LOGGER.info(f"Failed to connect to matplotlib server at port {port}")- return Response(- content="Matplotlib server is not available. Please rerun this cell or restart the service.",- status_code=503,- media_type="text/plain",- )- except Exception as e:- LOGGER.error(f"Error proxying to matplotlib server: {e}")- return Response(- content="Internal server error",- status_code=500,- media_type="text/plain",- )--[email protected]("/mpl/{figure:int}/{path:path}")-async def mpl_handler(request: Request) -> Response:- path = request.path_params["path"]- figurenum = request.path_params["figure"]- return await _mpl_handler(request, path, figurenum)--[email protected]("/mpl/{port}/ws")-async def mpl_websocket(websocket: WebSocket) -> None:- """Proxy WebSocket connections to matplotlib server."""- global figure_endpoints- # Only authenticated users can register figure->port mappings- if not validate_auth(websocket):- await websocket.close(code=1008, reason="Unauthorized")- return-- port = str(websocket.path_params["port"])- await websocket.accept()-- # Construct target WebSocket URL with query parameters- query_params = dict(websocket.query_params)- query_string = "&".join(f"{k}={v}" for k, v in query_params.items())- target_ws_url = f"ws://localhost:{port}/ws"- if query_string:- target_ws_url += f"?{query_string}"-- # get figure from query params- figure_num = None- try:- figure_num = query_params.get("figure")- if figure_num is not None:- figure_endpoints[int(figure_num)] = f"{port}"- except (TypeError, ValueError):- LOGGER.warning(- f"Invalid figure number in WebSocket connection: {query_params.get('figure')}"- )- pass-- try:- async with websockets.connect(- target_ws_url, max_size=WS_MAX_SIZE- ) as mpl_ws:-- async def forward_to_mpl() -> None:- try:- async for message in websocket.iter_text():- await mpl_ws.send(message)- except Exception as e:- LOGGER.debug(f"Client->Server forwarding ended: {e}")-- async def forward_to_client() -> None:- try:- async for message in mpl_ws:- if isinstance(message, bytes):- await websocket.send_bytes(message)- else:- await websocket.send_text(message)- except Exception as e:- LOGGER.debug(f"Server->Client forwarding ended: {e}")-- await asyncio.gather(- forward_to_mpl(), forward_to_client(), return_exceptions=True- )-- except Exception as e:- LOGGER.error(f"WebSocket proxy error: {e}")- finally:- try:- await websocket.close()- except Exception:- passdiff --git a/marimo/_server/api/router.py b/marimo/_server/api/router.pyindex 9318f58acc..8037a02add 100644--- a/marimo/_server/api/router.py+++ b/marimo/_server/api/router.py@@ -24,7 +24,6 @@ from marimo._server.api.endpoints.health import router as health_routerfrom marimo._server.api.endpoints.home import router as home_routerfrom marimo._server.api.endpoints.login import router as login_routerfrom marimo._server.api.endpoints.lsp import router as lsp_router-from marimo._server.api.endpoints.mpl import router as mpl_routerfrom marimo._server.api.endpoints.packages import router as packages_routerfrom marimo._server.api.endpoints.secrets import router as secrets_routerfrom marimo._server.api.endpoints.sql import router as sql_router@@ -82,7 +81,6 @@ def build_routes(base_url: str = "") -> list[BaseRoute]:app_router.include_router(lsp_router, prefix="/api/lsp", name="lsp")app_router.include_router(health_router, name="health")app_router.include_router(ws_router, name="ws")- app_router.include_router(mpl_router, name="mpl")app_router.include_router(assets_router, name="assets")return app_router.routesdiff --git a/marimo/_smoke_tests/iplot.py b/marimo/_smoke_tests/iplot.pyindex 63606979f6..5a0d9e2c9e 100644--- a/marimo/_smoke_tests/iplot.py+++ b/marimo/_smoke_tests/iplot.py@@ -2,13 +2,13 @@import marimo-__generated_with = "0.16.3"+__generated_with = "0.20.4"app = marimo.App()@app.cell-def _(mo):- mo.app_meta().request+def _():+ # mo.app_meta().requestreturn@@ -17,6 +17,7 @@ def _():import marimo as moimport numpy as npimport matplotlib.pyplot as plt+return mo, np, plt@@ -39,6 +40,7 @@ def _(mo, np, plt):ax.set_zlabel("Z Label")return mo.mpl.interactive(fig)+return (interactive_plot,)diff --git a/tests/_plugins/stateless/test_mpl.py b/tests/_plugins/stateless/test_mpl.pyindex be4e9018aa..7b60561e7f 100644--- a/tests/_plugins/stateless/test_mpl.py+++ b/tests/_plugins/stateless/test_mpl.py@@ -5,11 +5,6 @@ from unittest.mock import MagicMock, patchimport pytestfrom marimo._output.hypertext import Html-from marimo._plugins.stateless.mpl._mpl import (- _convert_scheme_to_ws,- _get_remote_url,- _template,-)from marimo._runtime.commands import DeleteCellCommandfrom marimo._runtime.runtime import Kernelfrom tests.conftest import ExecReqProvider@@ -17,92 +12,54 @@ from tests.conftest import ExecReqProvider@pytest.mark.requires("matplotlib")def test_mpl_interactive_repr_png() -> None:- """Test that mpl.interactive provides PNG fallback for ipynb export."""+ """Test that mpl_interactive provides PNG fallback for ipynb export."""import base64import matplotlib.pyplot as plt- from marimo._plugins.stateless.mpl._mpl import InteractiveMplHtml+ from marimo._plugins.stateless.mpl._mpl import png_bytes# Create a simple figurefig, ax = plt.subplots()ax.plot([1, 2, 3], [1, 2, 3])- # Create the InteractiveMplHtml object- html_obj = InteractiveMplHtml("<div>test</div>", fig)-- # Verify _repr_png_ returns valid base64-encoded PNG bytes- png_b64 = html_obj._repr_png_()+ # Verify png_bytes returns valid base64-encoded PNG bytes+ png_b64 = png_bytes(fig)assert isinstance(png_b64, bytes)# Decode and verify it's valid PNG- png_bytes = base64.b64decode(png_b64)- assert png_bytes.startswith(b"\x89PNG") # PNG magic bytes- assert len(png_bytes) > 100 # Should have substantial content-- plt.close(fig)--[email protected]("matplotlib")-def test_mpl_interactive_mime_no_js() -> None:- """Test that _mime_ returns PNG when in no-JS mode (ipynb export)."""- import matplotlib.pyplot as plt-- from marimo._output.hypertext import patch_html_for_non_interactive_output- from marimo._plugins.stateless.mpl._mpl import InteractiveMplHtml-- # Create a simple figure- fig, ax = plt.subplots()- ax.plot([1, 2, 3], [1, 2, 3])-- # In normal mode, should return text/html- html_obj = InteractiveMplHtml("<div>test</div>", fig)- mimetype, _ = html_obj._mime_()- assert mimetype == "text/html"-- # In no-JS mode (ipynb export), should return image/png- with patch_html_for_non_interactive_output():- html_obj2 = InteractiveMplHtml("<div>test</div>", fig)- mimetype, data = html_obj2._mime_()- assert mimetype == "image/png"- # Data should be the PNG bytes decoded- assert isinstance(data, str)+ raw_png = base64.b64decode(png_b64)+ assert raw_png.startswith(b"\x89PNG") # PNG magic bytes+ assert len(raw_png) > 100 # Should have substantial contentplt.close(fig)@pytest.mark.requires("matplotlib")async def test_mpl_interactive(k: Kernel, exec_req: ExecReqProvider) -> None:- from threading import Thread-- # This tests that the interactive figure is correctly displayed- # and does not crash when tornado is not installed.-- with patch.object(Thread, "start", lambda self: None): # noqa: ARG005- await k.run(- [- cell := exec_req.get(- """- # remove tornado from sys.modules- import sys- sys.modules.pop("tornado", None)-- import marimo as mo- import matplotlib.pyplot as plt- plt.plot([1, 2])- try:- interactive = mo.mpl.interactive(plt.gcf())- except Exception as e:- interactive = str(e)- """- ),- ]- )+ # This tests that the interactive figure is correctly created+ # as a UIElement and does not crash.+ await k.run(+ [+ cell := exec_req.get(+ """+ import marimo as mo+ import matplotlib.pyplot as plt+ plt.plot([1, 2])+ try:+ interactive = mo.mpl.interactive(plt.gcf())+ except Exception as e:+ interactive = str(e)+ """+ ),+ ]+ )- interactive = k.globals["interactive"]- assert isinstance(interactive, Html)- assert interactive.text.startswith("<iframe srcdoc=")- await k.delete_cell(DeleteCellCommand(cell_id=cell.cell_id))+ interactive = k.globals["interactive"]+ assert isinstance(interactive, Html)+ # Should contain the marimo-mpl-interactive component+ assert "marimo-mpl-interactive" in interactive.text+ await k.delete_cell(DeleteCellCommand(cell_id=cell.cell_id))@pytest.mark.requires("matplotlib")@@ -133,231 +90,6 @@ def test_patch_javascript() -> None:assert javascript.count("// canvas_div.focus();") == 1-def test_get_remote_url_with_request() -> None:- """Test _get_remote_url when request and headers exist"""-- # Mock the app_meta function and request- mock_request = MagicMock()- mock_request.headers.get.return_value = "https://example.com/path/"-- with patch("marimo._plugins.stateless.mpl._mpl.app_meta") as mock_app_meta:- mock_app_meta.return_value.request = mock_request-- result = _get_remote_url()-- assert result == "https://example.com/path"- mock_request.headers.get.assert_called_once_with("x-runtime-url")---def test_get_remote_url_no_request() -> None:- """Test _get_remote_url when no request exists"""-- with patch("marimo._plugins.stateless.mpl._mpl.app_meta") as mock_app_meta:- mock_app_meta.return_value.request = None-- result = _get_remote_url()-- assert result == ""---def test_get_remote_url_no_header() -> None:- """Test _get_remote_url when x-runtime-url header is missing"""-- mock_request = MagicMock()- mock_request.headers.get.return_value = None-- with patch("marimo._plugins.stateless.mpl._mpl.app_meta") as mock_app_meta:- mock_app_meta.return_value.request = mock_request-- result = _get_remote_url()-- assert result == ""---def test_get_remote_url_empty_header() -> None:- """Test _get_remote_url when x-runtime-url header is empty"""-- mock_request = MagicMock()- mock_request.headers.get.return_value = ""-- with patch("marimo._plugins.stateless.mpl._mpl.app_meta") as mock_app_meta:- mock_app_meta.return_value.request = mock_request-- result = _get_remote_url()-- assert result == ""---def test_convert_scheme_to_ws_http() -> None:- """Test _convert_scheme_to_ws with http URL"""-- result = _convert_scheme_to_ws("http://example.com/path")- assert result == "ws://example.com/path"---def test_convert_scheme_to_ws_https() -> None:- """Test _convert_scheme_to_ws with https URL"""-- result = _convert_scheme_to_ws("https://example.com/path")- assert result == "wss://example.com/path"---def test_convert_scheme_to_ws_other_scheme() -> None:- """Test _convert_scheme_to_ws with non-http/https URL"""-- result = _convert_scheme_to_ws("ftp://example.com/path")- assert result == "ftp://example.com/path"---def test_convert_scheme_to_ws_no_scheme() -> None:- """Test _convert_scheme_to_ws with URL without scheme"""-- result = _convert_scheme_to_ws("example.com/path")- assert result == "example.com/path"---def test_template_with_remote_url() -> None:- """Test _template function with remote URL"""-- mock_request = MagicMock()- mock_request.headers.get.return_value = "https://example.com"-- with patch("marimo._plugins.stateless.mpl._mpl.app_meta") as mock_app_meta:- mock_app_meta.return_value.request = mock_request-- result = _template("test_fig", 8080)-- assert "wss://example.com/mpl/8080/ws?figure=test_fig" in result- assert "://example.com/mpl/test_fig" in result---def test_template_without_remote_url() -> None:- """Test _template function without remote URL"""-- with patch("marimo._plugins.stateless.mpl._mpl.app_meta") as mock_app_meta:- mock_app_meta.return_value.request = None-- result = _template("test_fig", 8080)-- assert "/mpl/8080/ws?figure=test_fig" in result- assert "/mpl/test_fig" in result---def test_template_contains_html_structure() -> None:- """Test _template function contains proper HTML structure"""-- with patch("marimo._plugins.stateless.mpl._mpl.app_meta") as mock_app_meta:- mock_app_meta.return_value.request = None-- result = _template("12345", 9000)-- assert "<!DOCTYPE html>" in result- assert '<html lang="en">' in result- assert "<head>" in result- assert "<body>" in result- assert '<div id="figure"></div>' in result- assert "12345" in result- assert "9000" in result---def test_template_contains_visibilitychange_refresh() -> None:- """Test that template includes visibilitychange listener to refresh- figures when the browser tab becomes visible again.-- Regression test for https://github.com/marimo-team/marimo/issues/2092:- plots rendered while the tab is hidden appear blank because browsers- throttle canvas rendering in background tabs.- """-- with patch("marimo._plugins.stateless.mpl._mpl.app_meta") as mock_app_meta:- mock_app_meta.return_value.request = None-- result = _template("12345", 9000)-- assert "visibilitychange" in result- assert "document.hidden" in result- assert 'send_message("refresh"' in result---def test_mpl_server_manager() -> None:- """Test MplServerManager basic functionality"""- from marimo._plugins.stateless.mpl._mpl import MplServerManager-- manager = MplServerManager()-- # Initially should not be running- assert not manager.is_running()-- # Mock threading.Thread to avoid actually starting a server- with patch("threading.Thread") as mock_thread_class:- mock_thread = MagicMock()- mock_thread.is_alive.return_value = True- mock_thread_class.return_value = mock_thread-- # Start should create and return an app- app = manager.start(app_host="localhost", free_port=12345)-- # Should now be running- assert manager.is_running()-- # Verify app state- assert app.state.host == "localhost"- assert app.state.port == 12345-- # Thread should have been started- mock_thread.start.assert_called_once()-- # Stop should mark as not running- manager.stop()- assert not manager.is_running()---def test_get_or_create_application_with_restart() -> None:- """Test get_or_create_application handles server restart"""- from marimo._plugins.stateless.mpl._mpl import (- _server_manager,- figure_managers,- get_or_create_application,- )-- # Clear any existing state- globals()["_app"] = None- figure_managers.figure_managers.clear()-- with patch("threading.Thread") as mock_thread_class:- # First thread: running- mock_thread1 = MagicMock()- mock_thread1.is_alive.return_value = True-- # Second thread: also running (for restart)- mock_thread2 = MagicMock()- mock_thread2.is_alive.return_value = True-- mock_thread_class.side_effect = [mock_thread1, mock_thread2]-- # First call should create app- app1 = get_or_create_application()- assert app1 is not None- assert _server_manager.is_running()-- # Simulate server death- mock_thread1.is_alive.return_value = False-- # Add a figure to test cleanup- figure_managers.figure_managers["test"] = MagicMock()-- # Next call should restart server and clear figures- app2 = get_or_create_application()- assert app2 is not None- assert app2 is not app1 # Should be a new app instance- assert (- len(figure_managers.figure_managers) == 0- ) # Figures should be cleared-- # Should have started two threads (original + restart)- assert mock_thread_class.call_count == 2--@pytest.mark.requires("matplotlib")def test_mpl_interactive_fallback_when_virtual_files_not_supported() -> None:"""Test that mpl.interactive falls back to PNG when virtual_files_supported=False."""@@ -382,8 +114,8 @@ def test_mpl_interactive_fallback_when_virtual_files_not_supported() -> None:# Should return Html objectassert isinstance(result, Html)- # Should NOT contain iframe (interactive mode)- assert "iframe" not in result.text.lower()+ # Should NOT contain the interactive plugin+ assert "marimo-mpl-interactive" not in result.text# Should contain a PNG mimetypeassert result._mime_()[0] == "image/png"diff --git a/tests/_plugins/ui/_impl/test_from_mpl_interactive.py b/tests/_plugins/ui/_impl/test_from_mpl_interactive.pynew file mode 100644index 0000000000..37ed0d5510--- /dev/null+++ b/tests/_plugins/ui/_impl/test_from_mpl_interactive.py@@ -0,0 +1,362 @@+# Copyright 2026 Marimo. All rights reserved.+from __future__ import annotations++from typing import Any+from unittest.mock import MagicMock, patch++import pytest++[email protected]("matplotlib")+class TestSyncWebSocket:+ """Test the _SyncWebSocket adapter that bridges FigureManager to MarimoComm."""++ def _make_ws(self) -> tuple[Any, MagicMock]:+ from marimo._plugins.ui._impl.from_mpl_interactive import (+ _SyncWebSocket,+ )++ mock_comm = MagicMock()+ ws = _SyncWebSocket(mock_comm)+ return ws, mock_comm++ def test_send_json(self) -> None:+ ws, mock_comm = self._make_ws()+ ws.send_json({"type": "figure_size", "width": 640})+ mock_comm.send.assert_called_once_with(+ data={+ "method": "custom",+ "content": {+ "type": "json",+ "data": {"type": "figure_size", "width": 640},+ },+ },+ )++ def test_send_binary(self) -> None:+ ws, mock_comm = self._make_ws()+ blob = b"\x89PNG\r\n\x1a\n" + b"\x00" * 100+ ws.send_binary(blob)+ mock_comm.send.assert_called_once_with(+ data={+ "method": "custom",+ "content": {"type": "binary"},+ },+ buffers=[blob],+ )++[email protected]("matplotlib")+class TestHandleCommMsg:+ """Test message parsing in mpl_interactive._handle_comm_msg.++ The comm payload from ModelCommand.into_comm_payload() is nested:+ {"content": {"data": {"method": "custom", "content": <mpl_event>}}}+ """++ def _make_element(self) -> Any:+ import matplotlib.pyplot as plt++ from marimo._plugins.ui._impl.from_mpl_interactive import (+ mpl_interactive,+ )++ fig, ax = plt.subplots()+ ax.plot([1, 2, 3])+ with patch("marimo._plugins.ui._impl.comm.broadcast_notification"):+ element = mpl_interactive(fig)+ return element, fig++ def _wrap_event(self, event: dict[str, Any]) -> dict[str, Any]:+ """Wrap an mpl event in the ModelCommand payload structure."""+ return {+ "content": {+ "data": {+ "method": "custom",+ "content": event,+ },+ },+ }++ def test_supports_binary_ignored(self) -> None:+ element, fig = self._make_element()+ # Should not raise+ element._handle_comm_msg(+ self._wrap_event({"type": "supports_binary", "value": True})+ )+ import matplotlib.pyplot as plt++ plt.close(fig)++ def test_mouse_event_forwarded(self) -> None:+ element, fig = self._make_element()+ event = {+ "type": "motion_notify",+ "x": 100,+ "y": 200,+ "figure_id": str(id(fig)),+ }+ with patch.object(+ element._figure_manager, "handle_json"+ ) as mock_handle:+ element._handle_comm_msg(self._wrap_event(event))+ mock_handle.assert_called_once_with(event)++ import matplotlib.pyplot as plt++ plt.close(fig)++ def test_download_request(self) -> None:+ element, fig = self._make_element()+ with patch.object(element, "_handle_download") as mock_dl:+ element._handle_comm_msg(+ self._wrap_event({"type": "download", "format": "svg"})+ )+ mock_dl.assert_called_once_with("svg")++ import matplotlib.pyplot as plt++ plt.close(fig)++ def test_download_default_format(self) -> None:+ element, fig = self._make_element()+ with patch.object(element, "_handle_download") as mock_dl:+ element._handle_comm_msg(self._wrap_event({"type": "download"}))+ mock_dl.assert_called_once_with("png")++ import matplotlib.pyplot as plt++ plt.close(fig)++ def test_empty_message_does_not_crash(self) -> None:+ element, fig = self._make_element()+ # Empty message — no "type" key, should still call handle_json+ with patch.object(+ element._figure_manager, "handle_json"+ ) as mock_handle:+ element._handle_comm_msg({"content": {"data": {}}})+ mock_handle.assert_called_once_with({})++ import matplotlib.pyplot as plt++ plt.close(fig)++[email protected]("matplotlib")+class TestHandleDownload:+ """Test that _handle_download renders the figure and sends it via comm."""++ def test_download_produces_valid_png(self) -> None:+ import matplotlib.pyplot as plt++ from marimo._plugins.ui._impl.from_mpl_interactive import (+ mpl_interactive,+ )++ fig, ax = plt.subplots()+ ax.plot([1, 2, 3])++ with patch("marimo._plugins.ui._impl.comm.broadcast_notification"):+ element = mpl_interactive(fig)++ sent_data: list[dict[str, Any]] = []+ sent_buffers: list[list[Any]] = []++ def capture_send(data: Any, buffers: Any = None) -> None:+ sent_data.append(data)+ sent_buffers.append(buffers or [])++ element._comm.send = capture_send # type: ignore[assignment]++ element._handle_download("png")++ assert len(sent_data) == 1+ assert sent_data[0]["content"]["type"] == "download"+ assert sent_data[0]["content"]["format"] == "png"+ assert len(sent_buffers[0]) == 1+ # Verify it's valid PNG+ assert sent_buffers[0][0][:4] == b"\x89PNG"++ plt.close(fig)++[email protected]("matplotlib")+class TestMplCleanupHandle:+ """Test that _MplCleanupHandle properly closes the comm."""++ def test_dispose_closes_comm(self) -> None:+ from marimo._plugins.ui._impl.from_mpl_interactive import (+ _MplCleanupHandle,+ )++ mock_comm = MagicMock()+ handle = _MplCleanupHandle(mock_comm)+ result = handle.dispose(context=MagicMock(), deletion=False)++ assert result is True+ mock_comm.close.assert_called_once()++ def test_dispose_on_deletion(self) -> None:+ from marimo._plugins.ui._impl.from_mpl_interactive import (+ _MplCleanupHandle,+ )++ mock_comm = MagicMock()+ handle = _MplCleanupHandle(mock_comm)+ result = handle.dispose(context=MagicMock(), deletion=True)++ assert result is True+ mock_comm.close.assert_called_once()++[email protected]("matplotlib")+class TestMplInteractiveArgs:+ """Test that mpl_interactive passes correct args to the UIElement."""++ def test_initial_dimensions(self) -> None:+ import matplotlib+ import matplotlib.pyplot as plt++ from marimo._plugins.ui._impl.from_mpl_interactive import (+ mpl_interactive,+ )++ fig, ax = plt.subplots(figsize=(8, 6))+ ax.plot([1, 2, 3])++ with patch("marimo._plugins.ui._impl.comm.broadcast_notification"):+ element = mpl_interactive(fig)++ dpi = matplotlib.rcParams["figure.dpi"]+ expected_w = int(8 * dpi)+ expected_h = int(6 * dpi)+ # Args are rendered as data-* attributes in HTML+ assert f"data-width='{expected_w}'" in element.text+ assert f"data-height='{expected_h}'" in element.text++ plt.close(fig)++ def test_virtual_file_urls_in_args(self) -> None:+ import matplotlib.pyplot as plt++ from marimo._plugins.ui._impl.from_mpl_interactive import (+ mpl_interactive,+ )++ fig, ax = plt.subplots()+ ax.plot([1, 2, 3])++ with patch("marimo._plugins.ui._impl.comm.broadcast_notification"):+ element = mpl_interactive(fig)++ # Args should contain URL references, not inline content+ assert "mpl-js-url" in element.text+ assert "css-url" in element.text+ assert "toolbar-images" in element.text+ # URLs should be virtual file paths or data URIs+ text = element.text+ assert ".js" in text or "data:" in text+ assert ".css" in text or "data:" in text++ plt.close(fig)++ def test_component_name(self) -> None:+ import matplotlib.pyplot as plt++ from marimo._plugins.ui._impl.from_mpl_interactive import (+ mpl_interactive,+ )++ fig, ax = plt.subplots()+ ax.plot([1, 2, 3])++ with patch("marimo._plugins.ui._impl.comm.broadcast_notification"):+ element = mpl_interactive(fig)++ assert "marimo-mpl-interactive" in element.text+ plt.close(fig)++ def test_convert_value_returns_empty_dict(self) -> None:+ import matplotlib.pyplot as plt++ from marimo._plugins.ui._impl.from_mpl_interactive import (+ mpl_interactive,+ )++ fig, ax = plt.subplots()+ ax.plot([1, 2, 3])++ with patch("marimo._plugins.ui._impl.comm.broadcast_notification"):+ element = mpl_interactive(fig)++ assert element._convert_value({"model_id": "abc"}) == {}+ plt.close(fig)+++class TestScopeCss:+ """Test that _scope_css uses native CSS nesting."""++ def test_wraps_rules_in_scope(self) -> None:+ from marimo._plugins.ui._impl.from_mpl_interactive import _scope_css++ css = ".toolbar { display: flex; }\n.btn { color: red; }"+ result = _scope_css(css, ".my-scope")+ assert result.startswith(".my-scope {")+ assert result.endswith("}")+ assert ".toolbar { display: flex; }" in result+ assert ".btn { color: red; }" in result++ def test_keyframes_preserved(self) -> None:+ from marimo._plugins.ui._impl.from_mpl_interactive import _scope_css++ css = "@keyframes spin { from { transform: rotate(0); } to { transform: rotate(360deg); } }"+ result = _scope_css(css, ".s")+ assert "@keyframes spin" in result++ def test_media_query_preserved(self) -> None:+ from marimo._plugins.ui._impl.from_mpl_interactive import _scope_css++ css = "@media (max-width: 600px) { .x { display: none; } }"+ result = _scope_css(css, ".s")+ assert "@media (max-width: 600px)" in result++[email protected]("matplotlib")+class TestCachedAssets:+ """Test that static assets are cached across instances."""++ def test_toolbar_images_cached(self) -> None:+ from marimo._plugins.ui._impl.from_mpl_interactive import (+ _get_toolbar_images,+ )++ # Clear the cache to test from scratch+ _get_toolbar_images.cache_clear()++ images1 = _get_toolbar_images()+ images2 = _get_toolbar_images()+ assert images1 is images2+ assert len(images1) > 0+ # All values should be data URIs+ for key, val in images1.items():+ assert val.startswith("data:image/png;base64,"), key++ def test_mpl_css_content(self) -> None:+ from marimo._plugins.ui._impl.from_mpl_interactive import (+ _get_mpl_css,+ )++ css = _get_mpl_css()+ assert isinstance(css, str)+ assert len(css) > 0+ # Should contain our custom overrides+ assert "mpl-toolbar" in css++ def test_patched_js_has_focus_patches(self) -> None:+ from marimo._plugins.ui._impl.from_mpl_interactive import (+ _get_patched_mpl_js,+ )++ js = _get_patched_mpl_js()+ assert "// canvas.focus();" in js+ assert "// canvas_div.focus();" in jsdiff --git a/tests/_server/api/endpoints/test_mpl_endpoints.py b/tests/_server/api/endpoints/test_mpl_endpoints.pydeleted file mode 100644index bfb7074ae7..0000000000--- a/tests/_server/api/endpoints/test_mpl_endpoints.py+++ /dev/null@@ -1,183 +0,0 @@-# Copyright 2026 Marimo. All rights reserved.-from __future__ import annotations--from typing import TYPE_CHECKING-from unittest.mock import AsyncMock, MagicMock, patch--from marimo._server.api.endpoints.mpl import WS_MAX_SIZE, figure_endpoints--if TYPE_CHECKING:- from starlette.testclient import TestClient---class TestMatplotlibProxyEndpoints:- """Tests for matplotlib proxy endpoints."""-- def setup_method(self) -> None:- """Clear figure_endpoints before each test."""- figure_endpoints.clear()-- def teardown_method(self) -> None:- """Clean up after each test."""- figure_endpoints.clear()-- @staticmethod- def test_http_requires_auth(client: TestClient) -> None:- """Test that HTTP proxy requires authentication."""- figure_endpoints[1] = "8888"-- # Mock validate_auth to return False (unauthenticated)- with patch(- "marimo._server.api.endpoints.mpl.validate_auth",- return_value=False,- ):- response = client.get("/mpl/1/test_path")- assert response.status_code == 401, response.text- assert "Unauthorized" in response.text-- @staticmethod- def test_unauthorized_figure_returns_403(client: TestClient) -> None:- """Test that accessing unregistered figure returns 403."""- # Mock auth to pass, but figure not registered- with patch(- "marimo._server.api.endpoints.mpl.validate_auth", return_value=True- ):- response = client.get("/mpl/999/some_path")- assert response.status_code == 403, response.text- assert "Unauthorized" in response.text-- @staticmethod- def test_connection_error_returns_503(client: TestClient) -> None:- """Test connection failure returns 503."""- figure_endpoints[1] = "8888"-- with patch(- "marimo._server.api.endpoints.mpl.validate_auth", return_value=True- ):- with patch("urllib.request.urlopen") as mock_urlopen:- from urllib.error import URLError-- mock_urlopen.side_effect = URLError("Connection refused")- response = client.get("/mpl/1/test_path")- assert response.status_code == 503, response.text- assert "Matplotlib server is not available" in response.text-- @staticmethod- def test_successful_proxy(client: TestClient) -> None:- """Test successful proxying to matplotlib server."""- figure_endpoints[1] = "8888"-- with patch(- "marimo._server.api.endpoints.mpl.validate_auth", return_value=True- ):- with patch("urllib.request.urlopen") as mock_urlopen:- mock_response = MagicMock()- mock_response.status = 200- mock_response.headers = {"content-type": "text/html"}- mock_response.read.return_value = b"<html>Success</html>"- mock_urlopen.return_value.__enter__.return_value = (- mock_response- )-- response = client.get("/mpl/1/test")- assert response.status_code == 200, response.text- assert response.text == "<html>Success</html>"-- @staticmethod- def test_query_params_forwarded(client: TestClient) -> None:- """Test query parameters are forwarded to matplotlib server."""- figure_endpoints[1] = "8888"-- with patch(- "marimo._server.api.endpoints.mpl.validate_auth", return_value=True- ):- with patch("urllib.request.urlopen") as mock_urlopen:- mock_response = MagicMock()- mock_response.status = 200- mock_response.headers = {}- mock_response.read.return_value = b""- mock_urlopen.return_value.__enter__.return_value = (- mock_response- )-- client.get("/mpl/1/test?param1=value1¶m2=value2")-- request_obj = mock_urlopen.call_args[0][0]- assert "param1=value1" in request_obj.full_url- assert "param2=value2" in request_obj.full_url-- @staticmethod- def test_headers_filtered(client: TestClient) -> None:- """Test that problematic headers (host, content-length) are filtered."""- figure_endpoints[1] = "8888"-- with patch(- "marimo._server.api.endpoints.mpl.validate_auth", return_value=True- ):- with patch("urllib.request.urlopen") as mock_urlopen:- mock_response = MagicMock()- mock_response.status = 200- mock_response.headers = {}- mock_response.read.return_value = b""- mock_urlopen.return_value.__enter__.return_value = (- mock_response- )-- client.get("/mpl/1/test")-- request_obj = mock_urlopen.call_args[0][0]- assert "Host" not in request_obj.headers- assert "Content-length" not in request_obj.headers-- @staticmethod- def test_websocket_requires_auth(client: TestClient) -> None:- """Test that WebSocket connection requires authentication."""- from starlette.websockets import WebSocketDisconnect-- # Mock validate_auth to return False (unauthenticated)- with patch(- "marimo._server.api.endpoints.mpl.validate_auth",- return_value=False,- ):- try:- with client.websocket_connect("/mpl/8888/ws"):- pass- except WebSocketDisconnect:- # Expected - connection should be rejected- pass-- @staticmethod- def test_websocket_authenticated_connects(client: TestClient) -> None:- """Test that authenticated WebSocket connection succeeds."""- from starlette.websockets import WebSocketDisconnect-- # Mock validate_auth to return True (authenticated)- with patch(- "marimo._server.api.endpoints.mpl.validate_auth", return_value=True- ):- with patch("websockets.connect") as mock_connect:- mock_ws = MagicMock()- mock_context = MagicMock()- mock_context.__aenter__ = AsyncMock(return_value=mock_ws)- mock_context.__aexit__ = AsyncMock(return_value=None)- mock_connect.return_value = mock_context-- async def mock_iter():- return- yield-- mock_ws.__aiter__ = mock_iter-- try:- with client.websocket_connect("/mpl/8888/ws?figure=123"):- pass- except WebSocketDisconnect:- pass-- # Verify websockets.connect was called with correct port- mock_connect.assert_called()- call_url = mock_connect.call_args[0][0]- assert "localhost:8888" in call_url- # Verify max_size is set to handle large matplotlib PNGs- call_kwargs = mock_connect.call_args[1]- assert call_kwargs.get("max_size") == WS_MAX_SIZEdiff --git a/tests/_server/api/test_middleware.py b/tests/_server/api/test_middleware.pyindex 2bd8b23ff8..de51464b58 100644--- a/tests/_server/api/test_middleware.py+++ b/tests/_server/api/test_middleware.py@@ -32,7 +32,6 @@ from marimo._server.main import (from marimo._server.session_manager import SessionManagerfrom marimo._server.tokens import AuthTokenfrom marimo._session.model import SessionMode-from marimo._utils.net import find_free_portfrom tests._server.conftest import join_kernel_thread_tasksfrom tests._server.mocks import get_mock_session_manager, token_header@@ -330,22 +329,6 @@ def run_target_server():server.run()-def run_mpl_server(host: str, port: int):- """Runs the matplotlib plugin server.- Defined at module level so it can be pickled."""- from marimo._plugins.stateless.mpl._mpl import (- create_application, # Import here to avoid circular imports- )-- app = create_application()- app.state.host = host- app.state.port = port- app.state.secure = False- config = Config(app=app, host=host, port=port, log_level="info")- server = Server(config)- server.run()--async def serve_static(request: Request) -> Response:del requestcontent = "body { color: red; }"@@ -399,35 +382,6 @@ class TestProxyMiddleware:)return edit_app- @pytest.fixture(scope="module")- def mpl_server(self):- """Start the matplotlib plugin server in a separate process."""- host = "127.0.0.1"- port = find_free_port(10_000)-- process = Process(- target=run_mpl_server, args=(host, port), daemon=True- )- process.start()- time.sleep(1)- yield host, port- process.terminate()- process.join()-- @pytest.fixture- def app_with_mpl_proxy(- self, edit_app: Starlette, mpl_server: tuple[str, int]- ) -> ASGIApp:- """Create the app with ProxyMiddleware targeting the matplotlib plugin server."""- host, port = mpl_server- target_url = f"http://{host}:{port}"- edit_app.add_middleware(- ProxyMiddleware,- proxy_path="/mpl",- target_url=target_url,- )- return edit_app-@pytest.fixture(scope="module")def static_server(self):"""Start a separate server for static files."""@@ -620,25 +574,6 @@ class TestProxyMiddleware:response_3 = websocket.receive_json()assert response_3["message"] == "ws response from proxied app"- @pytest.mark.xfail(- reason="Returning 403 instead of invalid ID message",- )- @pytest.mark.skipif(- sys.platform == "win32",- reason="Skipping test on Windows due to websocket issues",- )- def test_proxy_websocket_with_invalid_id(- self, app_with_mpl_proxy: Starlette- ) -> None:- client = TestClient(app_with_mpl_proxy)- with client.websocket_connect(- "/mpl/ws?figure=invalid_id",- ) as websocket:- websocket.send_json({"type": "supports_binary", "value": True})- message = websocket.receive_json()- assert message["type"] == "error"- assert "invalid" in message["message"].lower()-async def test_proxy_middleware_websocket_protocol(self, monkeypatch: pytest.MonkeyPatch) -> None:@@ -687,8 +622,6 @@ class TestProxyMiddleware:await middleware(scope, None, None)assert proxy_calls[-1] == "wss://example.com/proxy/test"- # Could be good to go on to test the happy path for mpl but we're already doing that with the test client above so leaving just this invalid ID test for-def _mock_lsp_server(server_id: str, port: int):"""Helper to create a mock LSP server."""