Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

fix: mpl.interactive with remote backends (#5662)

Myles Scolnicka701d678f7d7
diff --git a/frontend/src/core/runtime/__tests__/runtime.test.ts b/frontend/src/core/runtime/__tests__/runtime.test.ts
index 7ea7a4a15a..8867fc456d 100644
--- a/frontend/src/core/runtime/__tests__/runtime.test.ts
+++ b/frontend/src/core/runtime/__tests__/runtime.test.ts
@@ -244,6 +244,7 @@ describe("RuntimeManager", () => {
"Authorization": "Bearer test-token",
"Marimo-Server-Token": "",
"Marimo-Session-Id": "test-session-id",
+ "x-runtime-url": "https://example.com/",
}
`);
});
@@ -255,6 +256,7 @@ describe("RuntimeManager", () => {
expect(headers).toEqual({
"Marimo-Session-Id": "test-session-id",
"Marimo-Server-Token": "",
+ "x-runtime-url": "http://localhost:8080/",
});
});
});
diff --git a/frontend/src/core/runtime/runtime.ts b/frontend/src/core/runtime/runtime.ts
index a1ee8adf61..4bdc504335 100644
--- a/frontend/src/core/runtime/runtime.ts
+++ b/frontend/src/core/runtime/runtime.ts
@@ -212,6 +212,10 @@ export class RuntimeManager {
const headers: Record<string, string> = {
"Marimo-Session-Id": getSessionId(),
"Marimo-Server-Token": this.config.serverToken ?? "",
+ // Needed for widgets that need absolute URLs when embedding in an iframe
+ // e.g. mpl.interactive()
+ // We don't prefix with `marimo` since those get stripped internally
+ "x-runtime-url": this.httpURL.toString(),
};
if (this.config.authToken) {
diff --git a/marimo/_plugins/stateless/mpl/_mpl.py b/marimo/_plugins/stateless/mpl/_mpl.py
index d610bbed23..a94f64c269 100644
--- a/marimo/_plugins/stateless/mpl/_mpl.py
+++ b/marimo/_plugins/stateless/mpl/_mpl.py
@@ -29,6 +29,7 @@ from marimo._runtime.context import (
get_context,
)
from marimo._runtime.context.kernel_context import KernelRuntimeContext
+from marimo._runtime.runtime import app_meta
from marimo._server.utils import find_free_port
from marimo._utils.platform import is_pyodide
from marimo._utils.signals import get_signals
@@ -101,11 +102,34 @@ def _get_secure() -> bool:
)
+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()
+ base_url_and_path = f"{base_url}/mpl/{port}"
+ ws_base_url = _convert_scheme_to_ws(base_url_and_path)
+
return html_content % {
- "ws_uri": f"/mpl/{port}/ws?figure={fig_id}",
+ "ws_uri": f"{ws_base_url}/ws?figure={fig_id}",
"fig_id": fig_id,
- "port": port,
+ "base_url": base_url_and_path,
}
@@ -405,13 +429,13 @@ html_content = """
<!DOCTYPE html>
<html lang="en">
<head>
- <base href='/mpl/%(port)s/ ' />
- <link rel="stylesheet" href="/mpl/%(port)s/_static/css/page.css" type="text/css" />
- <link rel="stylesheet" href="/mpl/%(port)s/_static/css/boilerplate.css" type="text/css" />
- <link rel="stylesheet" href="/mpl/%(port)s/_static/css/fbm.css" type="text/css" />
- <link rel="stylesheet" href="/mpl/%(port)s/_static/css/mpl.css" type="text/css" />
- <link rel="stylesheet" href="/mpl/%(port)s/custom.css" type="text/css" />
- <script src="/mpl/%(port)s/mpl.js"></script>
+ <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) {
diff --git a/marimo/_server/main.py b/marimo/_server/main.py
index 0ea1205e59..2f472421c1 100644
--- a/marimo/_server/main.py
+++ b/marimo/_server/main.py
@@ -88,7 +88,7 @@ def create_starlette_app(
allow_methods=["*"],
allow_headers=["*"],
),
- _create_mpl_proxy_middleware(),
+ _create_mpl_proxy_middleware(base_url=base_url),
]
)
@@ -118,21 +118,54 @@ def create_starlette_app(
)
-def _create_mpl_proxy_middleware() -> Middleware:
- # MPL proxy logic
+def _create_mpl_proxy_middleware(base_url: str) -> Middleware:
+ # Construct the full proxy path with base_url
+ # Normalize base_url to avoid double slashes
+ normalized_base_url = base_url.rstrip("/")
+ proxy_path = f"{normalized_base_url}/mpl"
+
def mpl_target_url(path: str) -> str:
- # Path format: /mpl/<port>/rest/of/path
- port = path.split("/", 3)[2]
+ # Path format: {base_url}/mpl/<port>/rest/of/path
+ # Remove the proxy_path prefix to get /<port>/rest/of/path
+ if not path.startswith(proxy_path):
+ raise ValueError(
+ f"Path {path} does not start with proxy path {proxy_path}"
+ )
+
+ remaining = path[len(proxy_path) :]
+ if not remaining.startswith("/"):
+ raise ValueError(f"Invalid MPL path format: {path}")
+
+ # Parse /<port>/rest/of/path to get the port
+ parts = remaining.split("/")
+ if len(parts) < 2 or not parts[1]:
+ raise ValueError(f"Invalid MPL path format: {path}")
+
+ port = parts[1]
return f"http://localhost:{port}"
def mpl_path_rewrite(path: str) -> str:
- # Remove the /mpl/<port>/ prefix
- rest = path.split("/", 3)[3]
- return f"/{rest}"
+ # Remove the {base_url}/mpl/<port>/ prefix
+ # Remove the proxy_path prefix first
+ if not path.startswith(proxy_path):
+ return "/"
+
+ remaining = path[len(proxy_path) :]
+ if not remaining.startswith("/"):
+ return "/"
+
+ # Parse /<port>/rest/of/path and return /rest/of/path
+ parts = remaining.split("/")
+ if len(parts) < 2:
+ return "/"
+
+ # Skip the empty first part and the port to get the rest
+ rest_parts = parts[2:]
+ return "/" + "/".join(rest_parts) if rest_parts else "/"
return Middleware(
ProxyMiddleware,
- proxy_path="/mpl",
+ proxy_path=proxy_path,
target_url=mpl_target_url,
path_rewrite=mpl_path_rewrite,
)
diff --git a/marimo/_smoke_tests/iplot.py b/marimo/_smoke_tests/iplot.py
index 88c62456d8..586b1e5ea1 100644
--- a/marimo/_smoke_tests/iplot.py
+++ b/marimo/_smoke_tests/iplot.py
@@ -1,12 +1,19 @@
# Copyright 2024 Marimo. All rights reserved.
+
import marimo
-__generated_with = "0.1.18"
+__generated_with = "0.14.11"
app = marimo.App()
@app.cell
-def __():
+def _(mo):
+ mo.app_meta().request
+ return
+
+
+def _():
import marimo as mo
import numpy as np
import matplotlib.pyplot as plt
@@ -14,8 +21,8 @@ def __():
@app.cell
-def __(mo, np, plt):
- def interactive_plot(seed = 42, size=100):
+def _(mo, np, plt):
+ def interactive_plot(seed=42, size=100):
# Generating random data
np.random.seed(seed)
x = np.random.randint(0, 100, size=size)
@@ -24,39 +31,39 @@ def __(mo, np, plt):
# Creating a 3D scatter plot
fig = plt.figure()
- ax = fig.add_subplot(111, projection='3d')
- ax.scatter(x, y, z, c='r', marker='o')
+ ax = fig.add_subplot(111, projection="3d")
+ ax.scatter(x, y, z, c="r", marker="o")
- ax.set_xlabel('X Label')
- ax.set_ylabel('Y Label')
- ax.set_zlabel('Z Label')
+ ax.set_xlabel("X Label")
+ ax.set_ylabel("Y Label")
+ ax.set_zlabel("Z Label")
return mo.mpl.interactive(fig)
- return interactive_plot,
+ return (interactive_plot,)
@app.cell
-def __(interactive_plot):
+def _(interactive_plot):
interactive_plot(size=10)
return
@app.cell
-def __(interactive_plot):
+def _(interactive_plot):
b = interactive_plot(size=20)
b
- return b,
+ return
@app.cell
-def __(mo, plt):
+def _(mo, plt):
plt.plot([1, 2])
mo.mpl.interactive(plt.gca())
return
@app.cell
-def __(plt):
+def _(plt):
plt.plot([3, 4])
return
diff --git a/tests/_plugins/stateless/test_mpl.py b/tests/_plugins/stateless/test_mpl.py
index 5ffebf8582..130459f1a4 100644
--- a/tests/_plugins/stateless/test_mpl.py
+++ b/tests/_plugins/stateless/test_mpl.py
@@ -1,11 +1,16 @@
from __future__ import annotations
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
import pytest
from marimo._dependencies.dependencies import DependencyManager
from marimo._output.hypertext import Html
+from marimo._plugins.stateless.mpl._mpl import (
+ _convert_scheme_to_ws,
+ _get_remote_url,
+ _template,
+)
from marimo._runtime.requests import DeleteCellRequest
from marimo._runtime.runtime import Kernel
from tests.conftest import ExecReqProvider
@@ -80,3 +85,132 @@ def test_patch_javascript() -> None:
javascript = patch_javascript(javascript)
assert javascript.count("// canvas.focus();") == 1
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 "test_fig" in result
+ assert "https://example.com/mpl/8080" 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 "test_fig" in result
+ assert "/mpl/8080" 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
diff --git a/tests/_server/api/test_middleware.py b/tests/_server/api/test_middleware.py
index 9de9a56e98..14e9ebc9dd 100644
--- a/tests/_server/api/test_middleware.py
+++ b/tests/_server/api/test_middleware.py
@@ -6,7 +6,7 @@ import json
import sys
import time
from multiprocessing import Process
-from typing import TYPE_CHECKING, Any
+from typing import TYPE_CHECKING, Any, Callable
import pytest
import uvicorn
@@ -23,7 +23,10 @@ from marimo._server.api.middleware import (
_AsyncHTTPClient,
_URLRequest,
)
-from marimo._server.main import create_starlette_app
+from marimo._server.main import (
+ _create_mpl_proxy_middleware,
+ create_starlette_app,
+)
from marimo._server.model import SessionMode
from marimo._server.tokens import AuthToken
from marimo._server.utils import find_free_port
@@ -667,3 +670,196 @@ class TestProxyMiddleware:
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
+
+
+class TestMplProxyMiddleware:
+ def test_mpl_proxy_middleware_no_base_url(self):
+ """Test MPL proxy middleware with empty base_url."""
+ middleware = _create_mpl_proxy_middleware("")
+
+ # Check that the middleware is created correctly
+ assert middleware.cls == ProxyMiddleware
+ assert middleware.kwargs["proxy_path"] == "/mpl"
+
+ # Test target_url function
+ target_url_func: Callable[[str], str] = middleware.kwargs["target_url"]
+ assert (
+ target_url_func("/mpl/8080/some/path") == "http://localhost:8080"
+ )
+
+ # Test path_rewrite function
+ path_rewrite_func: Callable[[str], str] = middleware.kwargs[
+ "path_rewrite"
+ ]
+ assert path_rewrite_func("/mpl/8080/some/path") == "/some/path"
+ assert path_rewrite_func("/mpl/8080/") == "/"
+ assert path_rewrite_func("/mpl/8080") == "/"
+
+ def test_mpl_proxy_middleware_with_base_url(self):
+ """Test MPL proxy middleware with base_url."""
+ middleware = _create_mpl_proxy_middleware("/foo")
+
+ # Check that the middleware is created correctly
+ assert middleware.cls == ProxyMiddleware
+ assert middleware.kwargs["proxy_path"] == "/foo/mpl"
+
+ # Test target_url function
+ target_url_func = middleware.kwargs["target_url"]
+ assert (
+ target_url_func("/foo/mpl/8080/some/path")
+ == "http://localhost:8080"
+ )
+
+ # Test path_rewrite function
+ path_rewrite_func: Callable[[str], str] = middleware.kwargs[
+ "path_rewrite"
+ ]
+ assert path_rewrite_func("/foo/mpl/8080/some/path") == "/some/path"
+ assert path_rewrite_func("/foo/mpl/8080/") == "/"
+ assert path_rewrite_func("/foo/mpl/8080") == "/"
+
+ def test_mpl_proxy_middleware_with_base_url_trailing_slash(self):
+ """Test MPL proxy middleware with base_url that has trailing slash."""
+ middleware = _create_mpl_proxy_middleware("/foo/")
+
+ # Check that the middleware is created correctly
+ assert middleware.cls == ProxyMiddleware
+ assert middleware.kwargs["proxy_path"] == "/foo/mpl"
+
+ # Test target_url function
+ target_url_func: Callable[[str], str] = middleware.kwargs["target_url"]
+ assert (
+ target_url_func("/foo/mpl/8080/some/path")
+ == "http://localhost:8080"
+ )
+
+ # Test path_rewrite function
+ path_rewrite_func = middleware.kwargs["path_rewrite"]
+ assert path_rewrite_func("/foo/mpl/8080/some/path") == "/some/path"
+
+ def test_mpl_proxy_middleware_complex_paths(self):
+ """Test MPL proxy middleware with complex paths."""
+ middleware = _create_mpl_proxy_middleware("/api/v1")
+
+ # Check that the middleware is created correctly
+ assert middleware.cls == ProxyMiddleware
+ assert middleware.kwargs["proxy_path"] == "/api/v1/mpl"
+
+ # Test target_url function
+ target_url_func = middleware.kwargs["target_url"]
+ assert (
+ target_url_func("/api/v1/mpl/9000/static/css/style.css")
+ == "http://localhost:9000"
+ )
+
+ # Test path_rewrite function
+ path_rewrite_func: Callable[[str], str] = middleware.kwargs[
+ "path_rewrite"
+ ]
+ assert (
+ path_rewrite_func("/api/v1/mpl/9000/static/css/style.css")
+ == "/static/css/style.css"
+ )
+
+ def test_mpl_proxy_middleware_target_url_errors(self):
+ """Test error cases for target_url function."""
+ middleware = _create_mpl_proxy_middleware("/foo")
+ target_url_func = middleware.kwargs["target_url"]
+
+ # Test with wrong prefix
+ with pytest.raises(
+ ValueError,
+ match="Path /bar/mpl/8080/path does not start with proxy path /foo/mpl",
+ ):
+ target_url_func("/bar/mpl/8080/path")
+
+ # Test with no port
+ with pytest.raises(ValueError, match="Invalid MPL path format"):
+ target_url_func("/foo/mpl/")
+
+ # Test with no slash after proxy_path
+ with pytest.raises(ValueError, match="Invalid MPL path format"):
+ target_url_func("/foo/mpl8080/path")
+
+ def test_mpl_proxy_middleware_path_rewrite_edge_cases(self):
+ """Test edge cases for path_rewrite function."""
+ middleware = _create_mpl_proxy_middleware("/foo")
+ path_rewrite_func: Callable[[str], str] = middleware.kwargs[
+ "path_rewrite"
+ ]
+
+ # Test with wrong prefix - should return "/"
+ assert path_rewrite_func("/bar/mpl/8080/path") == "/"
+
+ # Test with no slash after proxy_path - should return "/"
+ assert path_rewrite_func("/foo/mpl8080/path") == "/"
+
+ # Test with incomplete path - should return "/"
+ assert path_rewrite_func("/foo/mpl/") == "/"
+
+ # Test with just the port - should return "/"
+ assert path_rewrite_func("/foo/mpl/8080") == "/"
+
+ def test_mpl_proxy_middleware_root_base_url(self):
+ """Test MPL proxy middleware with root base_url."""
+ middleware = _create_mpl_proxy_middleware("/")
+
+ # Check that the middleware is created correctly
+ assert middleware.cls == ProxyMiddleware
+ assert middleware.kwargs["proxy_path"] == "/mpl"
+
+ # Test target_url function
+ target_url_func: Callable[[str], str] = middleware.kwargs["target_url"]
+ assert (
+ target_url_func("/mpl/8080/some/path") == "http://localhost:8080"
+ )
+
+ # Test path_rewrite function
+ path_rewrite_func: Callable[[str], str] = middleware.kwargs[
+ "path_rewrite"
+ ]
+ assert path_rewrite_func("/mpl/8080/some/path") == "/some/path"
+
+ def test_mpl_proxy_middleware_integration_with_base_url(self):
+ """Test MPL proxy middleware integration with base_url in a real app."""
+ # Create app with base_url
+ app = create_starlette_app(base_url="/api/v1")
+ app.state.session_manager = get_mock_session_manager()
+ app.state.config_manager = MarimoConfigManager(UserConfigManager())
+
+ # Mock out the server
+ uvicorn_server = uvicorn.Server(uvicorn.Config(app))
+ uvicorn_server.servers = []
+
+ app.state.server = uvicorn_server
+ app.state.host = "localhost"
+ app.state.port = 1234
+ app.state.base_url = "/api/v1"
+
+ client = TestClient(app)
+
+ # Test that regular API routes still work with base_url
+ response = client.get("/api/v1/health")
+ assert response.status_code == 200
+
+ # Test that routes without base_url don't work
+ response = client.get("/health")
+ assert response.status_code == 404
+
+ # Test that the MPL proxy middleware is properly configured by
+ # verifying that it would handle the expected paths correctly
+ middleware = _create_mpl_proxy_middleware("/api/v1")
+ target_url_func: Callable[[str], str] = middleware.kwargs["target_url"]
+ path_rewrite_func: Callable[[str], str] = middleware.kwargs[
+ "path_rewrite"
+ ]
+
+ # These should work with the base_url
+ assert (
+ target_url_func("/api/v1/mpl/8080/static/file.js")
+ == "http://localhost:8080"
+ )
+ assert (
+ path_rewrite_func("/api/v1/mpl/8080/static/file.js")
+ == "/static/file.js"
+ )