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: encode notebookId when using /public (#3770)

Myles Scolnick47ba1ab141c1
diff --git a/marimo/_output/utils.py b/marimo/_output/utils.py
index 16710a1d09..a3ea347958 100644
--- a/marimo/_output/utils.py
+++ b/marimo/_output/utils.py
@@ -23,6 +23,11 @@ def uri_encode_component(code: str) -> str:
return urllib.parse.quote(code, safe="~()*!.'")
+def uri_decode_component(code: str) -> str:
+ """Equivalent to `decodeURIComponent` in JavaScript."""
+ return urllib.parse.unquote(code)
+
+
def normalize_dimension(value: Union[int, float, str, None]) -> Optional[str]:
"""Normalize dimension value to CSS string.
diff --git a/marimo/_server/api/endpoints/assets.py b/marimo/_server/api/endpoints/assets.py
index d5d1a65f59..f53f18c6db 100644
--- a/marimo/_server/api/endpoints/assets.py
+++ b/marimo/_server/api/endpoints/assets.py
@@ -13,6 +13,7 @@ from starlette.staticfiles import StaticFiles
from marimo import _loggers
from marimo._config.manager import get_default_config_manager
+from marimo._output.utils import uri_decode_component
from marimo._runtime.virtual_file import EMPTY_VIRTUAL_FILE, read_virtual_file
from marimo._server.api.deps import AppState
from marimo._server.router import APIRouter
@@ -113,12 +114,24 @@ async def index(request: Request) -> HTMLResponse:
# Inject service worker registration with the notebook ID
html = inject_script(
html,
+ # Register service worker with the notebook ID
+ # Potentially update the service worker and send the notebook ID again.
f"""
if ('serviceWorker' in navigator) {{
const notebookId = '{file_key}';
navigator.serviceWorker.register('./public-files-sw.js')
.then(registration => {{
registration.active.postMessage({{ notebookId }});
+ }})
+ .catch(error => {{
+ console.error('Error registering service worker:', error);
+ }});
+ navigator.serviceWorker.ready
+ .then(registration => {{
+ registration.update().then(() => registration.active.postMessage({{ notebookId }}));
+ }})
+ .catch(error => {{
+ console.error('Error updating service worker:', error);
}});
}}
""",
@@ -199,21 +212,23 @@ async def public_files_service_worker(request: Request) -> Response:
del request
return Response(
content="""
- let currentNotebookId = null;
-
- self.addEventListener('message', (event) => {
- if (event.data.notebookId) {
- currentNotebookId = event.data.notebookId;
- }
+ let notebookIdPromise = new Promise((resolve) => {
+ self.addEventListener('message', (event) => {
+ if (event.data.notebookId) {
+ resolve(event.data.notebookId);
+ }
+ });
});
self.addEventListener('fetch', function(event) {
if (event.request.url.includes('/public/')) {
event.respondWith(
- fetch(event.request.url, {
- headers: {
- 'X-Notebook-Id': currentNotebookId
- }
+ notebookIdPromise.then(notebookId => {
+ return fetch(event.request.url, {
+ headers: {
+ 'X-Notebook-Id': encodeURIComponent(notebookId)
+ }
+ });
})
);
}
@@ -232,6 +247,8 @@ async def serve_public_file(request: Request) -> Response:
# Get notebook ID from header
notebook_id = request.headers.get("X-Notebook-Id")
if notebook_id:
+ # Decode notebook ID
+ notebook_id = uri_decode_component(notebook_id)
app_manager = app_state.session_manager.app_manager(notebook_id)
if app_manager.filename:
notebook_dir = Path(app_manager.filename).parent
diff --git a/tests/_output/test_output_utils.py b/tests/_output/test_output_utils.py
index af93f49147..6169870fff 100644
--- a/tests/_output/test_output_utils.py
+++ b/tests/_output/test_output_utils.py
@@ -43,6 +43,41 @@ def test_uri_encode_component() -> None:
assert utils.uri_encode_component("~.!'()") == "~.!'()"
+def test_uri_decode_component() -> None:
+ assert utils.uri_decode_component("hello%20world") == "hello world"
+ assert utils.uri_decode_component("!@#$%^&*()") == "!@#$%^&*()"
+ assert utils.uri_decode_component("~.!'()") == "~.!'()"
+
+
+def test_uri_encode_decode_component_not_lossy() -> None:
+ test_cases = [
+ "hello world",
+ "!@#$%^&*()",
+ "~.!'()",
+ "hello%20world",
+ "https://example.com/path?query=value&other=123",
+ "unicode_symbols_✨🌟⭐",
+ "spaces and tabs\t\t",
+ r"backslashes\and/slashes/",
+ 'quotes\'and"double"quotes',
+ "<>[]{}|",
+ "control\n\r\tcharacters",
+ "math±∞≠≈∫",
+ "currency¢£¥€$",
+ "accents éèêë àâäã ñ",
+ "chinese 你好 japanese こんにちは",
+ "emojis 👋🌍🎉🎨🚀",
+ "mixed_case_TEST_123",
+ ]
+
+ for item in test_cases:
+ assert (
+ utils.uri_decode_component(utils.uri_encode_component(item))
+ == item
+ )
+
+
def test_normalize_dimension() -> None:
# Test None
assert utils.normalize_dimension(None) is None