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: handle null registration.active in service worker registration (#8213)

Ahmad Yasserc68a27a01898
diff --git a/marimo/_server/api/endpoints/assets.py b/marimo/_server/api/endpoints/assets.py
index b7c635409c..762b649da1 100644
--- a/marimo/_server/api/endpoints/assets.py
+++ b/marimo/_server/api/endpoints/assets.py
@@ -299,18 +299,32 @@ def _inject_service_worker(html: str, file_key: str) -> str:
f"""
if ('serviceWorker' in navigator) {{
const notebookId = '{uri_encode_component(file_key)}';
- navigator.serviceWorker.register('./public-files-sw.js?v=2')
- .then(registration => {{
+ function sendNotebookId(registration) {{
+ if (registration.active) {{
registration.active.postMessage({{ notebookId }});
+ return;
+ }}
+ const worker = registration.installing || registration.waiting;
+ if (worker) {{
+ worker.addEventListener('statechange', function() {{
+ if (worker.state === 'activated') {{
+ registration.active.postMessage({{ notebookId }});
+ }}
+ }});
+ }}
+ }}
+ navigator.serviceWorker.register('./public-files-sw.js?v=2')
+ .then(function(registration) {{
+ sendNotebookId(registration);
}})
- .catch(error => {{
+ .catch(function(error) {{
console.error('Error registering service worker:', error);
}});
navigator.serviceWorker.ready
- .then(registration => {{
- registration.update().then(() => registration.active.postMessage({{ notebookId }}));
+ .then(function(registration) {{
+ registration.update().then(function() {{ sendNotebookId(registration); }});
}})
- .catch(error => {{
+ .catch(function(error) {{
console.error('Error updating service worker:', error);
}});
}} else {{
diff --git a/tests/_server/api/endpoints/test_assets.py b/tests/_server/api/endpoints/test_assets.py
index 692d81a99e..3c16e0adac 100644
--- a/tests/_server/api/endpoints/test_assets.py
+++ b/tests/_server/api/endpoints/test_assets.py
@@ -234,6 +234,16 @@ def test_inject_service_worker() -> None:
)
+def test_inject_service_worker_null_check() -> None:
+ result = _inject_service_worker("<body></body>", "notebook.py")
+ # The helper function should check registration.active before posting
+ assert "function sendNotebookId(registration)" in result
+ assert "if (registration.active)" in result
+ # Should handle installing/waiting workers via statechange listener
+ assert "registration.installing || registration.waiting" in result
+ assert "statechange" in result
+
+
def test_index_with_missing_local_file_and_asset_url(
client: TestClient,
) -> None: