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.

Persist anywidget model state in static HTML exports (#8166)

Trevor Manzf8733b814a5a
diff --git a/frontend/src/core/kernel/messages.ts b/frontend/src/core/kernel/messages.ts
index 9e4432c30b..6815ae7570 100644
--- a/frontend/src/core/kernel/messages.ts
+++ b/frontend/src/core/kernel/messages.ts
@@ -13,6 +13,7 @@ export const DATA_TYPES = [
"time",
"unknown",
] as const;
+export type ModelLifecycle = NotificationMessageData<"model-lifecycle">;
export type Banner = NotificationMessageData<"banner">;
export type AiInlineCompletionRequest = schemas["AiInlineCompletionRequest"];
export type DataTableColumn = schemas["DataTableColumn"];
diff --git a/frontend/src/core/static/static-state.ts b/frontend/src/core/static/static-state.ts
index 143e9c610d..1a6014b8ae 100644
--- a/frontend/src/core/static/static-state.ts
+++ b/frontend/src/core/static/static-state.ts
@@ -1,5 +1,6 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { invariant } from "@/utils/invariant";
+import type { ModelLifecycle } from "../kernel/messages";
import type { MarimoStaticState, StaticVirtualFiles } from "./types";
declare global {
@@ -17,3 +18,7 @@ export function getStaticVirtualFiles(): StaticVirtualFiles {
return window.__MARIMO_STATIC__.files;
}
+
+export function getStaticModelNotifications(): ModelLifecycle[] | undefined {
+ return window?.__MARIMO_STATIC__?.modelNotifications;
+}
diff --git a/frontend/src/core/static/types.ts b/frontend/src/core/static/types.ts
index 74382baecd..fba1138413 100644
--- a/frontend/src/core/static/types.ts
+++ b/frontend/src/core/static/types.ts
@@ -1,8 +1,10 @@
/* Copyright 2026 Marimo. All rights reserved. */
import type { DataURLString } from "@/utils/json/base64";
+import type { ModelLifecycle } from "../kernel/messages";
export type StaticVirtualFiles = Record<string, DataURLString>;
export interface MarimoStaticState {
files: StaticVirtualFiles;
+ modelNotifications?: ModelLifecycle[];
}
diff --git a/frontend/src/mount.tsx b/frontend/src/mount.tsx
index 07ffdb3193..b50dedc8f1 100644
--- a/frontend/src/mount.tsx
+++ b/frontend/src/mount.tsx
@@ -39,11 +39,18 @@ import {
import { codeAtom, filenameAtom } from "./core/saving/file-state";
import { store } from "./core/state/jotai";
import { patchFetch, patchVegaLoader } from "./core/static/files";
-import { isStaticNotebook } from "./core/static/static-state";
+import {
+ getStaticModelNotifications,
+ isStaticNotebook,
+} from "./core/static/static-state";
import { maybeRegisterVSCodeBindings } from "./core/vscode/vscode-bindings";
import type { FileStore } from "./core/wasm/store";
import { notebookFileStore } from "./core/wasm/store";
import { WebSocketState } from "./core/websocket/types";
+import {
+ handleWidgetMessage,
+ MODEL_MANAGER,
+} from "./plugins/impl/anywidget/model";
import { vegaLoader } from "./plugins/impl/vega/loader";
import { initializePlugins } from "./plugins/plugins";
import { ThemeProvider } from "./theme/ThemeProvider";
@@ -77,6 +84,7 @@ export function mount(options: unknown, el: Element): Error | undefined {
// If we're in static mode, we need to patch fetch to use the virtual file
patchFetch();
patchVegaLoader(vegaLoader);
+ hydrateStaticModels();
}
// Init store
@@ -330,6 +338,20 @@ function initStore(options: unknown) {
}
}
+/**
+ * Hydrate anywidget models from embedded static state so widgets
+ * render immediately without a kernel connection.
+ */
+function hydrateStaticModels(): void {
+ const notifications = getStaticModelNotifications();
+ if (!notifications) {
+ return;
+ }
+ for (const notification of notifications) {
+ handleWidgetMessage(MODEL_MANAGER, notification);
+ }
+}
+
export const visibleForTesting = {
reset: () => {
hasMounted = false;
diff --git a/frontend/src/plugins/impl/anywidget/__tests__/model.test.ts b/frontend/src/plugins/impl/anywidget/__tests__/model.test.ts
index 87e2d454de..0434c0acf6 100644
--- a/frontend/src/plugins/impl/anywidget/__tests__/model.test.ts
+++ b/frontend/src/plugins/impl/anywidget/__tests__/model.test.ts
@@ -31,6 +31,12 @@ vi.mock("@/core/network/requests", () => ({
}),
}));
+// Mock isStaticNotebook — default to false (normal mode)
+const mockIsStatic = vi.fn().mockReturnValue(false);
+vi.mock("@/core/static/static-state", () => ({
+ isStaticNotebook: () => mockIsStatic(),
+}));
+
// Helper to create a mock MarimoComm
function createMockComm<T>() {
return {
@@ -393,4 +399,51 @@ describe("ModelManager", () => {
expect(BINDING_MANAGER.has(testId)).toBe(false);
});
+
+ describe("static mode", () => {
+ beforeEach(() => {
+ mockIsStatic.mockReturnValue(true);
+ });
+
+ afterAll(() => {
+ mockIsStatic.mockReturnValue(false);
+ });
+
+ it("should create model with no-op comm in static mode", async () => {
+ await handleWidgetMessage(modelManager, {
+ model_id: testId,
+ message: {
+ method: "open",
+ state: { count: 42 },
+ buffer_paths: [],
+ buffers: [],
+ },
+ });
+
+ const model = await modelManager.get(testId);
+ expect(model.get("count")).toBe(42);
+
+ // save_changes should not call the real request client
+ model.set("count", 100);
+ model.save_changes();
+ expect(mockSendModelValue).not.toHaveBeenCalled();
+ });
+
+ it("should not throw on send in static mode", async () => {
+ await handleWidgetMessage(modelManager, {
+ model_id: testId,
+ message: {
+ method: "open",
+ state: { count: 0 },
+ buffer_paths: [],
+ buffers: [],
+ },
+ });
+
+ const model = await modelManager.get(testId);
+ // send() should silently no-op
+ await expect(model.send({ test: true })).resolves.toBeUndefined();
+ expect(mockSendModelValue).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/frontend/src/plugins/impl/anywidget/model.ts b/frontend/src/plugins/impl/anywidget/model.ts
index df3f1bf39f..b8800da625 100644
--- a/frontend/src/plugins/impl/anywidget/model.ts
+++ b/frontend/src/plugins/impl/anywidget/model.ts
@@ -5,6 +5,7 @@ import type { AnyModel } from "@anywidget/types";
import { debounce } from "lodash-es";
import type { NotificationMessageData } from "@/core/kernel/messages";
import { getRequestClient } from "@/core/network/requests";
+import { isStaticNotebook } from "@/core/static/static-state";
import {
decodeFromWire,
serializeBuffersToBase64,
@@ -343,12 +344,14 @@ export async function handleWidgetMessage(
return;
}
- modelManager.create(
- modelId,
- (signal) =>
- new Model(
- stateWithBuffers,
- {
+ modelManager.create(modelId, (signal) => {
+ // In static exports there is no kernel, so comm calls are no-ops.
+ const comm: MarimoComm<ModelState> = isStaticNotebook()
+ ? {
+ sendUpdate: async () => undefined,
+ sendCustomMessage: async () => undefined,
+ }
+ : {
async sendUpdate(changeData) {
if (signal.aborted) {
Logger.debug(
@@ -377,10 +380,10 @@ export async function handleWidgetMessage(
buffers: buffers.map(dataViewToBase64),
});
},
- },
- signal,
- ),
- );
+ };
+
+ return new Model(stateWithBuffers, comm, signal);
+ });
return;
}
diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.py
index 606b7ca7b4..787ce0d8f9 100644
--- a/marimo/_cli/development/commands.py
+++ b/marimo/_cli/development/commands.py
@@ -610,6 +610,7 @@ def preview(file_path: Path, port: int, host: str, headless: bool) -> None:
code_hash=hash_code(code),
notebook_snapshot=notebook_snapshot,
files={},
+ model_notifications=session_view.get_model_notifications(),
asset_url=asset_url,
)
diff --git a/marimo/_messaging/notification.py b/marimo/_messaging/notification.py
index b3b0eff2c1..67c245bfbb 100644
--- a/marimo/_messaging/notification.py
+++ b/marimo/_messaging/notification.py
@@ -201,6 +201,25 @@ class ModelLifecycleNotification(Notification, tag="model-lifecycle"):
model_id: WidgetModelId
message: ModelMessage
+ def to_json_serializable(self) -> dict[str, Any]:
+ """Convert to a plain dict that json.dumps can serialize.
+
+ Used by static HTML export to embed model notifications in a
+ <script> tag via json_script(). We use msgspec.to_builtins for
+ the struct conversion, then base64-encode any bytes buffers
+ since raw bytes are not JSON-serializable.
+ """
+ import base64
+
+ d: dict[str, Any] = msgspec.to_builtins(self)
+ # bytes are not JSON-serializable; base64-encode each buffer
+ msg = d.get("message", {})
+ if "buffers" in msg:
+ msg["buffers"] = [
+ base64.b64encode(b).decode("ascii") for b in msg["buffers"]
+ ]
+ return d
+
class InterruptedNotification(Notification, tag="interrupted"):
"""Kernel was interrupted by user (SIGINT/Ctrl+C)."""
diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.py
index 51c5cbf4fb..abba9c61a2 100644
--- a/marimo/_server/export/exporter.py
+++ b/marimo/_server/export/exporter.py
@@ -117,6 +117,7 @@ class Exporter:
session_snapshot=session_snapshot,
notebook_snapshot=notebook_snapshot,
files=virtual_files,
+ model_notifications=session_view.get_model_notifications(),
asset_url=request.asset_url,
)
diff --git a/marimo/_server/templates/templates.py b/marimo/_server/templates/templates.py
index bb8948b2f5..e52a3cb52f 100644
--- a/marimo/_server/templates/templates.py
+++ b/marimo/_server/templates/templates.py
@@ -11,6 +11,7 @@ from typing import Any, Literal, Optional, Union, cast
from marimo._ast.app_config import _AppConfig
from marimo._config.config import MarimoConfig, PartialMarimoConfig
from marimo._convert.converters import MarimoConvert
+from marimo._messaging.notification import ModelLifecycleNotification
from marimo._output.utils import uri_encode_component
from marimo._schemas.notebook import NotebookV1
from marimo._schemas.session import NotebookSessionV1
@@ -319,6 +320,7 @@ def static_notebook_template(
session_snapshot: NotebookSessionV1,
notebook_snapshot: NotebookV1,
files: dict[str, str],
+ model_notifications: Optional[list[ModelLifecycleNotification]] = None,
asset_url: Optional[str] = None,
) -> str:
if asset_url is None:
@@ -361,6 +363,7 @@ def static_notebook_template(
<script data-marimo="true">
window.__MARIMO_STATIC__ = {{}};
window.__MARIMO_STATIC__.files = {json_script(files)};
+ window.__MARIMO_STATIC__.modelNotifications = {json_script([n.to_json_serializable() for n in model_notifications or []])};
</script>
"""
)
diff --git a/marimo/_session/state/session_view.py b/marimo/_session/state/session_view.py
index c91d99fbf7..0b01e3dded 100644
--- a/marimo/_session/state/session_view.py
+++ b/marimo/_session/state/session_view.py
@@ -94,7 +94,6 @@ class ModelReplayState:
self.buffers[tuple(path)] = buf
def to_notification(self) -> ModelLifecycleNotification:
- """Convert back to a ModelOpen notification for replay."""
paths = list(self.buffers.keys())
bufs = list(self.buffers.values())
return ModelLifecycleNotification(
@@ -521,8 +520,8 @@ class SessionView:
# Model messages must come before cell notifications to ensure
# the model exists before the view tries to use it.
- for view in self.model_states.values():
- all_notifications.append(view.to_notification())
+ for state in self.model_states.values():
+ all_notifications.append(state.to_notification())
if self.ui_element_messages:
for ui_messages in self.ui_element_messages.values():
@@ -536,6 +535,16 @@ class SessionView:
all_notifications.append(self.startup_logs)
return all_notifications
+ def get_model_notifications(self) -> list[ModelLifecycleNotification]:
+ """Return model-open notifications for all live widget models.
+
+ Used to embed model state in static HTML exports so anywidgets
+ can render without a running kernel.
+ """
+ return [
+ state.to_notification() for state in self.model_states.values()
+ ]
+
def is_empty(self) -> bool:
return all(
notif.output is None and notif.console is None
diff --git a/tests/_server/templates/snapshots/export1.txt b/tests/_server/templates/snapshots/export1.txt
index c1073036c0..4960aec3e6 100644
--- a/tests/_server/templates/snapshots/export1.txt
+++ b/tests/_server/templates/snapshots/export1.txt
@@ -75,6 +75,7 @@
<script data-marimo="true">
window.__MARIMO_STATIC__ = {};
window.__MARIMO_STATIC__.files = {"file1": "File 1 content", "file2": "File 2 content"};
+ window.__MARIMO_STATIC__.modelNotifications = [];
</script>
</head>
<body>
diff --git a/tests/_server/templates/snapshots/export2.txt b/tests/_server/templates/snapshots/export2.txt
index 29e90895f0..67ec275fbd 100644
--- a/tests/_server/templates/snapshots/export2.txt
+++ b/tests/_server/templates/snapshots/export2.txt
@@ -75,6 +75,7 @@
<script data-marimo="true">
window.__MARIMO_STATIC__ = {};
window.__MARIMO_STATIC__.files = {"file1": "File 1 content", "file2": "File 2 content"};
+ window.__MARIMO_STATIC__.modelNotifications = [];
</script>
</head>
<body>
diff --git a/tests/_server/templates/snapshots/export3.txt b/tests/_server/templates/snapshots/export3.txt
index ebb0b8bca5..524d867b40 100644
--- a/tests/_server/templates/snapshots/export3.txt
+++ b/tests/_server/templates/snapshots/export3.txt
@@ -75,6 +75,7 @@
<script data-marimo="true">
window.__MARIMO_STATIC__ = {};
window.__MARIMO_STATIC__.files = {};
+ window.__MARIMO_STATIC__.modelNotifications = [];
</script>
</head>
<body>
diff --git a/tests/_server/templates/snapshots/export4.txt b/tests/_server/templates/snapshots/export4.txt
index 41336a6f14..3784693448 100644
--- a/tests/_server/templates/snapshots/export4.txt
+++ b/tests/_server/templates/snapshots/export4.txt
@@ -75,6 +75,7 @@
<script data-marimo="true">
window.__MARIMO_STATIC__ = {};
window.__MARIMO_STATIC__.files = {};
+ window.__MARIMO_STATIC__.modelNotifications = [];
</script>
<style title='marimo-custom'>/* custom css */</style></head>
<body>
diff --git a/tests/_server/templates/snapshots/export5.txt b/tests/_server/templates/snapshots/export5.txt
index bd47e415db..004c3aff72 100644
--- a/tests/_server/templates/snapshots/export5.txt
+++ b/tests/_server/templates/snapshots/export5.txt
@@ -75,6 +75,7 @@
<script data-marimo="true">
window.__MARIMO_STATIC__ = {};
window.__MARIMO_STATIC__.files = {};
+ window.__MARIMO_STATIC__.modelNotifications = [];
</script>
diff --git a/tests/_server/templates/snapshots/export6.txt b/tests/_server/templates/snapshots/export6.txt
index 54bcb159eb..cb2f6178ae 100644
--- a/tests/_server/templates/snapshots/export6.txt
+++ b/tests/_server/templates/snapshots/export6.txt
@@ -75,6 +75,7 @@
<script data-marimo="true">
window.__MARIMO_STATIC__ = {};
window.__MARIMO_STATIC__.files = {};
+ window.__MARIMO_STATIC__.modelNotifications = [];
</script>
<style title='marimo-custom'>/* custom css 1 */</style>
<style title='marimo-custom'>/* custom css 2 */</style></head>
diff --git a/tests/_session/state/test_session_view.py b/tests/_session/state/test_session_view.py
index b05edb5849..6ef7a7e359 100644
--- a/tests/_session/state/test_session_view.py
+++ b/tests/_session/state/test_session_view.py
@@ -310,6 +310,56 @@ def test_model_multiple_models(session_view: SessionView) -> None:
assert session_view.model_states[model_id2].state == {"key": "v2"}
+def test_get_model_notifications(session_view: SessionView) -> None:
+ # Empty initially
+ assert session_view.get_model_notifications() == []
+
+ # Add two models
+ m1 = WidgetModelId("m1")
+ m2 = WidgetModelId("m2")
+ session_view.add_notification(
+ ModelLifecycleNotification(
+ model_id=m1,
+ message=ModelOpen(
+ state={"count": 0},
+ buffer_paths=[],
+ buffers=[],
+ ),
+ )
+ )
+ session_view.add_notification(
+ ModelLifecycleNotification(
+ model_id=m2,
+ message=ModelOpen(
+ state={"img": None},
+ buffer_paths=[["img"]],
+ buffers=[b"\x89PNG"],
+ ),
+ )
+ )
+
+ result = session_view.get_model_notifications()
+ assert len(result) == 2
+ by_id = {n.model_id: n for n in result}
+
+ assert by_id[m1].message == ModelOpen(
+ state={"count": 0}, buffer_paths=[], buffers=[]
+ )
+ assert by_id[m2].message == ModelOpen(
+ state={"img": None},
+ buffer_paths=[["img"]],
+ buffers=[b"\x89PNG"],
+ )
+
+ # Close m1, only m2 remains
+ session_view.add_notification(
+ ModelLifecycleNotification(model_id=m1, message=ModelClose())
+ )
+ result = session_view.get_model_notifications()
+ assert len(result) == 1
+ assert result[0].model_id == m2
+
+
class TestModelReplayState:
"""Unit tests for ModelReplayState buffer merging."""
@@ -392,26 +442,36 @@ class TestModelReplayState:
assert view.buffers == {("img",): b"png"}
assert view.state == {"label": "hi", "img": None}
- def test_to_notification_round_trips(self) -> None:
- model_id = WidgetModelId("m")
+ def test_to_notification_no_buffers(self) -> None:
view = ModelReplayState(
- model_id=model_id,
+ model_id=WidgetModelId("m"),
+ state={"label": "hi", "count": 42},
+ buffers={},
+ )
+ result = view.to_notification()
+ assert result.model_id == WidgetModelId("m")
+ assert result.message == ModelOpen(
+ state={"label": "hi", "count": 42},
+ buffer_paths=[],
+ buffers=[],
+ )
+
+ def test_to_notification_with_buffers(self) -> None:
+ view = ModelReplayState(
+ model_id=WidgetModelId("m"),
state={"img": None, "data": None, "label": "hi"},
buffers={("img",): b"png", ("data",): b"csv"},
)
- notif = view.to_notification()
- assert notif.model_id == model_id
- assert isinstance(notif.message, ModelOpen)
- assert notif.message.state == {
- "img": None,
- "data": None,
- "label": "hi",
- }
+ result = view.to_notification()
+ assert result.model_id == WidgetModelId("m")
+ msg = result.message
+ assert isinstance(msg, ModelOpen)
+ assert msg.state == {"img": None, "data": None, "label": "hi"}
# buffer_paths and buffers should be parallel and match
path_buf = dict(
zip(
- [tuple(p) for p in notif.message.buffer_paths],
- notif.message.buffers,
+ [tuple(p) for p in msg.buffer_paths],
+ msg.buffers,
)
)
assert path_buf == {("img",): b"png", ("data",): b"csv"}