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.

Support anywidget composition and hot reload (#10127)

Trevor Manz56d8ec070ee4
diff --git a/frontend/package.json b/frontend/package.json
index 6bd255dfe2..2f793e4b5a 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -22,7 +22,7 @@
},
"dependencies": {
"@ai-sdk/react": "^3.0.134",
- "@anywidget/types": "^0.2.0",
+ "@anywidget/types": "^0.4.0",
"@codemirror/autocomplete": "^6.20.1",
"@codemirror/commands": "^6.10.2",
"@codemirror/lang-markdown": "^6.5.0",
diff --git a/frontend/src/core/islands/bootstrap.ts b/frontend/src/core/islands/bootstrap.ts
index 339cf0af02..be1eaa0086 100644
--- a/frontend/src/core/islands/bootstrap.ts
+++ b/frontend/src/core/islands/bootstrap.ts
@@ -5,8 +5,8 @@ import { ISLAND_CSS_CLASSES, ISLAND_TAG_NAMES } from "@/core/islands/constants";
import { renderHTML } from "@/plugins/core/RenderHTML";
import {
handleWidgetMessage,
- MODEL_MANAGER,
-} from "@/plugins/impl/anywidget/model";
+ WIDGET_REGISTRY,
+} from "@/plugins/impl/anywidget/registry";
import { initializePlugins } from "@/plugins/plugins";
import { Functions } from "@/utils/functions";
import {
@@ -253,7 +253,7 @@ function handleMessage(
return;
case "model-lifecycle":
- handleWidgetMessage(MODEL_MANAGER, msg.data);
+ handleWidgetMessage(WIDGET_REGISTRY, msg.data);
return;
case "consumer-capabilities":
diff --git a/frontend/src/core/websocket/useMarimoKernelConnection.tsx b/frontend/src/core/websocket/useMarimoKernelConnection.tsx
index 28d32e6756..023338c1d3 100644
--- a/frontend/src/core/websocket/useMarimoKernelConnection.tsx
+++ b/frontend/src/core/websocket/useMarimoKernelConnection.tsx
@@ -16,8 +16,8 @@ import { useConnectionTransport } from "@/core/websocket/useWebSocket";
import { renderHTML } from "@/plugins/core/RenderHTML";
import {
handleWidgetMessage,
- MODEL_MANAGER,
-} from "@/plugins/impl/anywidget/model";
+ WIDGET_REGISTRY,
+} from "@/plugins/impl/anywidget/registry";
import { logNever } from "@/utils/assertNever";
import { prettyError } from "@/utils/errors";
import {
@@ -284,7 +284,7 @@ export function useMarimoKernelConnection(opts: {
}
case "model-lifecycle":
- handleWidgetMessage(MODEL_MANAGER, msg.data);
+ handleWidgetMessage(WIDGET_REGISTRY, msg.data);
return;
case "remove-ui-elements":
diff --git a/frontend/src/mount.tsx b/frontend/src/mount.tsx
index 40f895d6eb..ee4286f799 100644
--- a/frontend/src/mount.tsx
+++ b/frontend/src/mount.tsx
@@ -54,8 +54,8 @@ import { notebookFileStore } from "./core/wasm/store";
import { WebSocketState } from "./core/websocket/types";
import {
handleWidgetMessage,
- MODEL_MANAGER,
-} from "./plugins/impl/anywidget/model";
+ WIDGET_REGISTRY,
+} from "./plugins/impl/anywidget/registry";
import { vegaLoader } from "./plugins/impl/vega/loader";
import { initializePlugins } from "./plugins/plugins";
import { ThemeProvider } from "./theme/ThemeProvider";
@@ -369,7 +369,7 @@ function hydrateStaticModels(): void {
return;
}
for (const notification of notifications) {
- handleWidgetMessage(MODEL_MANAGER, notification);
+ handleWidgetMessage(WIDGET_REGISTRY, notification);
}
}
diff --git a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
index 8803bc7d6a..4d6907cbc7 100644
--- a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
+++ b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
@@ -1,32 +1,21 @@
/* Copyright 2026 Marimo. All rights reserved. */
-/* oxlint-disable typescript/no-explicit-any */
-import type { AnyWidget } from "@anywidget/types";
-import { useEffect, useRef } from "react";
+import { useEffect, useRef, useState } from "react";
import { z } from "zod";
-import { useAsyncData } from "@/hooks/useAsyncData";
-import type { HTMLElementNotDerivedFromRef } from "@/hooks/useEventListener";
import { createPlugin } from "@/plugins/core/builder";
import type { IPluginProps } from "@/plugins/types";
-import { prettyError } from "@/utils/errors";
-import { Logger } from "@/utils/Logger";
-import { hasFunctionProperty, isRecord } from "@/utils/records";
import { ErrorBanner } from "../common/error-banner";
-import { getMarimoInternal, MODEL_MANAGER, type Model } from "./model";
-import type { ModelState, WidgetModelId } from "./types";
-import { BINDING_MANAGER, WIDGET_DEF_REGISTRY } from "./widget-binding";
+import { WIDGET_REGISTRY } from "./registry";
+import { isWidgetModelId, type WidgetModelId } from "./types";
/**
- * AnyWidget asset data
+ * The component's only data attribute; everything else arrives through
+ * the model's comm messages, keyed by this id.
*/
interface Data {
- jsUrl: string;
- jsHash: string;
modelId: WidgetModelId;
}
-type AnyWidgetState = ModelState;
-
/**
* Value payload sent by the frontend on state updates.
*
@@ -37,315 +26,54 @@ interface ModelIdRef {
model_id?: WidgetModelId;
}
-export function useAnyWidgetModule(opts: { jsUrl: string; jsHash: string }) {
- const { jsUrl, jsHash } = opts;
-
- // JS is an ESM file with a render function on it
- // export function render({ model, el }) {
- // ...
- const {
- data: jsModule,
- error,
- refetch,
- } = useAsyncData(async () => {
- return await WIDGET_DEF_REGISTRY.getModule(jsUrl, jsHash);
- // Re-render on jsHash change (which is a hash of the contents of the file)
- // instead of a jsUrl change because URLs may change without the contents
- // actually changing (and we don't want to re-render on every change).
- // If there is an error loading the URL (e.g. maybe an invalid or old URL),
- // we also want to re-render.
- }, [jsHash]);
-
- // If there is an error and the jsUrl has changed, we want to re-render
- // because the URL may have changed to a valid URL.
- const hasError = Boolean(error);
- useEffect(() => {
- if (hasError && jsUrl) {
- WIDGET_DEF_REGISTRY.invalidate(jsHash);
- refetch();
- }
- }, [hasError, jsUrl]);
-
- return {
- jsModule,
- error,
- };
-}
-
-export function useMountCss(css: string | null | undefined, host: HTMLElement) {
- // Mount the CSS
- useEffect(() => {
- const shadowRoot = host.shadowRoot;
- if (!css || !shadowRoot) {
- return;
- }
-
- // Try constructed stylesheets first
- if (
- "adoptedStyleSheets" in Document.prototype &&
- "replace" in CSSStyleSheet.prototype
- ) {
- const sheet = new CSSStyleSheet();
- try {
- sheet.replaceSync(css);
- if (shadowRoot) {
- shadowRoot.adoptedStyleSheets = [
- ...shadowRoot.adoptedStyleSheets,
- sheet,
- ];
- }
- return () => {
- if (shadowRoot) {
- shadowRoot.adoptedStyleSheets =
- shadowRoot.adoptedStyleSheets.filter((s) => s !== sheet);
- }
- };
- } catch {
- // Fall through to inline styles if constructed sheets fail
- }
- }
-
- // Fallback to inline styles
- const style = document.createElement("style");
- style.innerHTML = css;
- shadowRoot.append(style);
- return () => {
- style.remove();
- };
- }, [css, host]);
-}
-
export const AnyWidgetPlugin = createPlugin<ModelIdRef>("marimo-anywidget")
.withData(
z.object({
- jsUrl: z.string(),
- jsHash: z.string(),
- modelId: z.string().transform((v) => v as WidgetModelId),
+ modelId: z.custom<WidgetModelId>(isWidgetModelId, {
+ message: "Expected a non-empty widget model id",
+ }),
}),
)
.withFunctions({})
.renderer((props) => <AnyWidgetSlot {...props} />);
-const AnyWidgetSlot = (props: IPluginProps<ModelIdRef, Data>) => {
- const { jsUrl, jsHash, modelId } = props.data;
- const host = props.host as HTMLElementNotDerivedFromRef;
-
- const { jsModule, error } = useAnyWidgetModule({ jsUrl, jsHash });
-
- if (error) {
- return <ErrorBanner error={error} />;
- }
-
- if (!jsModule) {
- return null;
- }
-
- const widget = resolveAnyWidget(jsModule, jsUrl);
- if (!widget) {
- return (
- <ErrorBanner error={getInvalidAnyWidgetModuleError(jsModule, jsUrl)} />
- );
- }
-
- return (
- <LoadedSlot
- // Force remount when the widget module or model changes (cell re-run).
- key={`${jsHash}:${modelId}`}
- widget={widget}
- modelId={modelId}
- host={host}
- />
- );
-};
-
-/**
- * Run the anywidget module
- *
- * Per AFM spec (anywidget.dev/en/afm):
- * - initialize() is called once per model lifetime
- * - render() is called once per view (can be multiple per model)
- */
-async function runAnyWidgetModule<T extends AnyWidgetState>(
- widgetDef: AnyWidget<T>,
- model: Model<T>,
- modelId: WidgetModelId,
- el: HTMLElement,
- signal: AbortSignal,
-): Promise<void> {
- // Clear the element, in case the widget is re-rendering
- el.innerHTML = "";
-
- try {
- const binding = BINDING_MANAGER.getOrCreate(modelId);
- const render = await binding.bind(widgetDef, model);
- await render(el, signal);
- // Replay current model values so render listeners observe hydrated state
- // even if backend updates arrived before listeners were attached.
- getMarimoInternal(model).reemitState();
- } catch (error) {
- Logger.error("Error rendering anywidget", error);
- el.classList.add("text-error");
- el.innerHTML = `Error rendering anywidget: ${prettyError(error)}`;
- }
-}
-
-function isAnyWidgetModule(mod: any): mod is { default: AnyWidget } {
- if (!mod.default) {
- return false;
- }
-
- return (
- typeof mod.default === "function" ||
- typeof mod.default?.render === "function" ||
- typeof mod.default?.initialize === "function"
- );
-}
-
-const warnedLegacyNamedExportUrls = new Set<string>();
-// Cache the synthesized widget per module namespace so its identity stays
-// stable across re-renders (like a default export), avoiding needless
-// WidgetBinding re-initialization.
-const legacyWidgetCache = new WeakMap<object, AnyWidget>();
-
/**
- * Resolve the AnyWidget from a loaded module: prefer the AFM-spec default
- * export, otherwise synthesize one from legacy named `render`/`initialize`
- * exports. Returns null if neither is present.
+ * React adapter for a runtime-owned view. React supplies only the render
+ * target and its lifetime; the runtime owns models, generations, CSS,
+ * composition, and hot reload.
*/
-function resolveAnyWidget(mod: any, jsUrl: string): AnyWidget | null {
- if (isAnyWidgetModule(mod)) {
- return mod.default;
- }
-
- // Only fall back to legacy (pre-AFM) named exports when there is no default
- // export at all; a present-but-invalid default should surface an error
- // rather than be masked.
- if (mod?.default != null) {
- return null;
- }
-
- const hasNamedRender = typeof mod?.render === "function";
- const hasNamedInitialize = typeof mod?.initialize === "function";
- if (!hasNamedRender && !hasNamedInitialize) {
- return null;
- }
-
- const cached = legacyWidgetCache.get(mod);
- if (cached) {
- return cached;
- }
-
- if (!warnedLegacyNamedExportUrls.has(jsUrl)) {
- warnedLegacyNamedExportUrls.add(jsUrl);
- Logger.warn(
- `Anywidget module at ${jsUrl} uses deprecated top-level named ` +
- "exports (`render`/`initialize`). Per the AFM spec, use a default " +
- "export instead: `export default { render }`. " +
- "See https://anywidget.dev/en/afm/",
- );
- }
-
- const widget: AnyWidget = { render: mod.render, initialize: mod.initialize };
- legacyWidgetCache.set(mod, widget);
- return widget;
-}
-
-function getInvalidAnyWidgetModuleError(mod: unknown, jsUrl: string): Error {
- const afmDocs = "https://anywidget.dev/en/afm/";
- const hasNamedRender = isRecord(mod) && hasFunctionProperty(mod, "render");
- const hasNamedInitialize =
- isRecord(mod) && hasFunctionProperty(mod, "initialize");
-
- if (hasNamedRender || hasNamedInitialize) {
- const namedExports = [
- hasNamedRender ? "`render`" : null,
- hasNamedInitialize ? "`initialize`" : null,
- ]
- .filter(Boolean)
- .join(" and ");
- const lifecycleHooks = [
- hasNamedRender ? "render" : null,
- hasNamedInitialize ? "initialize" : null,
- ].filter((hook): hook is string => hook !== null);
- const defaultExportExample = `export default { ${lifecycleHooks.join(", ")} }`;
- const namedExportExample =
- lifecycleHooks.length === 1
- ? `export function ${lifecycleHooks[0]}`
- : "named export function ...";
- return new Error(
- `Anywidget module at ${jsUrl} uses named exports (${namedExports}). ` +
- "Per the AFM spec, use a default export instead: " +
- `\`${defaultExportExample}\` (not \`${namedExportExample}\`). ` +
- `See ${afmDocs}`,
- );
- }
-
- if (!isRecord(mod) || mod.default === undefined) {
- return new Error(
- `Anywidget module at ${jsUrl} is missing a default export. ` +
- "Per the AFM spec, use `export default { render }` or " +
- "`export default async () => ({ render })`. " +
- `See ${afmDocs}`,
- );
- }
-
- return new Error(
- `Anywidget module at ${jsUrl} has an invalid default export. ` +
- "Expected a factory function or an object with `render` or `initialize`. " +
- `See ${afmDocs}`,
- );
-}
-
-interface Props<T extends AnyWidgetState> {
- widget: AnyWidget<T>;
- modelId: WidgetModelId;
- host: HTMLElementNotDerivedFromRef;
-}
-
-const LoadedSlot = <T extends AnyWidgetState>({
- widget,
- modelId,
- host,
-}: Props<T> & { widget: AnyWidget<T> }) => {
+const AnyWidgetSlot = (props: IPluginProps<ModelIdRef, Data>) => {
+ const { modelId } = props.data;
const htmlRef = useRef<HTMLDivElement>(null);
-
- // value is already decoded from wire format, may be null if waiting for open message
- const model = MODEL_MANAGER.getSync(modelId);
-
- if (!model) {
- Logger.error("Model not found for modelId", modelId);
- }
-
- const css = model?.get("_css");
- useMountCss(css, host);
+ const [error, setError] = useState<Error>();
useEffect(() => {
- if (!htmlRef.current || !model) {
+ const el = htmlRef.current;
+ if (!el) {
return;
}
const controller = new AbortController();
- runAnyWidgetModule(
- widget,
- model,
+ setError(undefined);
+ WIDGET_REGISTRY.createView({
modelId,
- htmlRef.current,
- controller.signal,
- );
+ el,
+ signal: controller.signal,
+ }).catch((error) => {
+ if (!controller.signal.aborted) {
+ setError(error instanceof Error ? error : new Error(String(error)));
+ }
+ });
return () => controller.abort();
- // We re-run the widget when the modelId changes, which means the cell
- // that created the Widget has been re-run.
- // We need to re-run the widget because it may contain initialization code
- // that could be reset by the new widget.
- // See example: https://github.com/marimo-team/marimo/issues/3962#issuecomment-2703184123
- }, [widget, modelId, model]);
+ }, [modelId]);
- return <div ref={htmlRef} />;
+ return (
+ <>
+ {error ? <ErrorBanner error={error} /> : null}
+ <div ref={htmlRef} />
+ </>
+ );
};
export const visibleForTesting = {
- LoadedSlot,
- runAnyWidgetModule,
- isAnyWidgetModule,
- resolveAnyWidget,
- getInvalidAnyWidgetModuleError,
+ AnyWidgetSlot,
};
diff --git a/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.tsx b/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.tsx
index 428a6722d0..3fe96e971c 100644
--- a/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.tsx
+++ b/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.tsx
@@ -1,271 +1,163 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { render, waitFor } from "@testing-library/react";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { TestUtils } from "@/__tests__/test-helpers";
-import type { HTMLElementNotDerivedFromRef } from "@/hooks/useEventListener";
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ type MockInstance,
+ vi,
+} from "vitest";
+import type { IPluginProps } from "@/plugins/types";
import { visibleForTesting } from "../AnyWidgetPlugin";
-import { MODEL_MANAGER, Model } from "../model";
-import type { WidgetModelId } from "../types";
-import { BINDING_MANAGER } from "../widget-binding";
+import { Model } from "../model";
+import { WIDGET_REGISTRY } from "../registry";
+import type { EsmSpec, ModelState, WidgetModelId } from "../types";
+import { WIDGET_DEF_REGISTRY } from "../widget-binding";
-const {
- LoadedSlot,
- isAnyWidgetModule,
- resolveAnyWidget,
- getInvalidAnyWidgetModuleError,
-} = visibleForTesting;
+const { AnyWidgetSlot } = visibleForTesting;
// Helper to create typed model IDs for tests
const asModelId = (id: string): WidgetModelId => id as WidgetModelId;
-// Mock a minimal AnyWidget implementation
-const mockWidget = {
- initialize: vi.fn(),
- render: vi.fn(),
-};
-
-describe("LoadedSlot", () => {
- const modelId = asModelId("test-model-id");
- let mockModel: Model<{ count: number }>;
-
- const mockProps = {
- widget: mockWidget,
- data: {
- jsUrl: "http://example.com/widget.js",
- jsHash: "abc123",
- modelId: modelId,
- },
- host: document.createElement(
- "div",
- ) as unknown as HTMLElementNotDerivedFromRef,
- modelId: modelId,
+function createMockComm() {
+ return {
+ sendUpdate: vi.fn().mockResolvedValue(undefined),
+ sendCustomMessage: vi.fn().mockResolvedValue(undefined),
+ };
+}
+
+function createMockModel(state?: ModelState) {
+ return new Model<ModelState>(state ?? { count: 0 }, createMockComm());
+}
+
+const hostEl = () => document.createElement("div");
+
+describe("AnyWidgetSlot", () => {
+ const SPEC: EsmSpec = { url: "./@file/10-slot.js", hash: "slot-hash" };
+ let getModuleSpy: MockInstance<typeof WIDGET_DEF_REGISTRY.getModule>;
+ let nextId = 0;
+ let modelId: WidgetModelId;
+ let mockWidget: {
+ initialize: ReturnType<typeof vi.fn>;
+ render: ReturnType<typeof vi.fn>;
};
beforeEach(() => {
- vi.clearAllMocks();
- // Create and register a mock model before each test
- mockModel = new Model(
- { count: 0 },
- {
- sendUpdate: vi.fn().mockResolvedValue(undefined),
- sendCustomMessage: vi.fn().mockResolvedValue(undefined),
- },
- );
- MODEL_MANAGER.set(modelId, mockModel);
+ nextId += 1;
+ modelId = asModelId(`slot-test-${nextId}`);
+ mockWidget = { initialize: vi.fn(), render: vi.fn() };
+ getModuleSpy = vi
+ .spyOn(WIDGET_DEF_REGISTRY, "getModule")
+ .mockResolvedValue({ default: mockWidget });
+ WIDGET_REGISTRY.setModel(modelId, createMockModel());
+ WIDGET_REGISTRY.setSpec(modelId, {
+ url: SPEC.url,
+ // Unique hash per test so the module-cache spy is always hit.
+ hash: `${SPEC.hash}-${nextId}`,
+ });
});
afterEach(() => {
- BINDING_MANAGER.destroy(modelId);
- });
-
- it("should render a div with ref", () => {
- const { container } = render(<LoadedSlot {...mockProps} />);
- expect(container.querySelector("div")).not.toBeNull();
- });
-
- it("should call runAnyWidgetModule on initialization", async () => {
- render(<LoadedSlot {...mockProps} />);
-
- // Wait a render
+ WIDGET_REGISTRY.delete(modelId);
+ getModuleSpy.mockRestore();
+ });
+
+ const props = (
+ id: WidgetModelId,
+ value: Record<string, unknown> = {},
+ ): IPluginProps<{ model_id?: WidgetModelId }, { modelId: WidgetModelId }> =>
+ ({
+ data: { modelId: id },
+ value,
+ host: hostEl(),
+ setValue: vi.fn(),
+ functions: {},
+ }) as unknown as IPluginProps<
+ { model_id?: WidgetModelId },
+ { modelId: WidgetModelId }
+ >;
+
+ it("resolves the widget through the registry and renders a view", async () => {
+ render(<AnyWidgetSlot {...props(modelId)} />);
await waitFor(() => {
- expect(mockWidget.render).toHaveBeenCalled();
+ expect(mockWidget.initialize).toHaveBeenCalledTimes(1);
+ expect(mockWidget.render).toHaveBeenCalledTimes(1);
});
});
- it("should not remount when value update drops model_id", async () => {
- // Regression: when the frontend sends a state update (e.g. {zoom_level: 0}),
- // it overwrites the UIElement value that originally held {model_id: "..."}.
- // The key must stay stable because modelId comes from data, not value.
- const { container, rerender } = render(<LoadedSlot {...mockProps} />);
-
+ it("aborts the runtime-owned view on unmount", async () => {
+ const { unmount } = render(<AnyWidgetSlot {...props(modelId)} />);
+ await waitFor(() => {
+ expect(mockWidget.render).toHaveBeenCalledTimes(1);
+ });
+ const signal = mockWidget.render.mock.calls[0][0].signal as AbortSignal;
+ expect(signal.aborted).toBe(false);
+ unmount();
+ expect(signal.aborted).toBe(true);
+ });
+
+ it("does not remount when only the value changes", async () => {
+ // Regression: a state update rewrites the plugin value (dropping
+ // model_id), but the key comes from data attributes, so the view
+ // must survive.
+ const { container, rerender } = render(
+ <AnyWidgetSlot {...props(modelId)} />,
+ );
await waitFor(() => {
expect(mockWidget.render).toHaveBeenCalledTimes(1);
});
-
const divBefore = container.querySelector("div");
- // Simulate a value update that does NOT include model_id
- // (this is what happens when the widget sends trait state)
- rerender(<LoadedSlot {...mockProps} />);
+ rerender(<AnyWidgetSlot {...props(modelId, { zoom_level: 0 })} />);
await waitFor(() => {
- // The div should be the same DOM node (no remount)
expect(container.querySelector("div")).toBe(divBefore);
- // render should not be called again (no remount)
expect(mockWidget.render).toHaveBeenCalledTimes(1);
});
});
- it("should re-run widget when widget prop changes", async () => {
- const { rerender } = render(<LoadedSlot {...mockProps} />);
-
- // Wait for initial render
+ it("remounts and re-initializes when modelId changes (cell re-run)", async () => {
+ // Regression for marimo-team/marimo#3962: a cell re-run reconstructs
+ // the widget, opening a new comm with a new model id. The plugin
+ // must remount so initialize runs against the fresh model.
+ const { rerender } = render(<AnyWidgetSlot {...props(modelId)} />);
await waitFor(() => {
- expect(mockWidget.render).toHaveBeenCalled();
+ expect(mockWidget.render).toHaveBeenCalledTimes(1);
});
- // Create a new widget mock
- const newMockWidget = {
- initialize: vi.fn(),
- render: vi.fn(),
- };
-
- // Change the widget
- rerender(<LoadedSlot {...mockProps} widget={newMockWidget} />);
- await TestUtils.nextTick();
-
- // Wait for re-render with new widget
+ const rerunId = asModelId(`slot-test-${nextId}-rerun`);
+ WIDGET_REGISTRY.setModel(rerunId, createMockModel());
+ WIDGET_REGISTRY.setSpec(rerunId, {
+ url: SPEC.url,
+ hash: `${SPEC.hash}-${nextId}-rerun`,
+ });
+ try {
+ rerender(<AnyWidgetSlot {...props(rerunId)} />);
+ await waitFor(() => {
+ expect(mockWidget.initialize).toHaveBeenCalledTimes(2);
+ expect(mockWidget.render).toHaveBeenCalledTimes(2);
+ });
+ } finally {
+ WIDGET_REGISTRY.delete(rerunId);
+ }
+ });
+
+ it("shows an error banner when the widget cannot be resolved", async () => {
+ getModuleSpy.mockRejectedValue(new Error("import failed"));
+ const { container } = render(<AnyWidgetSlot {...props(modelId)} />);
await waitFor(() => {
- expect(newMockWidget.render).toHaveBeenCalled();
+ expect(container.textContent).toContain("import failed");
});
});
- it("should hydrate view state even when listener attaches late", async () => {
- mockModel = new Model(
- { count: 8 },
- {
- sendUpdate: vi.fn().mockResolvedValue(undefined),
- sendCustomMessage: vi.fn().mockResolvedValue(undefined),
- },
- );
- MODEL_MANAGER.set(modelId, mockModel);
-
- const lateListenerWidget = {
- initialize: vi.fn(),
- render: vi.fn(({ model, el }) => {
- // Simulate a widget view that starts with a local default and
- // relies on change events for hydration.
- el.textContent = "count is 5";
- const onCount = () => {
- el.textContent = `count is ${model.get("count")}`;
- };
- model.on("change:count", onCount);
- return () => model.off("change:count", onCount);
- }),
- };
-
- const { container } = render(
- <LoadedSlot {...mockProps} widget={lateListenerWidget} />,
- );
-
+ it("shows an error banner when render fails", async () => {
+ mockWidget.render.mockRejectedValue(new Error("widget exploded"));
+ const { container } = render(<AnyWidgetSlot {...props(modelId)} />);
await waitFor(() => {
- expect(lateListenerWidget.render).toHaveBeenCalled();
- expect(container.textContent).toContain("count is 8");
+ expect(container.textContent).toContain("widget exploded");
});
});
});
-
-describe("isAnyWidgetModule", () => {
- it("should accept a default object with render", () => {
- expect(isAnyWidgetModule({ default: { render: () => undefined } })).toBe(
- true,
- );
- });
-
- it("should accept a default factory function", () => {
- expect(
- isAnyWidgetModule({ default: async () => ({ render: () => {} }) }),
- ).toBe(true);
- });
-
- it("should reject legacy named render exports", () => {
- expect(isAnyWidgetModule({ render: () => undefined })).toBe(false);
- });
-});
-
-describe("resolveAnyWidget", () => {
- const jsUrl = "./@file/widget.js";
-
- it("should return the default export when present", () => {
- const widget = { render: () => undefined };
- expect(resolveAnyWidget({ default: widget }, jsUrl)).toBe(widget);
- });
-
- it("should return a default factory function", () => {
- const factory = async () => ({ render: () => {} });
- expect(resolveAnyWidget({ default: factory }, jsUrl)).toBe(factory);
- });
-
- it("should synthesize a widget from a legacy named render export", () => {
- const render = vi.fn();
- const resolved = resolveAnyWidget({ render }, jsUrl);
- expect(resolved).not.toBeNull();
- expect(resolved).toMatchObject({ render });
- });
-
- it("should synthesize a widget from a legacy named initialize export", () => {
- const initialize = vi.fn();
- const resolved = resolveAnyWidget({ initialize }, jsUrl);
- expect(resolved).not.toBeNull();
- expect(resolved).toMatchObject({ initialize });
- });
-
- it("should return null for a module with no valid exports", () => {
- expect(resolveAnyWidget({}, jsUrl)).toBeNull();
- expect(resolveAnyWidget({ default: {} }, jsUrl)).toBeNull();
- expect(resolveAnyWidget({ render: "not a function" }, jsUrl)).toBeNull();
- });
-
- it("should return a stable widget identity across calls for one module", () => {
- const mod = { render: vi.fn() };
- expect(resolveAnyWidget(mod, jsUrl)).toBe(resolveAnyWidget(mod, jsUrl));
- });
-
- it("should not fall back to named exports when a default export is present", () => {
- // A present-but-invalid default should surface an error, not be masked.
- expect(
- resolveAnyWidget({ default: {}, render: vi.fn() }, jsUrl),
- ).toBeNull();
- });
-});
-
-describe("getInvalidAnyWidgetModuleError", () => {
- const jsUrl = "./@file/widget.js";
-
- it("should explain legacy named render exports", () => {
- const error = getInvalidAnyWidgetModuleError(
- { render: () => undefined },
- jsUrl,
- );
- expect(error.message).toContain("named exports (`render`)");
- expect(error.message).toContain("`export default { render }`");
- expect(error.message).toContain("not `export function render`");
- });
-
- it("should explain legacy named initialize exports", () => {
- const error = getInvalidAnyWidgetModuleError(
- { initialize: () => undefined },
- jsUrl,
- );
- expect(error.message).toContain("named exports (`initialize`)");
- expect(error.message).toContain("`export default { initialize }`");
- expect(error.message).toContain("not `export function initialize`");
- });
-
- it("should avoid nested backticks for multi-hook named exports", () => {
- const error = getInvalidAnyWidgetModuleError(
- { render: () => undefined, initialize: () => undefined },
- jsUrl,
- );
- expect(error.message).toContain(
- "`export default { render, initialize }` (not `named export function ...`).",
- );
- expect(error.message).not.toContain("`named `export");
- });
-
- it("should explain a missing default export", () => {
- expect(getInvalidAnyWidgetModuleError({}, jsUrl).message).toContain(
- "missing a default export",
- );
- expect(getInvalidAnyWidgetModuleError(null, jsUrl).message).toContain(
- "missing a default export",
- );
- });
-
- it("should explain an invalid default export", () => {
- const error = getInvalidAnyWidgetModuleError({ default: {} }, jsUrl);
- expect(error.message).toContain("invalid default export");
- expect(error.message).toContain("https://anywidget.dev/en/afm/");
- });
-});
diff --git a/frontend/src/plugins/impl/anywidget/__tests__/host.test.ts b/frontend/src/plugins/impl/anywidget/__tests__/host.test.ts
new file mode 100644
index 0000000000..b1759e3b6e
--- /dev/null
+++ b/frontend/src/plugins/impl/anywidget/__tests__/host.test.ts
@@ -0,0 +1,313 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ type MockInstance,
+ vi,
+} from "vitest";
+import { createHost } from "../host";
+import { Model } from "../model";
+import { WIDGET_REGISTRY } from "../registry";
+import type { ModelState, WidgetModelId } from "../types";
+import { visibleForTesting, WIDGET_DEF_REGISTRY } from "../widget-binding";
+import { WIDGET_REF_PREFIX } from "../widget-ref";
+
+const { WidgetBinding } = visibleForTesting;
+
+const asModelId = (id: string): WidgetModelId => id as WidgetModelId;
+const ref = (id: string): string => `${WIDGET_REF_PREFIX}${id}`;
+
+function createMockComm() {
+ return {
+ sendUpdate: vi.fn().mockResolvedValue(undefined),
+ sendCustomMessage: vi.fn().mockResolvedValue(undefined),
+ };
+}
+
+describe("createHost", () => {
+ // Each test uses a unique model id so global WIDGET_REGISTRY state
+ // from earlier tests doesn't leak in.
+ let nextId = 0;
+ let modelId: WidgetModelId;
+ let parentController: AbortController;
+ let getModuleSpy: MockInstance<typeof WIDGET_DEF_REGISTRY.getModule>;
+
+ beforeEach(() => {
+ nextId += 1;
+ modelId = asModelId(`host-test-${nextId}`);
+ parentController = new AbortController();
+ getModuleSpy = vi.spyOn(WIDGET_DEF_REGISTRY, "getModule");
+ });
+
+ afterEach(() => {
+ WIDGET_REGISTRY.delete(modelId);
+ getModuleSpy.mockRestore();
+ });
+
+ /** Register a child in the global registry the way an open message
+ * would: model + ESM spec, with the module load answered by the spy. */
+ function registerChild(
+ widgetDef: object,
+ state?: ModelState,
+ ): Model<ModelState> {
+ const childModel = new Model<ModelState>(
+ state ?? { count: 0 },
+ createMockComm(),
+ );
+ WIDGET_REGISTRY.setModel(modelId, childModel);
+ WIDGET_REGISTRY.setSpec(modelId, {
+ url: `./@file/10-${modelId}.js`,
+ // Unique per test: the def registry caches modules by hash.
+ hash: `hash-${modelId}`,
+ });
+ getModuleSpy.mockResolvedValue({ default: widgetDef });
+ return childModel;
+ }
+
+ describe("getModel", () => {
+ it("resolves the child model by ref", async () => {
+ const childModel = new Model<ModelState>({ value: 42 }, createMockComm());
+ WIDGET_REGISTRY.setModel(modelId, childModel);
+
+ const host = createHost(WIDGET_REGISTRY, parentController.signal);
+ const resolved = await host.getModel(ref(modelId));
+ expect(resolved.get("value")).toBe(42);
+ });
+
+ it("rejects an invalid ref", async () => {
+ const host = createHost(WIDGET_REGISTRY, parentController.signal);
+ await expect(host.getModel("IPY_MODEL_xyz")).rejects.toThrow(/Invalid/);
+ });
+
+ it("scopes listeners on the resolved model to the parent's signal", async () => {
+ const childModel = new Model<ModelState>({ count: 0 }, createMockComm());
+ WIDGET_REGISTRY.setModel(modelId, childModel);
+
+ const host = createHost(WIDGET_REGISTRY, parentController.signal);
+ const resolved = await host.getModel(ref(modelId));
+
+ const cb = vi.fn();
+ resolved.on("change:count", cb);
+ childModel.set("count", 1);
+ expect(cb).toHaveBeenCalledTimes(1);
+
+ // Aborting the parent signal should clear the listener even though
+ // the caller never wired it up themselves.
+ parentController.abort();
+ childModel.set("count", 2);
+ expect(cb).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe("getWidget", () => {
+ it("resolves an undisplayed child with exports and a render method", async () => {
+ const exports = { setValue: vi.fn() };
+ const widgetDef = {
+ initialize: vi.fn().mockResolvedValue(exports),
+ render: vi.fn(),
+ };
+ registerChild(widgetDef);
+
+ const host = createHost(WIDGET_REGISTRY, parentController.signal);
+ const resolved = await host.getWidget(ref(modelId));
+ expect(resolved.exports).toBe(exports);
+
+ const el = document.createElement("div");
+ await resolved.render({ el });
+ expect(widgetDef.render).toHaveBeenCalledTimes(1);
+ expect(widgetDef.render.mock.calls[0][0].el).toBe(el);
+ });
+
+ it("waits for an in-flight `initialize` to settle", async () => {
+ let resolveInit!: (v: object) => void;
+ const widgetDef = {
+ initialize: vi.fn().mockReturnValue(
+ new Promise<object>((r) => {
+ resolveInit = r;
+ }),
+ ),
+ render: vi.fn(),
+ };
+ registerChild(widgetDef);
+
+ const host = createHost(WIDGET_REGISTRY, parentController.signal);
+ const widgetPromise = host.getWidget(ref(modelId));
+
+ // Until initialize resolves, getWidget should be pending.
+ let resolvedExports: unknown;
+ widgetPromise.then((w) => {
+ resolvedExports = w.exports;
+ });
+ await new Promise((r) => setTimeout(r, 5));
+ expect(resolvedExports).toBeUndefined();
+
+ const exports = { ready: true };
+ resolveInit(exports);
+ const resolved = await widgetPromise;
+ expect(resolved.exports).toBe(exports);
+ });
+
+ it("rejects if the child is deleted mid-initialize", async () => {
+ const widgetDef = {
+ initialize: vi.fn().mockReturnValue(new Promise(() => undefined)),
+ render: vi.fn(),
+ };
+ registerChild(widgetDef);
+
+ const host = createHost(WIDGET_REGISTRY, parentController.signal);
+ const widgetPromise = host.getWidget(ref(modelId));
+ widgetPromise.catch(() => undefined);
+ // Let the import resolve and initialize start.
+ await new Promise((r) => setTimeout(r, 0));
+
+ WIDGET_REGISTRY.delete(modelId);
+
+ await expect(widgetPromise).rejects.toThrow(/binding destroyed/);
+ });
+
+ it("rejects for a child that has no ESM spec", async () => {
+ // e.g. a ref to a traditional jupyter widget's model.
+ const childModel = new Model<ModelState>({ count: 0 }, createMockComm());
+ WIDGET_REGISTRY.setModel(modelId, childModel);
+
+ const host = createHost(WIDGET_REGISTRY, parentController.signal);
+ await expect(host.getWidget(ref(modelId))).rejects.toThrow(/No ESM spec/);
+ });
+
+ it("uses the parent's signal as a default for child render", async () => {
+ const widgetDef = {
+ initialize: vi.fn(),
+ render: vi.fn(),
+ };
+ registerChild(widgetDef);
+
+ const host = createHost(WIDGET_REGISTRY, parentController.signal);
+ const resolved = await host.getWidget(ref(modelId));
+
+ await resolved.render({ el: document.createElement("div") });
+ const childRenderSignal = widgetDef.render.mock.calls[0][0].signal;
+ expect(childRenderSignal.aborted).toBe(false);
+
+ // Aborting the parent signal cascades to the child's view.
+ parentController.abort();
+ expect(childRenderSignal.aborted).toBe(true);
+ });
+
+ it("uses the caller-supplied signal when given, ignoring the parent default", async () => {
+ const widgetDef = {
+ initialize: vi.fn(),
+ render: vi.fn(),
+ };
+ registerChild(widgetDef);
+
+ const host = createHost(WIDGET_REGISTRY, parentController.signal);
+ const resolved = await host.getWidget(ref(modelId));
+
+ const childController = new AbortController();
+ await resolved.render({
+ el: document.createElement("div"),
+ signal: childController.signal,
+ });
+ const childRenderSignal = widgetDef.render.mock.calls[0][0].signal;
+ expect(childRenderSignal.aborted).toBe(false);
+
+ childController.abort();
+ expect(childRenderSignal.aborted).toBe(true);
+ });
+ });
+});
+
+describe("WidgetBinding receives a host in render props", () => {
+ it("passes a host into render whose getWidget resolves siblings", async () => {
+ const parentId = asModelId("host-render-parent");
+ const childId = asModelId("host-render-child");
+ const parentController = new AbortController();
+ const getModuleSpy = vi.spyOn(WIDGET_DEF_REGISTRY, "getModule");
+ try {
+ const childExports = { id: "child" };
+ const childWidget = {
+ initialize: vi.fn().mockResolvedValue(childExports),
+ render: vi.fn(),
+ };
+ const childModel = new Model<ModelState>({ count: 0 }, createMockComm());
+ WIDGET_REGISTRY.setModel(childId, childModel);
+ WIDGET_REGISTRY.setSpec(childId, {
+ url: "./@file/10-host-render-child.js",
+ hash: "hash-host-render-child",
+ });
+ getModuleSpy.mockResolvedValue({ default: childWidget });
+
+ const parentModel = new Model<ModelState>(
+ { child: `${WIDGET_REF_PREFIX}${childId}` },
+ createMockComm(),
+ );
+ WIDGET_REGISTRY.setModel(parentId, parentModel);
+
+ const parentWidget = {
+ initialize: vi.fn(),
+ render: vi.fn(),
+ };
+ const parentBinding = await WidgetBinding.create({
+ widgetDef: parentWidget,
+ model: parentModel,
+ createHost: (signal) => createHost(WIDGET_REGISTRY, signal),
+ });
+
+ await parentBinding.createView(
+ { el: document.createElement("div") },
+ { signal: parentController.signal },
+ );
+
+ const renderProps = parentWidget.render.mock.calls[0][0];
+ expect(renderProps.host).toBeDefined();
+ expect(typeof renderProps.host.getWidget).toBe("function");
+
+ const resolved = await renderProps.host.getWidget(
+ parentModel.get("child"),
+ );
+ expect(resolved.exports).toBe(childExports);
+ } finally {
+ WIDGET_REGISTRY.delete(parentId);
+ WIDGET_REGISTRY.delete(childId);
+ getModuleSpy.mockRestore();
+ }
+ });
+});
+
+describe("host-mounted views hydrate like display-mounted ones", () => {
+ it("replays current state to a child's render listeners", async () => {
+ const childId = asModelId("host-hydration-child");
+ const parentController = new AbortController();
+ const getModuleSpy = vi.spyOn(WIDGET_DEF_REGISTRY, "getModule");
+ try {
+ const childWidget = {
+ render: vi.fn(({ model, el }) => {
+ el.textContent = "count is 5";
+ model.on("change:count", () => {
+ el.textContent = `count is ${model.get("count")}`;
+ });
+ }),
+ };
+ const childModel = new Model<ModelState>({ count: 8 }, createMockComm());
+ WIDGET_REGISTRY.setModel(childId, childModel);
+ WIDGET_REGISTRY.setSpec(childId, {
+ url: "./@file/10-host-hydration-child.js",
+ hash: "hash-host-hydration-child",
+ });
+ getModuleSpy.mockResolvedValue({ default: childWidget });
+
+ const host = createHost(WIDGET_REGISTRY, parentController.signal);
+ const resolved = await host.getWidget(ref(childId));
+
+ const el = document.createElement("div");
+ await resolved.render({ el });
+ expect(el.textContent).toBe("count is 8");
+ } finally {
+ WIDGET_REGISTRY.delete(childId);
+ getModuleSpy.mockRestore();
+ }
+ });
+});
diff --git a/frontend/src/plugins/impl/anywidget/__tests__/model-proxy.test.ts b/frontend/src/plugins/impl/anywidget/__tests__/model-proxy.test.ts
new file mode 100644
index 0000000000..a6eafa5897
--- /dev/null
+++ b/frontend/src/plugins/impl/anywidget/__tests__/model-proxy.test.ts
@@ -0,0 +1,158 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import { describe, expect, it, vi } from "vitest";
+import { Model } from "../model";
+import { modelProxy } from "../model-proxy";
+import type { ModelState } from "../types";
+
+function createMockComm() {
+ return {
+ sendUpdate: vi.fn().mockResolvedValue(undefined),
+ sendCustomMessage: vi.fn().mockResolvedValue(undefined),
+ };
+}
+
+describe("Model.on signal option", () => {
+ it("removes the listener when the signal aborts", () => {
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
+ const controller = new AbortController();
+ const cb = vi.fn();
+
+ model.on("change:count", cb, { signal: controller.signal });
+ model.set("count", 1);
+ expect(cb).toHaveBeenCalledTimes(1);
+
+ controller.abort();
+ model.set("count", 2);
+ expect(cb).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not register if the signal is already aborted", () => {
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
+ const controller = new AbortController();
+ controller.abort();
+ const cb = vi.fn();
+
+ model.on("change:count", cb, { signal: controller.signal });
+ model.set("count", 1);
+ expect(cb).not.toHaveBeenCalled();
+ });
+
+ it("scopes listeners independently per signal", () => {
+ const model = new Model<ModelState>({ value: 0 }, createMockComm());
+ const view1 = new AbortController();
+ const view2 = new AbortController();
+ const cb1 = vi.fn();
+ const cb2 = vi.fn();
+
+ model.on("change:value", cb1, { signal: view1.signal });
+ model.on("change:value", cb2, { signal: view2.signal });
+
+ model.set("value", 1);
+ expect(cb1).toHaveBeenCalledTimes(1);
+ expect(cb2).toHaveBeenCalledTimes(1);
+
+ view1.abort();
+ model.set("value", 2);
+ expect(cb1).toHaveBeenCalledTimes(1);
+ expect(cb2).toHaveBeenCalledTimes(2);
+ });
+
+ it("allows a listener to call off() during emit without skipping siblings", () => {
+ // Snapshot-before-iterate guard: a listener that removes itself
+ // (typical signal-abort cleanup path) shouldn't drop a sibling.
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
+ const sibling = vi.fn();
+ const selfRemoving = vi.fn(() => model.off("change:count", selfRemoving));
+
+ model.on("change:count", selfRemoving);
+ model.on("change:count", sibling);
+
+ model.set("count", 1);
+ expect(selfRemoving).toHaveBeenCalledTimes(1);
+ expect(sibling).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("modelProxy", () => {
+ it("auto-ties on() to the supplied signal", () => {
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
+ const controller = new AbortController();
+ const proxy = modelProxy(model, controller.signal);
+ const cb = vi.fn();
+
+ proxy.on("change:count", cb);
+ model.set("count", 1);
+ expect(cb).toHaveBeenCalledTimes(1);
+
+ // Aborting the signal should clear the listener even though the
+ // widget author never wired it up themselves.
+ controller.abort();
+ model.set("count", 2);
+ expect(cb).toHaveBeenCalledTimes(1);
+ });
+
+ it("scopes child listeners to per-view signals", () => {
+ const model = new Model<ModelState>({ value: 0 }, createMockComm());
+ const view1 = new AbortController();
+ const view2 = new AbortController();
+ const cb1 = vi.fn();
+ const cb2 = vi.fn();
+
+ modelProxy(model, view1.signal).on("change:value", cb1);
+ modelProxy(model, view2.signal).on("change:value", cb2);
+
+ model.set("value", 1);
+ expect(cb1).toHaveBeenCalledTimes(1);
+ expect(cb2).toHaveBeenCalledTimes(1);
+
+ // Dispose view1 — view2's listener stays.
+ view1.abort();
+ model.set("value", 2);
+ expect(cb1).toHaveBeenCalledTimes(1);
+ expect(cb2).toHaveBeenCalledTimes(2);
+ });
+
+ it("scopes legacy widget_manager child listeners to the parent signal", async () => {
+ const parent = new Model<ModelState>({}, createMockComm());
+ const child = new Model<ModelState>({ count: 0 }, createMockComm());
+ vi.spyOn(parent.widget_manager, "get_model").mockResolvedValue(child);
+ const controller = new AbortController();
+ const parentProxy = modelProxy(parent, controller.signal);
+
+ const childProxy =
+ await parentProxy.widget_manager.get_model<ModelState>("child-id");
+ const callback = vi.fn();
+ childProxy.on("change:count", callback);
+
+ child.set("count", 1);
+ expect(callback).toHaveBeenCalledTimes(1);
+
+ controller.abort();
+ child.set("count", 2);
+ expect(callback).toHaveBeenCalledTimes(1);
+ });
+
+ it("forwards get / set / save_changes", () => {
+ const comm = createMockComm();
+ const model = new Model<ModelState>({ count: 0 }, comm);
+ const controller = new AbortController();
+ const proxy = modelProxy(model, controller.signal);
+
+ proxy.set("count", 5);
+ expect(proxy.get("count")).toBe(5);
+ proxy.save_changes();
+ expect(comm.sendUpdate).toHaveBeenCalledWith({ count: 5 });
+ });
+
+ it("forwards off() through to the underlying model", () => {
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
+ const controller = new AbortController();
+ const proxy = modelProxy(model, controller.signal);
+ const cb = vi.fn();
+
+ proxy.on("change:count", cb);
+ proxy.off("change:count", cb);
+ model.set("count", 1);
+ expect(cb).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/plugins/impl/anywidget/__tests__/model.test.ts b/frontend/src/plugins/impl/anywidget/__tests__/model.test.ts
index 99c86f6930..4cafb0c985 100644
--- a/frontend/src/plugins/impl/anywidget/__tests__/model.test.ts
+++ b/frontend/src/plugins/impl/anywidget/__tests__/model.test.ts
@@ -9,16 +9,9 @@ import {
vi,
} from "vitest";
import { TestUtils } from "@/__tests__/test-helpers";
-import {
- getMarimoInternal,
- handleWidgetMessage,
- Model,
- visibleForTesting,
-} from "../model";
-import type { WidgetModelId } from "../types";
-import { BINDING_MANAGER } from "../widget-binding";
-
-const { ModelManager } = visibleForTesting;
+import { getMarimoInternal, Model } from "../model";
+import { WidgetRegistry } from "../registry";
+import type { ModelState, WidgetModelId } from "../types";
// Helper to create typed model IDs for tests
const asModelId = (id: string): WidgetModelId => id as WidgetModelId;
@@ -38,7 +31,7 @@ vi.mock("@/core/static/static-state", () => ({
}));
// Helper to create a mock MarimoComm
-function createMockComm<T>() {
+function createMockComm() {
return {
sendUpdate: vi.fn().mockResolvedValue(undefined),
sendCustomMessage: vi.fn().mockResolvedValue(undefined),
@@ -47,7 +40,7 @@ function createMockComm<T>() {
describe("Model", () => {
let model: Model<{ foo: string; bar: number }>;
- let mockComm: ReturnType<typeof createMockComm<{ foo: string; bar: number }>>;
+ let mockComm: ReturnType<typeof createMockComm>;
beforeEach(() => {
mockComm = createMockComm();
@@ -211,13 +204,13 @@ describe("Model", () => {
describe("widget_manager", () => {
const childModelId = asModelId("test-id");
- const childModel = new Model({ foo: "test" }, createMockComm());
- const manager = new ModelManager(10);
+ const childModel = new Model<ModelState>({ foo: "test" }, createMockComm());
+ const manager = new WidgetRegistry(10);
let previousModelManager = Model._modelManager;
beforeAll(() => {
previousModelManager = Model._modelManager;
- manager.set(childModelId, childModel);
+ manager.setModel(childModelId, childModel);
Model._modelManager = manager;
});
@@ -272,25 +265,6 @@ describe("Model", () => {
});
});
- describe("reemitState", () => {
- it("should emit change events for current values without state changes", async () => {
- const onFoo = vi.fn();
- const onBar = vi.fn();
- const onAny = vi.fn();
-
- model.on("change:foo", onFoo);
- model.on("change:bar", onBar);
- model.on("change", onAny);
-
- getMarimoInternal(model).reemitState();
- await TestUtils.nextTick();
-
- expect(onFoo).toHaveBeenCalledWith("test");
- expect(onBar).toHaveBeenCalledWith(123);
- expect(onAny).toHaveBeenCalledTimes(1);
- });
- });
-
describe("emitCustomMessage", () => {
it("should handle custom messages", () => {
const callback = vi.fn();
@@ -323,146 +297,3 @@ describe("Model", () => {
});
});
});
-
-describe("ModelManager", () => {
- let modelManager = new ModelManager(50);
- const testId = asModelId("test-id");
-
- beforeEach(() => {
- // Clear the model manager before each test
- modelManager = new ModelManager(50);
- mockSendModelValue.mockClear();
- });
-
- it("should set and get models", async () => {
- const model = new Model({ count: 0 }, createMockComm());
- modelManager.set(testId, model);
- const retrievedModel = await modelManager.get(testId);
- expect(retrievedModel).toBe(model);
- });
-
- it("should handle model not found", async () => {
- await expect(modelManager.get(asModelId("non-existent"))).rejects.toThrow(
- "Model not found for key: non-existent",
- );
- });
-
- it("should delete models", async () => {
- const model = new Model({ count: 0 }, createMockComm());
- modelManager.set(testId, model);
- modelManager.delete(testId);
- await expect(modelManager.get(testId)).rejects.toThrow();
- });
-
- it("should handle widget messages", async () => {
- await handleWidgetMessage(modelManager, {
- model_id: testId,
- message: {
- method: "open",
- state: { count: 0 },
- buffer_paths: [],
- buffers: [],
- },
- });
- const model = await modelManager.get(testId);
- expect(model.get("count")).toBe(0);
-
- await handleWidgetMessage(modelManager, {
- model_id: testId,
- message: {
- method: "update",
- state: { count: 1 },
- buffer_paths: [],
- buffers: [],
- },
- });
- expect(model.get("count")).toBe(1);
- });
-
- it("should handle custom messages", async () => {
- const model = new Model({ count: 0 }, createMockComm());
- const callback = vi.fn();
- model.on("msg:custom", callback);
- modelManager.set(testId, model);
-
- await handleWidgetMessage(modelManager, {
- model_id: testId,
- message: { method: "custom", content: { count: 1 }, buffers: [] },
- });
- expect(callback).toHaveBeenCalledWith({ count: 1 }, []);
- });
-
- it("should handle close messages", async () => {
- const model = new Model({ count: 0 }, createMockComm());
- modelManager.set(testId, model);
-
- await handleWidgetMessage(modelManager, {
- model_id: testId,
- message: { method: "close" },
- });
- await expect(modelManager.get(testId)).rejects.toThrow();
- });
-
- it("should destroy binding on close message", async () => {
- const model = new Model({ count: 0 }, createMockComm());
- modelManager.set(testId, model);
-
- // Create a binding for this model
- BINDING_MANAGER.getOrCreate(testId);
- expect(BINDING_MANAGER.has(testId)).toBe(true);
-
- await handleWidgetMessage(modelManager, {
- model_id: testId,
- message: { method: "close" },
- });
-
- 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/__tests__/registry.test.ts b/frontend/src/plugins/impl/anywidget/__tests__/registry.test.ts
new file mode 100644
index 0000000000..cfe8363507
--- /dev/null
+++ b/frontend/src/plugins/impl/anywidget/__tests__/registry.test.ts
@@ -0,0 +1,708 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ type MockInstance,
+ vi,
+} from "vitest";
+import { getMarimoInternal, Model } from "../model";
+import { handleWidgetMessage, WidgetRegistry } from "../registry";
+import type { EsmSpec, ModelState, WidgetModelId } from "../types";
+import { WIDGET_DEF_REGISTRY } from "../widget-binding";
+
+// Helper to create typed model IDs for tests
+const asModelId = (id: string): WidgetModelId => id as WidgetModelId;
+
+// Mock the request client
+const mockSendModelValue = vi.fn().mockResolvedValue(null);
+vi.mock("@/core/network/requests", () => ({
+ getRequestClient: () => ({
+ sendModelValue: mockSendModelValue,
+ }),
+}));
+
+// Mock isStaticNotebook — default to false (normal mode)
+const mockIsStatic = vi.fn().mockReturnValue(false);
+vi.mock("@/core/static/static-state", () => ({
+ isStaticNotebook: () => mockIsStatic(),
+}));
+
+function createMockComm() {
+ return {
+ sendUpdate: vi.fn().mockResolvedValue(undefined),
+ sendCustomMessage: vi.fn().mockResolvedValue(undefined),
+ };
+}
+
+const SPEC: EsmSpec = { url: "./@file/10-widget.js", hash: "hash-1" };
+
+describe("WidgetRegistry models", () => {
+ let registry = new WidgetRegistry(50);
+ const testId = asModelId("test-id");
+
+ beforeEach(() => {
+ registry = new WidgetRegistry(50);
+ mockSendModelValue.mockClear();
+ });
+
+ it("should set and get models", async () => {
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
+ registry.setModel(testId, model);
+ const retrievedModel = await registry.getModel(testId);
+ expect(retrievedModel).toBe(model);
+ });
+
+ it("should handle model not found", async () => {
+ await expect(registry.getModel(asModelId("non-existent"))).rejects.toThrow(
+ "Model not found for key: non-existent",
+ );
+ });
+
+ it("accepts a fresh model after an earlier rendezvous times out", async () => {
+ const id = asModelId("late-model");
+ await expect(registry.getModel(id)).rejects.toThrow(
+ "Model not found for key: late-model",
+ );
+
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
+ registry.setModel(id, model);
+
+ await expect(registry.getModel(id)).resolves.toBe(model);
+ });
+
+ it("disposes a pre-open view when model rendezvous times out", async () => {
+ const id = asModelId("timed-out-view");
+ const host = document.createElement("div");
+ const root = host.attachShadow({ mode: "open" });
+ const el = document.createElement("div");
+ root.append(el);
+ const controller = new AbortController();
+
+ const pending = registry.createView({
+ modelId: id,
+ el,
+ signal: controller.signal,
+ });
+ expect(root.querySelector("style")).not.toBeNull();
+
+ await expect(pending).rejects.toThrow(
+ "Model not found for key: timed-out-view",
+ );
+ expect(root.querySelector("style")).toBeNull();
+ expect(controller.signal.aborted).toBe(false);
+ });
+
+ it("should delete models", async () => {
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
+ registry.setModel(testId, model);
+ registry.delete(testId);
+ await expect(registry.getModel(testId)).rejects.toThrow();
+ });
+
+ it("should handle widget messages", async () => {
+ await handleWidgetMessage(registry, {
+ model_id: testId,
+ message: {
+ method: "open",
+ state: { count: 0 },
+ buffer_paths: [],
+ buffers: [],
+ },
+ });
+ const model = await registry.getModel(testId);
+ expect(model.get("count")).toBe(0);
+
+ await handleWidgetMessage(registry, {
+ model_id: testId,
+ message: {
+ method: "update",
+ state: { count: 1 },
+ buffer_paths: [],
+ buffers: [],
+ },
+ });
+ expect(model.get("count")).toBe(1);
+ });
+
+ it("should handle custom messages", async () => {
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
+ const callback = vi.fn();
+ model.on("msg:custom", callback);
+ registry.setModel(testId, model);
+
+ await handleWidgetMessage(registry, {
+ model_id: testId,
+ message: { method: "custom", content: { count: 1 }, buffers: [] },
+ });
+ expect(callback).toHaveBeenCalledWith({ count: 1 }, []);
+ });
+
+ it("should handle close messages", async () => {
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
+ registry.setModel(testId, model);
+
+ await handleWidgetMessage(registry, {
+ model_id: testId,
+ message: { method: "close" },
+ });
+ await expect(registry.getModel(testId)).rejects.toThrow();
+ });
+
+ describe("static mode", () => {
+ beforeEach(() => {
+ mockIsStatic.mockReturnValue(true);
+ });
+
+ afterEach(() => {
+ mockIsStatic.mockReturnValue(false);
+ });
+
+ it("should create model with no-op comm in static mode", async () => {
+ await handleWidgetMessage(registry, {
+ model_id: testId,
+ message: {
+ method: "open",
+ state: { count: 42 },
+ buffer_paths: [],
+ buffers: [],
+ },
+ });
+
+ const model = await registry.getModel(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(registry, {
+ model_id: testId,
+ message: {
+ method: "open",
+ state: { count: 0 },
+ buffer_paths: [],
+ buffers: [],
+ },
+ });
+
+ const model = await registry.getModel(testId);
+ // send() should silently no-op
+ await expect(model.send({ test: true })).resolves.toBeUndefined();
+ expect(mockSendModelValue).not.toHaveBeenCalled();
+ });
+ });
+});
+
+describe("WidgetRegistry.getWidget", () => {
+ let registry = new WidgetRegistry(50);
+ const testId = asModelId("widget-id");
+ let getModuleSpy: MockInstance<typeof WIDGET_DEF_REGISTRY.getModule>;
+
+ beforeEach(() => {
+ registry = new WidgetRegistry(50);
+ getModuleSpy = vi.spyOn(WIDGET_DEF_REGISTRY, "getModule");
+ });
+
+ afterEach(() => {
+ getModuleSpy.mockRestore();
+ });
+
+ it("binds an undisplayed widget from its ESM spec", async () => {
+ // The composition case: the child's model and spec arrived on its
+ // open message, but no display mount ever renders it standalone.
+ // getWidget must self-serve from the spec.
+ const exports = { hello: vi.fn() };
+ const widgetDef = {
+ initialize: vi.fn().mockResolvedValue(exports),
+ render: vi.fn(),
+ };
+ getModuleSpy.mockResolvedValue({ default: widgetDef });
+
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
+ registry.setModel(testId, model);
+ registry.setSpec(testId, SPEC);
+
+ const widget = await registry.getWidget(testId);
+
+ expect(getModuleSpy).toHaveBeenCalledWith({
+ jsUrl: SPEC.url,
+ jsHash: SPEC.hash,
+ kernelAuthored: true,
+ });
+ expect(widgetDef.initialize).toHaveBeenCalledTimes(1);
+ expect(widget.exports).toBe(exports);
+ });
+
+ it("records the spec from an open message", async () => {
+ const widgetDef = { initialize: vi.fn(), render: vi.fn() };
+ getModuleSpy.mockResolvedValue({ default: widgetDef });
+
+ await handleWidgetMessage(registry, {
+ model_id: testId,
+ message: {
+ method: "open",
+ state: { count: 0 },
+ buffer_paths: [],
+ buffers: [],
+ esm_spec: { url: SPEC.url, hash: SPEC.hash },
+ },
+ });
+
+ await registry.getWidget(testId);
+ expect(getModuleSpy).toHaveBeenCalledWith({
+ jsUrl: SPEC.url,
+ jsHash: SPEC.hash,
+ kernelAuthored: true,
+ });
+ });
+
+ it("shares one generation across concurrent and repeat callers", async () => {
+ const widgetDef = { initialize: vi.fn(), render: vi.fn() };
+ getModuleSpy.mockResolvedValue({ default: widgetDef });
+
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
+ registry.setModel(testId, model);
+ registry.setSpec(testId, SPEC);
+
+ const [a, b] = await Promise.all([
+ registry.getWidget(testId),
+ registry.getWidget(testId),
+ ]);
+ const c = await registry.getWidget(testId);
+ expect(a.exports).toBe(b.exports);
+ expect(a.exports).toBe(c.exports);
+ expect(widgetDef.initialize).toHaveBeenCalledTimes(1);
+ expect(getModuleSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it("fails fast for a model with no ESM spec", async () => {
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
+ registry.setModel(testId, model);
+
+ await expect(registry.getWidget(testId)).rejects.toThrow(
+ /No ESM spec for model/,
+ );
+ });
+
+ it("rejects when the module import fails, then retries fresh", async () => {
+ getModuleSpy.mockRejectedValueOnce(new Error("network down"));
+
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
+ registry.setModel(testId, model);
+ registry.setSpec(testId, SPEC);
+
+ await expect(registry.getWidget(testId)).rejects.toThrow("network down");
+
+ // A failed generation must not poison the entry: the next call
+ // starts over from the spec.
+ const widgetDef = { initialize: vi.fn(), render: vi.fn() };
+ getModuleSpy.mockResolvedValue({ default: widgetDef });
+ const widget = await registry.getWidget(testId);
+ expect(widget.exports).toBeUndefined();
+ expect(widgetDef.initialize).toHaveBeenCalledTimes(1);
+ });
+
+ it("rejects with the AFM error when the module has no usable exports", async () => {
+ getModuleSpy.mockResolvedValue({ notAWidget: true });
+
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
+ registry.setModel(testId, model);
+ registry.setSpec(testId, SPEC);
+
+ await expect(registry.getWidget(testId)).rejects.toThrow(
+ /missing a default export/,
+ );
+ });
+
+ it("rejects when the model never arrives", async () => {
+ await expect(registry.getWidget(asModelId("never-opened"))).rejects.toThrow(
+ "Model not found for key: never-opened",
+ );
+ });
+
+ it("rejects an in-flight initialize when the entry is deleted", async () => {
+ const widgetDef = {
+ initialize: vi.fn().mockReturnValue(new Promise(() => undefined)),
+ render: vi.fn(),
+ };
+ getModuleSpy.mockResolvedValue({ default: widgetDef });
+
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
+ registry.setModel(testId, model);
+ registry.setSpec(testId, SPEC);
+
+ const pending = registry.getWidget(testId);
+ pending.catch(() => undefined);
+ // Let the import resolve and initialize start.
+ await new Promise((r) => setTimeout(r, 0));
+
+ registry.delete(testId);
+ await expect(pending).rejects.toThrow(/binding destroyed/);
+ });
+
+ it("destroys the generation on a close message", async () => {
+ const initCleanup = vi.fn();
+ const widgetDef = {
+ initialize: vi.fn().mockResolvedValue(initCleanup),
+ render: vi.fn(),
+ };
+ getModuleSpy.mockResolvedValue({ default: widgetDef });
+
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
+ registry.setModel(testId, model);
+ registry.setSpec(testId, SPEC);
+ await registry.getWidget(testId);
+
+ await handleWidgetMessage(registry, {
+ model_id: testId,
+ message: { method: "close" },
+ });
+ expect(initCleanup).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("WidgetRegistry generation swap (hot reload)", () => {
+ const testId = asModelId("hmr-id");
+ const SPEC_V1: EsmSpec = { url: "./@file/10-v1.js", hash: "hash-v1" };
+ const SPEC_V2: EsmSpec = { url: "./@file/10-v2.js", hash: "hash-v2" };
+ let getModuleSpy: MockInstance<typeof WIDGET_DEF_REGISTRY.getModule>;
+
+ const makeWidget = (label: string) => ({
+ initialize: vi.fn(),
+ render: vi.fn(({ el }: { el: HTMLElement }) => {
+ el.textContent = label;
+ }),
+ });
+
+ beforeEach(() => {
+ getModuleSpy = vi.spyOn(WIDGET_DEF_REGISTRY, "getModule");
+ });
+
+ afterEach(() => {
+ getModuleSpy.mockRestore();
+ });
+
+ async function setup(isEditMode: boolean) {
+ const registry = new WidgetRegistry(50, () => isEditMode);
+ const v1 = makeWidget("v1");
+ const v2 = makeWidget("v2");
+ getModuleSpy.mockImplementation(async ({ jsUrl }) => {
+ return jsUrl === SPEC_V1.url ? { default: v1 } : { default: v2 };
+ });
+
+ await handleWidgetMessage(registry, {
+ model_id: testId,
+ message: {
+ method: "open",
+ state: { count: 3 },
+ buffer_paths: [],
+ buffers: [],
+ esm_spec: { url: SPEC_V1.url, hash: SPEC_V1.hash },
+ },
+ });
+ const model = await registry.getModel(testId);
+ const widget = await registry.getWidget(testId);
+
+ // Mount a live view the swap must re-render.
+ const el = document.createElement("div");
+ const viewController = new AbortController();
+ await widget.render({ el, signal: viewController.signal });
+ expect(el.textContent).toBe("v1");
+
+ return { registry, model, widget, el, viewController, v1, v2 };
+ }
+
+ it("preserves the initial spec before first mount outside edit mode", async () => {
+ const registry = new WidgetRegistry(50, () => false);
+ const v1 = makeWidget("v1");
+ const v2 = makeWidget("v2");
+ getModuleSpy.mockImplementation(async ({ jsUrl }) => ({
+ default: jsUrl === SPEC_V1.url ? v1 : v2,
+ }));
+ registry.setModel(
+ testId,
+ new Model<ModelState>({ count: 0 }, createMockComm()),
+ );
+ registry.setSpec(testId, SPEC_V1);
+
+ // A viewer may receive an editor's hot-reload update before it ever
+ // mounts this widget. Its code must still be immutable for the model.
+ registry.setSpec(testId, SPEC_V2);
+ const widget = await registry.getWidget(testId);
+ const el = document.createElement("div");
+ await widget.render({ el });
+
+ expect(el.textContent).toBe("v1");
+ expect(v1.initialize).toHaveBeenCalledTimes(1);
+ expect(v2.initialize).not.toHaveBeenCalled();
+ });
+
+ it("swaps the generation and re-renders live views in edit mode", async () => {
+ const { registry, model, el, v1, v2 } = await setup(true);
+
+ const onCount = vi.fn();
+ model.on("change:count", onCount);
+
+ await handleWidgetMessage(registry, {
+ model_id: testId,
+ message: {
+ method: "update",
+ state: {},
+ buffer_paths: [],
+ buffers: [],
+ esm_spec: { url: SPEC_V2.url, hash: SPEC_V2.hash },
+ },
+ });
+
+ const next = await registry.getWidget(testId);
+ // Wait for the swap's re-render to land in the DOM.
+ await vi.waitFor(() => {
+ expect(el.textContent).toBe("v2");
+ });
+ expect(v2.initialize).toHaveBeenCalledTimes(1);
+ expect(v2.render).toHaveBeenCalledTimes(1);
+ // The old generation rendered exactly once, before the swap.
+ expect(v1.render).toHaveBeenCalledTimes(1);
+ // Model state persists across generations — that's the "hot" part.
+ expect(next.exports).toBeUndefined();
+ expect(model.get("count")).toBe(3);
+ // Listeners registered outside the binding survive.
+ model.set("count", 4);
+ expect(onCount).toHaveBeenCalledTimes(1);
+ });
+
+ it("ignores replacement specs outside edit mode", async () => {
+ const { registry, el, v2 } = await setup(false);
+
+ await handleWidgetMessage(registry, {
+ model_id: testId,
+ message: {
+ method: "update",
+ state: {},
+ buffer_paths: [],
+ buffers: [],
+ esm_spec: { url: SPEC_V2.url, hash: SPEC_V2.hash },
+ },
+ });
+
+ await registry.getWidget(testId);
+ expect(v2.initialize).not.toHaveBeenCalled();
+ expect(el.textContent).toBe("v1");
+ });
+
+ it("ignores an update whose spec hash is unchanged", async () => {
+ const { registry, v1 } = await setup(true);
+
+ await handleWidgetMessage(registry, {
+ model_id: testId,
+ message: {
+ method: "update",
+ state: {},
+ buffer_paths: [],
+ buffers: [],
+ esm_spec: { url: SPEC_V1.url, hash: SPEC_V1.hash },
+ },
+ });
+
+ await registry.getWidget(testId);
+ expect(v1.initialize).toHaveBeenCalledTimes(1);
+ });
+
+ it("cleans up the old generation's listeners on swap", async () => {
+ const { registry, model } = await setup(true);
+
+ // v1's render registered nothing; attach a listener the way a
+ // widget would, through a generation-scoped proxy — easiest to
+ // observe via initialize cleanup of a fresh generation:
+ const onCount = vi.fn();
+ const v3 = {
+ initialize: vi.fn(({ model }: { model: { on: Function } }) => {
+ model.on("change:count", onCount);
+ }),
+ render: vi.fn(),
+ };
+ getModuleSpy.mockResolvedValue({ default: v3 });
+
+ await handleWidgetMessage(registry, {
+ model_id: testId,
+ message: {
+ method: "update",
+ state: {},
+ buffer_paths: [],
+ buffers: [],
+ esm_spec: { url: "./@file/10-v3.js", hash: "hash-v3" },
+ },
+ });
+ await registry.getWidget(testId);
+
+ model.set("count", 10);
+ expect(onCount).toHaveBeenCalledTimes(1);
+
+ // Swap again: v3's listener must be gone afterwards.
+ getModuleSpy.mockResolvedValue({ default: makeWidget("v4") });
+ await handleWidgetMessage(registry, {
+ model_id: testId,
+ message: {
+ method: "update",
+ state: {},
+ buffer_paths: [],
+ buffers: [],
+ esm_spec: { url: "./@file/10-v4.js", hash: "hash-v4" },
+ },
+ });
+ await registry.getWidget(testId);
+
+ model.set("count", 11);
+ expect(onCount).toHaveBeenCalledTimes(1);
+ });
+
+ it("starts a new generation without waiting for stale initialize", async () => {
+ const registry = new WidgetRegistry(50, () => true);
+ const first = {
+ initialize: vi.fn().mockReturnValue(new Promise(() => undefined)),
+ render: vi.fn(),
+ };
+ const second = { initialize: vi.fn(), render: vi.fn() };
+ getModuleSpy.mockImplementation(async ({ jsUrl }) => ({
+ default: jsUrl === SPEC_V1.url ? first : second,
+ }));
+ registry.setModel(
+ testId,
+ new Model<ModelState>({ count: 0 }, createMockComm()),
+ );
+ registry.setSpec(testId, SPEC_V1);
+
+ const waiting = registry.getWidget(testId);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ registry.setSpec(testId, SPEC_V2);
+
+ await expect(waiting).resolves.toBeDefined();
+ expect(second.initialize).toHaveBeenCalledTimes(1);
+ });
+
+ it("waits for old render cleanup before rendering the replacement", async () => {
+ const registry = new WidgetRegistry(50, () => true);
+ let cleanupStarted!: () => void;
+ const started = new Promise<void>((resolve) => {
+ cleanupStarted = resolve;
+ });
+ let finishCleanup!: () => void;
+ const cleanupGate = new Promise<void>((resolve) => {
+ finishCleanup = resolve;
+ });
+ const v1 = {
+ initialize: vi.fn(),
+ render: vi.fn(({ el }: { el: HTMLElement }) => {
+ el.textContent = "v1";
+ return async () => {
+ cleanupStarted();
+ await cleanupGate;
+ el.textContent = "stale cleanup";
+ };
+ }),
+ };
+ const v2 = makeWidget("v2");
+ getModuleSpy.mockImplementation(async ({ jsUrl }) => ({
+ default: jsUrl === SPEC_V1.url ? v1 : v2,
+ }));
+ registry.setModel(
+ testId,
+ new Model<ModelState>({ count: 0 }, createMockComm()),
+ );
+ registry.setSpec(testId, SPEC_V1);
+ const widget = await registry.getWidget(testId);
+ const el = document.createElement("div");
+ await widget.render({ el });
+
+ registry.setSpec(testId, SPEC_V2);
+ await started;
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ const rendersBeforeCleanupFinished = v2.render.mock.calls.length;
+
+ finishCleanup();
+ expect(rendersBeforeCleanupFinished).toBe(0);
+ await vi.waitFor(() => {
+ expect(el.textContent).toBe("v2");
+ });
+ expect(v2.render).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("WidgetRegistry runtime styles", () => {
+ it("mounts composed widget CSS in its render root", async () => {
+ const registry = new WidgetRegistry(50);
+ const id = asModelId("styled-child");
+ const getModuleSpy = vi
+ .spyOn(WIDGET_DEF_REGISTRY, "getModule")
+ .mockResolvedValue({ default: { render: vi.fn() } });
+ const model = new Model<ModelState>(
+ { _css: ".child { color: red; }" },
+ createMockComm(),
+ );
+ registry.setModel(id, model);
+ registry.setSpec(id, {
+ url: "./@file/styled-child.js",
+ hash: "styled-child-hash",
+ });
+ const host = document.createElement("div");
+ const root = host.attachShadow({ mode: "open" });
+ const el = document.createElement("div");
+ root.append(el);
+ const controller = new AbortController();
+
+ try {
+ await registry.createView({
+ modelId: id,
+ el,
+ signal: controller.signal,
+ });
+ expect(root.querySelector("style")?.textContent).toContain("color: red");
+
+ model.set("_css", ".child { color: blue; }");
+ expect(root.querySelector("style")?.textContent).toContain("color: blue");
+
+ controller.abort();
+ expect(root.querySelector("style")).toBeNull();
+ } finally {
+ registry.delete(id);
+ getModuleSpy.mockRestore();
+ }
+ });
+});
+
+describe("WidgetRegistry custom messages during rendezvous", () => {
+ it("emits custom messages arriving before getWidget resolves", async () => {
+ // Regression guard for the rendezvous ordering: state and custom
+ // messages must flow to a model even while a generation is pending.
+ const registry = new WidgetRegistry(50);
+ const testId = asModelId("pending-custom");
+ const widgetDef = { initialize: vi.fn(), render: vi.fn() };
+ const getModuleSpy = vi
+ .spyOn(WIDGET_DEF_REGISTRY, "getModule")
+ .mockResolvedValue({ default: widgetDef });
+
+ try {
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
+ const callback = vi.fn();
+ model.on("msg:custom", callback);
+ registry.setModel(testId, model);
+ registry.setSpec(testId, SPEC);
+
+ const pending = registry.getWidget(testId);
+ getMarimoInternal(model).emitCustomMessage({
+ method: "custom",
+ content: { ping: 1 },
+ });
+ await pending;
+ expect(callback).toHaveBeenCalledWith({ ping: 1 }, []);
+ } finally {
+ getModuleSpy.mockRestore();
+ }
+ });
+});
diff --git a/frontend/src/plugins/impl/anywidget/__tests__/resolve-widget.test.ts b/frontend/src/plugins/impl/anywidget/__tests__/resolve-widget.test.ts
new file mode 100644
index 0000000000..78244e6c74
--- /dev/null
+++ b/frontend/src/plugins/impl/anywidget/__tests__/resolve-widget.test.ts
@@ -0,0 +1,132 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import { describe, expect, it, vi } from "vitest";
+import {
+ getInvalidAnyWidgetModuleError,
+ isAnyWidgetModule,
+ resolveAnyWidget,
+} from "../resolve-widget";
+
+describe("isAnyWidgetModule", () => {
+ it("should accept a default object with render", () => {
+ expect(isAnyWidgetModule({ default: { render: () => undefined } })).toBe(
+ true,
+ );
+ });
+
+ it("should accept a default factory function", () => {
+ expect(
+ isAnyWidgetModule({
+ default: async () => ({ render: () => undefined }),
+ }),
+ ).toBe(true);
+ });
+
+ it("should reject legacy named render exports", () => {
+ expect(isAnyWidgetModule({ render: () => undefined })).toBe(false);
+ });
+});
+
+describe("resolveAnyWidget", () => {
+ const jsUrl = "./@file/widget.js";
+
+ it("should return the default export when present", () => {
+ const widget = { render: () => undefined };
+ expect(resolveAnyWidget({ default: widget }, jsUrl)).toBe(widget);
+ });
+
+ it("should return a default factory function", () => {
+ const factory = async () => ({ render: () => undefined });
+ expect(resolveAnyWidget({ default: factory }, jsUrl)).toBe(factory);
+ });
+
+ it("should synthesize a widget from a legacy named render export", () => {
+ const render = vi.fn();
+ const resolved = resolveAnyWidget({ render }, jsUrl);
+ expect(resolved).not.toBeNull();
+ expect(resolved).toMatchObject({ render });
+ });
+
+ it("should synthesize a widget from a legacy named initialize export", () => {
+ const initialize = vi.fn();
+ const resolved = resolveAnyWidget({ initialize }, jsUrl);
+ expect(resolved).not.toBeNull();
+ expect(resolved).toMatchObject({ initialize });
+ });
+
+ it("should return null for a module with no valid exports", () => {
+ expect(resolveAnyWidget({}, jsUrl)).toBeNull();
+ expect(resolveAnyWidget({ default: {} }, jsUrl)).toBeNull();
+ expect(resolveAnyWidget({ render: "not a function" }, jsUrl)).toBeNull();
+ });
+
+ it("should return a stable widget identity across calls for one module", () => {
+ const mod = { render: vi.fn() };
+ expect(resolveAnyWidget(mod, jsUrl)).toBe(resolveAnyWidget(mod, jsUrl));
+ });
+
+ it("should not fall back to named exports when a default export is present", () => {
+ // A present-but-invalid default should surface an error, not be masked.
+ expect(
+ resolveAnyWidget({ default: {}, render: vi.fn() }, jsUrl),
+ ).toBeNull();
+ });
+});
+
+describe("getInvalidAnyWidgetModuleError", () => {
+ const jsUrl = "./@file/widget.js";
+
+ it("should explain legacy named render exports", () => {
+ const error = getInvalidAnyWidgetModuleError(
+ { render: () => undefined },
+ jsUrl,
+ );
+ expect(error.message).toContain("named exports (`render`)");
+ expect(error.message).toContain("`export default { render }`");
+ expect(error.message).toContain("not `export function render`");
+ });
+
+ it("should explain legacy named initialize exports", () => {
+ const error = getInvalidAnyWidgetModuleError(
+ { initialize: () => undefined },
+ jsUrl,
+ );
+ expect(error.message).toContain("named exports (`initialize`)");
+ expect(error.message).toContain("`export default { initialize }`");
+ expect(error.message).toContain("not `export function initialize`");
+ });
+
+ it("should avoid nested backticks for multi-hook named exports", () => {
+ const error = getInvalidAnyWidgetModuleError(
+ { render: () => undefined, initialize: () => undefined },
+ jsUrl,
+ );
+ expect(error.message).toContain(
+ "`export default { render, initialize }` (not `named export function ...`).",
+ );
+ expect(error.message).not.toContain("`named `export");
+ });
+
+ it("should explain a missing default export", () => {
+ expect(getInvalidAnyWidgetModuleError({}, jsUrl).message).toContain(
+ "missing a default export",
+ );
+ expect(getInvalidAnyWidgetModuleError(null, jsUrl).message).toContain(
+ "missing a default export",
+ );
+ });
+
+ it("should explain an invalid default export", () => {
+ const error = getInvalidAnyWidgetModuleError({ default: {} }, jsUrl);
+ expect(error.message).toContain("invalid default export");
+ expect(error.message).toContain("https://anywidget.dev/en/afm/");
+ });
+
+ it("prioritizes an invalid default over legacy named hooks", () => {
+ const error = getInvalidAnyWidgetModuleError(
+ { default: {}, render: () => undefined },
+ jsUrl,
+ );
+ expect(error.message).toContain("invalid default export");
+ expect(error.message).not.toContain("uses named exports");
+ });
+});
diff --git a/frontend/src/plugins/impl/anywidget/__tests__/widget-binding.test.ts b/frontend/src/plugins/impl/anywidget/__tests__/widget-binding.test.ts
index bd3091bd42..a197c7d9ea 100644
--- a/frontend/src/plugins/impl/anywidget/__tests__/widget-binding.test.ts
+++ b/frontend/src/plugins/impl/anywidget/__tests__/widget-binding.test.ts
@@ -1,19 +1,18 @@
/* Copyright 2026 Marimo. All rights reserved. */
import type { ExtractAtomValue } from "jotai";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { AnyWidget } from "@anywidget/types";
import { hasRunAnyCellAtom } from "@/components/editor/cell/useRunCells";
import { userConfigAtom } from "@/core/config/config";
import { parseUserConfig } from "@/core/config/config-schema";
import { initialModeAtom } from "@/core/mode";
import { store } from "@/core/state/jotai";
import { Model } from "../model";
-import type { ModelState, WidgetModelId } from "../types";
+import type { Host } from "../host";
+import type { ModelState } from "../types";
import { visibleForTesting } from "../widget-binding";
-const { WidgetDefRegistry, WidgetBinding, BindingManager } = visibleForTesting;
-
-// Helper to create typed model IDs for tests
-const asModelId = (id: string): WidgetModelId => id as WidgetModelId;
+const { WidgetDefRegistry, WidgetBinding } = visibleForTesting;
function createMockComm() {
return {
@@ -22,6 +21,34 @@ function createMockComm() {
};
}
+const createTestHost = (): Host => ({
+ getModel: vi.fn(),
+ getWidget: vi.fn(),
+});
+
+// oxlint-disable-next-line marimo/prefer-object-params -- terse test helper
+function createBinding<T extends ModelState>(
+ widgetDef: AnyWidget<T>,
+ model: Model<T>,
+ options: { controller?: AbortController } = {},
+) {
+ return WidgetBinding.create({
+ widgetDef,
+ model,
+ createHost: createTestHost,
+ controller: options.controller,
+ });
+}
+
+// oxlint-disable-next-line marimo/prefer-object-params -- terse test helper
+function getModule(
+ registry: InstanceType<typeof WidgetDefRegistry>,
+ jsUrl: string,
+ jsHash: string,
+) {
+ return registry.getModule({ jsUrl, jsHash });
+}
+
describe("WidgetDefRegistry", () => {
let registry: InstanceType<typeof WidgetDefRegistry>;
let previousConfig: ExtractAtomValue<typeof userConfigAtom>;
@@ -53,44 +80,35 @@ describe("WidgetDefRegistry", () => {
it("should cache modules by jsHash and return same promise", () => {
// Two calls with same hash should return the exact same promise object
- const promise1 = registry.getModule("http://localhost/widget.js", "hash1");
- const promise2 = registry.getModule("http://localhost/widget.js", "hash1");
+ const promise1 = getModule(registry, "http://localhost/widget.js", "hash1");
+ const promise2 = getModule(registry, "http://localhost/widget.js", "hash1");
expect(promise1).toBe(promise2);
// Catch the unhandled rejection from the import() attempt
promise1.catch(() => undefined);
});
it("should deduplicate concurrent imports for the same hash", () => {
- const promise1 = registry.getModule("http://localhost/a.js", "same-hash");
- const promise2 = registry.getModule("http://localhost/b.js", "same-hash");
+ const promise1 = getModule(registry, "http://localhost/a.js", "same-hash");
+ const promise2 = getModule(registry, "http://localhost/b.js", "same-hash");
// Same hash means same promise, even with different URLs
expect(promise1).toBe(promise2);
promise1.catch(() => undefined);
});
it("should create different promises for different hashes", () => {
- const promise1 = registry.getModule("http://localhost/a.js", "hash-a");
- const promise2 = registry.getModule("http://localhost/b.js", "hash-b");
+ const promise1 = getModule(registry, "http://localhost/a.js", "hash-a");
+ const promise2 = getModule(registry, "http://localhost/b.js", "hash-b");
expect(promise1).not.toBe(promise2);
promise1.catch(() => undefined);
promise2.catch(() => undefined);
});
- it("should invalidate cached modules", () => {
- const promise1 = registry.getModule("http://localhost/a.js", "hash1");
- promise1.catch(() => undefined);
- registry.invalidate("hash1");
- const promise2 = registry.getModule("http://localhost/a.js", "hash1");
- promise2.catch(() => undefined);
- expect(promise1).not.toBe(promise2);
- });
-
it("should remove from cache on import failure so retry creates new promise", async () => {
- const promise1 = registry.getModule("http://localhost/a.js", "fail-hash");
+ const promise1 = getModule(registry, "http://localhost/a.js", "fail-hash");
// The URL is rejected by the trusted-URL validator.
await expect(promise1).rejects.toThrow();
// After failure, cache should be cleared, so next call creates a new promise
- const promise2 = registry.getModule("http://localhost/a.js", "fail-hash");
+ const promise2 = getModule(registry, "http://localhost/a.js", "fail-hash");
expect(promise1).not.toBe(promise2);
promise2.catch(() => undefined);
});
@@ -106,7 +124,7 @@ describe("WidgetDefRegistry", () => {
"./@file/x.js?redirect=http://evil.com",
"",
])("rejects untrusted URL: %s", async (url) => {
- await expect(registry.getModule(url, `hash-${url}`)).rejects.toThrow(
+ await expect(getModule(registry, url, `hash-${url}`)).rejects.toThrow(
/untrusted/i,
);
});
@@ -116,179 +134,333 @@ describe("WidgetDefRegistry", () => {
// is a Node test environment with no server. We only assert that
// the rejection reason is NOT the "untrusted URL" refusal.
await expect(
- registry.getModule("./@file/123-widget.js", "trusted-hash"),
+ getModule(registry, "./@file/123-widget.js", "trusted-hash"),
).rejects.not.toThrow(/untrusted/i);
});
});
});
describe("WidgetBinding", () => {
- let binding: InstanceType<typeof WidgetBinding>;
- let model: Model<ModelState>;
-
- beforeEach(() => {
- binding = new WidgetBinding();
- model = new Model<ModelState>({ count: 0 }, createMockComm());
- });
-
- it("should initialize once and return a render function", async () => {
- const initCleanup = vi.fn();
- const renderCleanup = vi.fn();
+ it("should run initialize exactly once and expose exports", async () => {
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
+ const exports = { setValue: vi.fn() };
const widgetDef = {
- initialize: vi.fn().mockResolvedValue(initCleanup),
- render: vi.fn().mockResolvedValue(renderCleanup),
+ initialize: vi.fn().mockResolvedValue(exports),
+ render: vi.fn(),
};
- const renderFn = await binding.bind(widgetDef, model);
+ const binding = await createBinding(widgetDef, model);
expect(widgetDef.initialize).toHaveBeenCalledTimes(1);
- expect(typeof renderFn).toBe("function");
+ expect(binding.exports).toBe(exports);
- // Render into an element
- const el = document.createElement("div");
const controller = new AbortController();
- await renderFn(el, controller.signal);
- expect(widgetDef.render).toHaveBeenCalledTimes(1);
+ await binding.createView(
+ { el: document.createElement("div") },
+ { signal: controller.signal },
+ );
+ await binding.createView(
+ { el: document.createElement("div") },
+ { signal: controller.signal },
+ );
+ expect(widgetDef.initialize).toHaveBeenCalledTimes(1);
+ expect(widgetDef.render).toHaveBeenCalledTimes(2);
});
- it("should return cached render for same widget def", async () => {
- const widgetDef = {
- initialize: vi.fn(),
- render: vi.fn(),
- };
+ it("should handle widget def as a factory function", async () => {
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
+ const render = vi.fn();
+ const factory = vi.fn().mockResolvedValue({ render });
- const render1 = await binding.bind(widgetDef, model);
- const render2 = await binding.bind(widgetDef, model);
- expect(render1).toBe(render2);
- // Initialize should only be called once
- expect(widgetDef.initialize).toHaveBeenCalledTimes(1);
+ const binding = await createBinding(factory, model);
+ const controller = new AbortController();
+ await binding.createView(
+ { el: document.createElement("div") },
+ { signal: controller.signal },
+ );
+ expect(factory).toHaveBeenCalledTimes(1);
+ expect(render).toHaveBeenCalledTimes(1);
});
- it("should re-initialize on hot reload (different widget def)", async () => {
- const cleanup1 = vi.fn();
- const widgetDef1 = {
- initialize: vi.fn().mockResolvedValue(cleanup1),
- render: vi.fn(),
- };
+ it("should handle a widget with no initialize or render", async () => {
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
+ const binding = await createBinding({}, model);
+ expect(binding.exports).toBeUndefined();
+ const controller = new AbortController();
+ // No render — createView is a no-op, not an error.
+ await binding.createView(
+ { el: document.createElement("div") },
+ { signal: controller.signal },
+ );
+ });
+
+ it("should expose undefined exports for void initialize", async () => {
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
+ const binding = await createBinding(
+ { initialize: vi.fn(), render: vi.fn() },
+ model,
+ );
+ expect(binding.exports).toBeUndefined();
+ });
+
+ it("should run a legacy initialize cleanup on destroy", async () => {
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
+ const initCleanup = vi.fn();
+ const binding = await createBinding(
+ { initialize: vi.fn().mockResolvedValue(initCleanup), render: vi.fn() },
+ model,
+ );
+ expect(binding.exports).toBeUndefined();
+ expect(initCleanup).not.toHaveBeenCalled();
+ binding.destroy();
+ expect(initCleanup).toHaveBeenCalledTimes(1);
+ });
- const widgetDef2 = {
- initialize: vi.fn(),
+ it("should reject and run cleanup when aborted mid-initialize", async () => {
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
+ const initCleanup = vi.fn();
+ let resolveInit!: (v: unknown) => void;
+ const widgetDef = {
+ initialize: vi.fn().mockReturnValue(
+ new Promise((r) => {
+ resolveInit = r;
+ }),
+ ),
render: vi.fn(),
};
- const render1 = await binding.bind(widgetDef1, model);
- const render2 = await binding.bind(widgetDef2, model);
+ const controller = new AbortController();
+ const pending = createBinding(widgetDef, model, { controller });
+ pending.catch(() => undefined);
+
+ controller.abort();
+ resolveInit(initCleanup);
+
+ await expect(pending).rejects.toThrow(/binding destroyed/);
+ expect(initCleanup).toHaveBeenCalledTimes(1);
+ });
+
+ it("should pass an AbortSignal to initialize that aborts on destroy", async () => {
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
+ const widgetDef = { initialize: vi.fn(), render: vi.fn() };
+ const binding = await createBinding(widgetDef, model);
- expect(render1).not.toBe(render2);
- expect(cleanup1).toHaveBeenCalledTimes(1); // Old binding cleaned up
- expect(widgetDef2.initialize).toHaveBeenCalledTimes(1);
+ const initSignal = widgetDef.initialize.mock.calls[0][0]
+ .signal as AbortSignal;
+ expect(initSignal.aborted).toBe(false);
+ binding.destroy();
+ expect(initSignal.aborted).toBe(true);
});
- it("should cleanup render on view signal abort", async () => {
+ it("should abort a view when its own signal aborts", async () => {
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
const renderCleanup = vi.fn();
const widgetDef = {
- initialize: vi.fn(),
render: vi.fn().mockResolvedValue(renderCleanup),
};
+ const binding = await createBinding(widgetDef, model);
- const renderFn = await binding.bind(widgetDef, model);
- const el = document.createElement("div");
- const viewController = new AbortController();
- await renderFn(el, viewController.signal);
+ const controller = new AbortController();
+ await binding.createView(
+ { el: document.createElement("div") },
+ { signal: controller.signal },
+ );
+ const renderSignal = widgetDef.render.mock.calls[0][0]
+ .signal as AbortSignal;
+ expect(renderSignal.aborted).toBe(false);
+
+ controller.abort();
+ expect(renderSignal.aborted).toBe(true);
+ expect(renderCleanup).toHaveBeenCalledTimes(1);
+ });
+
+ it("runs a late render cleanup after the view already aborted", async () => {
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
+ const renderCleanup = vi.fn();
+ let resolveRender!: (cleanup: () => void) => void;
+ const widgetDef = {
+ render: vi.fn(
+ () =>
+ new Promise<() => void>((resolve) => {
+ resolveRender = resolve;
+ }),
+ ),
+ };
+ const binding = await createBinding(widgetDef, model);
+ const controller = new AbortController();
+
+ const pending = binding.createView(
+ { el: document.createElement("div") },
+ { signal: controller.signal },
+ );
+ controller.abort();
+ resolveRender(renderCleanup);
- // Aborting the view signal should trigger render cleanup
- viewController.abort();
+ await pending;
expect(renderCleanup).toHaveBeenCalledTimes(1);
});
- it("should cleanup everything on destroy", async () => {
- const initCleanup = vi.fn();
+ it("should abort every view when the binding is destroyed", async () => {
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
const renderCleanup = vi.fn();
const widgetDef = {
- initialize: vi.fn().mockResolvedValue(initCleanup),
render: vi.fn().mockResolvedValue(renderCleanup),
};
+ const binding = await createBinding(widgetDef, model);
- const renderFn = await binding.bind(widgetDef, model);
- const el = document.createElement("div");
- const viewController = new AbortController();
- await renderFn(el, viewController.signal);
+ const controller = new AbortController();
+ await binding.createView(
+ { el: document.createElement("div") },
+ { signal: controller.signal },
+ );
+ const renderSignal = widgetDef.render.mock.calls[0][0]
+ .signal as AbortSignal;
binding.destroy();
- expect(initCleanup).toHaveBeenCalledTimes(1);
+ expect(renderSignal.aborted).toBe(true);
expect(renderCleanup).toHaveBeenCalledTimes(1);
+ // The caller's own signal is untouched — only the combined one.
+ expect(controller.signal.aborted).toBe(false);
});
- it("should handle widget def as a function", async () => {
- const widget = {
- initialize: vi.fn(),
- render: vi.fn(),
+ it("should auto-clear render listeners when the view aborts", async () => {
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
+ const onCount = vi.fn();
+ const widgetDef = {
+ render: vi.fn(({ model }) => {
+ model.on("change:count", onCount);
+ }),
};
- const widgetDefFn = vi.fn().mockResolvedValue(widget);
+ const binding = await createBinding(widgetDef, model);
- await binding.bind(widgetDefFn, model);
- expect(widgetDefFn).toHaveBeenCalledTimes(1);
- expect(widget.initialize).toHaveBeenCalledTimes(1);
+ const controller = new AbortController();
+ await binding.createView(
+ { el: document.createElement("div") },
+ { signal: controller.signal },
+ );
+ // Called once by the hydration replay at mount, once by the set.
+ model.set("count", 1);
+ expect(onCount).toHaveBeenCalledTimes(2);
+
+ controller.abort();
+ model.set("count", 2);
+ expect(onCount).toHaveBeenCalledTimes(2);
});
- it("should handle widget with no initialize or render", async () => {
- const widgetDef = {};
- const renderFn = await binding.bind(widgetDef, model);
- expect(typeof renderFn).toBe("function");
+ it("should auto-clear initialize listeners on destroy", async () => {
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
+ const onCount = vi.fn();
+ const widgetDef = {
+ initialize: vi.fn(({ model }) => {
+ model.on("change:count", onCount);
+ }),
+ render: vi.fn(),
+ };
+ const binding = await createBinding(widgetDef, model);
- // Render should not throw
- const el = document.createElement("div");
- const controller = new AbortController();
- await renderFn(el, controller.signal);
+ model.set("count", 1);
+ expect(onCount).toHaveBeenCalledTimes(1);
+
+ binding.destroy();
+ model.set("count", 2);
+ expect(onCount).toHaveBeenCalledTimes(1);
});
});
-describe("BindingManager", () => {
- let manager: InstanceType<typeof BindingManager>;
+describe("WidgetBinding hydration replay", () => {
+ it("replays current state to render listeners exactly once", async () => {
+ const model = new Model<ModelState>({ count: 8 }, createMockComm());
+ const el = document.createElement("div");
+ const widgetDef = {
+ render: vi.fn(({ model, el }) => {
+ // A widget view that starts with a local default and relies on
+ // change events for hydration.
+ el.textContent = "count is 5";
+ model.on("change:count", () => {
+ el.textContent = `count is ${model.get("count")}`;
+ });
+ }),
+ };
+ const binding = await createBinding(widgetDef, model);
- beforeEach(() => {
- manager = new BindingManager();
+ const controller = new AbortController();
+ await binding.createView({ el }, { signal: controller.signal });
+ expect(el.textContent).toBe("count is 8");
});
- it("should create bindings on demand", () => {
- const modelId = asModelId("model-1");
- expect(manager.has(modelId)).toBe(false);
+ it("does not re-fire listeners of already-mounted views", async () => {
+ // Mounting view B must not double-paint view A: the replay is
+ // scoped to the listeners the new render attached.
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
+ const listeners: Array<ReturnType<typeof vi.fn>> = [];
+ const widgetDef = {
+ render: vi.fn(({ model }) => {
+ const listener = vi.fn();
+ listeners.push(listener);
+ model.on("change:count", listener);
+ }),
+ };
+ const binding = await createBinding(widgetDef, model);
+ const controller = new AbortController();
- const binding = manager.getOrCreate(modelId);
- expect(binding).toBeDefined();
- expect(manager.has(modelId)).toBe(true);
+ await binding.createView(
+ { el: document.createElement("div") },
+ { signal: controller.signal },
+ );
+ expect(listeners[0]).toHaveBeenCalledTimes(1);
+
+ await binding.createView(
+ { el: document.createElement("div") },
+ { signal: controller.signal },
+ );
+ // View B's listener hydrated once; view A's was left alone.
+ expect(listeners[1]).toHaveBeenCalledTimes(1);
+ expect(listeners[0]).toHaveBeenCalledTimes(1);
});
- it("should return the same binding for the same model id", () => {
- const modelId = asModelId("model-1");
- const binding1 = manager.getOrCreate(modelId);
- const binding2 = manager.getOrCreate(modelId);
- expect(binding1).toBe(binding2);
+ it("replays the any-change event to its listeners", async () => {
+ const model = new Model<ModelState>({ count: 1 }, createMockComm());
+ const onAnyChange = vi.fn();
+ const widgetDef = {
+ render: vi.fn(({ model }) => {
+ model.on("change", onAnyChange);
+ }),
+ };
+ const binding = await createBinding(widgetDef, model);
+ const controller = new AbortController();
+ await binding.createView(
+ { el: document.createElement("div") },
+ { signal: controller.signal },
+ );
+ expect(onAnyChange).toHaveBeenCalledTimes(1);
});
- it("should destroy and remove bindings", async () => {
- const modelId = asModelId("model-1");
- const binding = manager.getOrCreate(modelId);
-
- const model = new Model<ModelState>({ count: 0 }, createMockComm());
- const initCleanup = vi.fn();
+ it("does not replay initialize listeners", async () => {
+ // The guarantee is per-view: initialize listeners existed before
+ // any view, and replaying at them would fire once per mount.
+ const model = new Model<ModelState>({ count: 1 }, createMockComm());
+ const initListener = vi.fn();
const widgetDef = {
- initialize: vi.fn().mockResolvedValue(initCleanup),
+ initialize: vi.fn(({ model }) => {
+ model.on("change:count", initListener);
+ }),
render: vi.fn(),
};
- await binding.bind(widgetDef, model);
-
- manager.destroy(modelId);
- expect(manager.has(modelId)).toBe(false);
- expect(initCleanup).toHaveBeenCalledTimes(1);
+ const binding = await createBinding(widgetDef, model);
+ const controller = new AbortController();
+ await binding.createView(
+ { el: document.createElement("div") },
+ { signal: controller.signal },
+ );
+ expect(initListener).not.toHaveBeenCalled();
});
- it("should handle idempotent destroy", () => {
- const modelId = asModelId("model-1");
- manager.getOrCreate(modelId);
-
- // Should not throw
- manager.destroy(modelId);
- manager.destroy(modelId);
- expect(manager.has(modelId)).toBe(false);
+ it("clears the element before rendering into it", async () => {
+ const model = new Model<ModelState>({ count: 0 }, createMockComm());
+ const el = document.createElement("div");
+ el.innerHTML = "<span>stale content</span>";
+ const binding = await createBinding({ render: vi.fn() }, model);
+ const controller = new AbortController();
+ await binding.createView({ el }, { signal: controller.signal });
+ expect(el.innerHTML).toBe("");
});
});
diff --git a/frontend/src/plugins/impl/anywidget/__tests__/widget-ref.test.ts b/frontend/src/plugins/impl/anywidget/__tests__/widget-ref.test.ts
new file mode 100644
index 0000000000..31474f9a18
--- /dev/null
+++ b/frontend/src/plugins/impl/anywidget/__tests__/widget-ref.test.ts
@@ -0,0 +1,28 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import { describe, expect, it } from "vitest";
+import { parseWidgetRef, WIDGET_REF_PREFIX } from "../widget-ref";
+
+describe("parseWidgetRef", () => {
+ it("parses an anywidget: ref", () => {
+ expect(parseWidgetRef(`${WIDGET_REF_PREFIX}abc-123`)).toBe("abc-123");
+ });
+
+ it("rejects the legacy IPY_MODEL_ prefix", () => {
+ expect(() => parseWidgetRef("IPY_MODEL_abc-123")).toThrow(/Invalid/);
+ });
+
+ it("rejects a bare model id", () => {
+ expect(() => parseWidgetRef("abc-123")).toThrow(/Invalid/);
+ });
+
+ it("rejects an empty model id", () => {
+ expect(() => parseWidgetRef(WIDGET_REF_PREFIX)).toThrow(/Invalid/);
+ });
+
+ it("rejects non-string inputs", () => {
+ expect(() => parseWidgetRef(undefined)).toThrow(/Invalid/);
+ expect(() => parseWidgetRef(null)).toThrow(/Invalid/);
+ expect(() => parseWidgetRef(42)).toThrow(/Invalid/);
+ expect(() => parseWidgetRef({ model_id: "abc" })).toThrow(/Invalid/);
+ });
+});
diff --git a/frontend/src/plugins/impl/anywidget/host.ts b/frontend/src/plugins/impl/anywidget/host.ts
new file mode 100644
index 0000000000..8d186d79ce
--- /dev/null
+++ b/frontend/src/plugins/impl/anywidget/host.ts
@@ -0,0 +1,54 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import type { AnyModel, Host, ResolvedWidget } from "@anywidget/types";
+import { modelProxy } from "./model-proxy";
+import type { Model } from "./model";
+import type { ModelState } from "./types";
+import type { WidgetModelId } from "./types";
+import { parseWidgetRef } from "./widget-ref";
+
+export type { Host, ResolvedWidget };
+
+export interface WidgetResolver {
+ getModel(key: WidgetModelId): Promise<Model<ModelState>>;
+ getWidget<T = unknown>(key: WidgetModelId): Promise<ResolvedWidget<T>>;
+}
+
+/**
+ * Build a `Host` scoped to a parent view's lifetime.
+ *
+ * The supplied `parentSignal` is used as the default for child renders
+ * that don't pass their own `signal` — so a child mounted via
+ * `host.getWidget(ref).render({ el })` is automatically torn down when
+ * the parent view tears down. Listeners that the child registers on its
+ * own model via `model.on(...)` are scoped to the same signal through
+ * `modelProxy`.
+ */
+export function createHost(
+ resolver: WidgetResolver,
+ parentSignal: AbortSignal,
+): Host {
+ return {
+ async getModel<T extends Record<string, unknown> = Record<string, unknown>>(
+ ref: string,
+ ): Promise<AnyModel<T>> {
+ const modelId = parseWidgetRef(ref);
+ const model = await resolver.getModel(modelId);
+ // Wrap in a proxy so listeners the parent registers on the child's
+ // model are auto-cleared when the parent's view tears down.
+ // The generic T is structural — modelProxy returns the underlying
+ // AnyModel shape regardless of T, which the caller narrows.
+ return modelProxy(model, parentSignal) as unknown as AnyModel<T>;
+ },
+ async getWidget<T = unknown>(ref: string): Promise<ResolvedWidget<T>> {
+ const modelId = parseWidgetRef(ref);
+ const widget = await resolver.getWidget<T>(modelId);
+ return {
+ exports: widget.exports,
+ async render({ el, signal }) {
+ await widget.render({ el, signal: signal ?? parentSignal });
+ },
+ };
+ },
+ };
+}
diff --git a/frontend/src/plugins/impl/anywidget/model-proxy.ts b/frontend/src/plugins/impl/anywidget/model-proxy.ts
new file mode 100644
index 0000000000..e80999f8a4
--- /dev/null
+++ b/frontend/src/plugins/impl/anywidget/model-proxy.ts
@@ -0,0 +1,70 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import type { AnyModel } from "@anywidget/types";
+import type { ModelState } from "./types";
+
+type ModelEventCallback = Parameters<AnyModel<ModelState>["on"]>[1];
+
+/**
+ * A listener registered through a model proxy (see the hydration
+ * replay in `WidgetBinding.createView`).
+ */
+export interface ProxyRegistration {
+ event: string;
+ callback: ModelEventCallback;
+}
+
+/**
+ * Wrap a model so every `on()` call from inside `initialize` or `render`
+ * is auto-tied to a lifetime `AbortSignal`. When the signal aborts,
+ * every listener registered through the proxy is removed.
+ *
+ * Without this, a parent widget that re-renders a child via
+ * `host.getWidget().render` would accumulate listeners on the child's
+ * model on every re-render — the widget author would have to know to
+ * pass `signal` to each `on()` call themselves.
+ *
+ * The proxy is purely a host-side ergonomic helper. The widget author
+ * still writes `model.on("change:foo", handler)` exactly as before; the
+ * cleanup signal is supplied transparently.
+ *
+ * `onRegister`, when given, observes each `on()` registration.
+ */
+// oxlint-disable-next-line marimo/prefer-object-params -- concise internal helper used at protocol call sites
+export function modelProxy<T extends ModelState>(
+ model: AnyModel<T>,
+ signal: AbortSignal,
+ onRegister?: (registration: ProxyRegistration) => void,
+): AnyModel<T> {
+ return {
+ get(key) {
+ return model.get(key);
+ },
+ set(key, value) {
+ model.set(key, value);
+ },
+ save_changes() {
+ model.save_changes();
+ },
+ send: model.send.bind(model),
+ on(name: string, callback: ModelEventCallback): void {
+ if (signal.aborted) {
+ return;
+ }
+ model.on(name, callback);
+ signal.addEventListener("abort", () => model.off(name, callback), {
+ once: true,
+ });
+ onRegister?.({ event: name, callback });
+ },
+ off(name?: string | null, callback?: ModelEventCallback | null): void {
+ model.off(name ?? null, callback ?? null);
+ },
+ widget_manager: {
+ async get_model<TT extends ModelState>(modelId: string) {
+ const child = await model.widget_manager.get_model<TT>(modelId);
+ return modelProxy(child, signal);
+ },
+ },
+ };
+}
diff --git a/frontend/src/plugins/impl/anywidget/model.ts b/frontend/src/plugins/impl/anywidget/model.ts
index a3150d8b35..629f9df82e 100644
--- a/frontend/src/plugins/impl/anywidget/model.ts
+++ b/frontend/src/plugins/impl/anywidget/model.ts
@@ -3,104 +3,24 @@
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,
-} from "@/plugins/impl/anywidget/serialization";
-import { assertNever } from "@/utils/assertNever";
-import { Deferred } from "@/utils/Deferred";
-import {
- type Base64String,
- base64ToDataView,
- dataViewToBase64,
-} from "@/utils/json/base64";
import { Logger } from "@/utils/Logger";
-import { repl } from "@/utils/repl";
-import type { AnyWidgetMessage } from "./schemas";
import type { EventHandler, ModelState, WidgetModelId } from "./types";
-import { BINDING_MANAGER } from "./widget-binding";
-interface ModelEntry {
- deferred: Deferred<Model<ModelState>>;
- controller: AbortController;
-}
-
-class ModelManager {
- #entries = new Map<WidgetModelId, ModelEntry>();
- #timeout: number;
-
- constructor(timeout = 10_000) {
- this.#timeout = timeout;
- }
-
- #getOrCreateEntry(key: WidgetModelId): ModelEntry {
- let entry = this.#entries.get(key);
- if (!entry) {
- entry = {
- deferred: new Deferred<Model<ModelState>>(),
- controller: new AbortController(),
- };
- this.#entries.set(key, entry);
- }
- return entry;
- }
-
- get(key: WidgetModelId): Promise<Model<any>> {
- const entry = this.#getOrCreateEntry(key);
- if (entry.deferred.status === "pending") {
- // Add timeout to prevent hanging
- setTimeout(() => {
- if (entry.deferred.status !== "pending") {
- return;
- }
- entry.deferred.reject(new Error(`Model not found for key: ${key}`));
- this.#entries.delete(key);
- }, this.#timeout);
- }
- return entry.deferred.promise;
- }
-
- /**
- * Create a model with a managed lifecycle signal.
- * The signal is aborted when the model is deleted.
- */
- create(
- key: WidgetModelId,
- factory: (signal: AbortSignal) => Model<ModelState>,
- ): void {
- const entry = this.#getOrCreateEntry(key);
- entry.deferred.resolve(factory(entry.controller.signal));
- }
-
- set(key: WidgetModelId, model: Model<any>): void {
- this.#getOrCreateEntry(key).deferred.resolve(model);
- }
-
- /**
- * Get a model synchronously if it exists and has been resolved.
- * Returns undefined if the model doesn't exist or is still pending.
- */
- getSync(key: WidgetModelId): Model<any> | undefined {
- const entry = this.#entries.get(key);
- if (entry && entry.deferred.status === "resolved") {
- return entry.deferred.value;
- }
- return undefined;
- }
-
- delete(key: WidgetModelId): void {
- Logger.debug(
- `[ModelManager] Deleting model=${key}, aborting lifecycle signal`,
- );
- this.#entries.get(key)?.controller.abort();
- this.#entries.delete(key);
- }
+/**
+ * The custom-message shape delivered to `msg:custom` listeners — the
+ * only message shape the frontend re-declares; the wire contract is
+ * the generated `model-lifecycle` type.
+ */
+export interface CustomMessage {
+ method: "custom";
+ // oxlint-disable-next-line typescript/no-explicit-any
+ content: any;
}
-interface MarimoComm<T> {
+/**
+ * The model's channel back to the kernel; a no-op in static exports.
+ */
+export interface MarimoComm<T> {
sendUpdate: (value: Partial<T>) => Promise<void>;
sendCustomMessage: (content: unknown, buffers: DataView[]) => Promise<void>;
}
@@ -112,15 +32,11 @@ interface MarimoInternalApi<T extends ModelState> {
* Update model state and emit change events for any differences.
*/
updateAndEmitDiffs: (value: T) => void;
- /**
- * Re-emit current state as change events.
- */
- reemitState: () => void;
/**
* Emit a custom message to listeners.
*/
emitCustomMessage: (
- message: Extract<AnyWidgetMessage, { method: "custom" }>,
+ message: CustomMessage,
buffers?: readonly DataView[],
) => void;
}
@@ -135,8 +51,6 @@ export function getMarimoInternal<T extends ModelState>(
return model[marimoSymbol];
}
-export const MODEL_MANAGER = new ModelManager();
-
export class Model<T extends ModelState> implements AnyModel<T> {
#ANY_CHANGE_EVENT = "change";
#dirtyFields: Map<keyof T, unknown>;
@@ -144,7 +58,14 @@ export class Model<T extends ModelState> implements AnyModel<T> {
#comm: MarimoComm<T>;
#listeners: Record<string, Set<EventHandler> | undefined> = {};
- static _modelManager: ModelManager = MODEL_MANAGER;
+ /**
+ * Resolves models for the legacy ipywidgets escape hatch
+ * (`widget_manager.get_model`). Assigned by the registry module at
+ * import time to avoid an import cycle.
+ */
+ static _modelManager: {
+ getModel(model_id: WidgetModelId): Promise<Model<any>>;
+ };
constructor(data: T, comm: MarimoComm<T>, signal?: AbortSignal) {
this.#data = data;
@@ -164,9 +85,8 @@ export class Model<T extends ModelState> implements AnyModel<T> {
*/
[marimoSymbol]: MarimoInternalApi<T> = {
updateAndEmitDiffs: (value: T) => this.#updateAndEmitDiffs(value),
- reemitState: () => this.#reemitState(),
emitCustomMessage: (
- message: Extract<AnyWidgetMessage, { method: "custom" }>,
+ message: CustomMessage,
buffers?: readonly DataView[],
) => this.#emitCustomMessage(message, buffers),
};
@@ -204,7 +124,7 @@ export class Model<T extends ModelState> implements AnyModel<T> {
async get_model<TT extends ModelState>(
model_id: WidgetModelId,
): Promise<AnyModel<TT>> {
- const model = await Model._modelManager.get(model_id);
+ const model = await Model._modelManager.getModel(model_id);
if (!model) {
throw new Error(
`Model not found with id: ${model_id}. This is likely because the model was not registered.`,
@@ -239,19 +159,43 @@ export class Model<T extends ModelState> implements AnyModel<T> {
this.#comm.sendUpdate(partialData);
}
- on(eventName: string, callback: EventHandler): void {
+ /**
+ * Register an event listener.
+ *
+ * Passing `signal` ties the listener's lifetime to an `AbortSignal` —
+ * when the signal aborts, the listener is auto-removed. This is the
+ * preferred cleanup mechanism (matches the web platform pattern of
+ * `addEventListener({ signal })`) and is what `modelProxy` uses to
+ * scope listeners to view / binding lifetimes.
+ */
+ on(
+ eventName: string,
+ callback: EventHandler,
+ options?: { signal?: AbortSignal },
+ ): void {
+ const signal = options?.signal;
+ if (signal?.aborted) {
+ return;
+ }
if (!this.#listeners[eventName]) {
this.#listeners[eventName] = new Set();
}
this.#listeners[eventName].add(callback);
+ signal?.addEventListener("abort", () => this.off(eventName, callback), {
+ once: true,
+ });
}
#emit<K extends keyof T>(event: `change:${K & string}`, value: T[K]) {
- if (!this.#listeners[event]) {
+ const listeners = this.#listeners[event];
+ if (!listeners) {
return;
}
- const listeners = this.#listeners[event];
- for (const listener of listeners) {
+ // Snapshot before iterating: a callback may unregister itself
+ // (typical signal-based abort handler calling `model.off`), and a
+ // Set mutated mid-iteration drops the very next element.
+ // oxlint-disable-next-line no-useless-spread -- snapshot is intentional
+ for (const listener of [...listeners]) {
try {
listener(value);
} catch (error) {
@@ -274,29 +218,21 @@ export class Model<T extends ModelState> implements AnyModel<T> {
});
}
- #reemitState() {
- for (const [key, value] of Object.entries(this.#data) as [
- keyof T & string,
- T[keyof T],
- ][]) {
- this.#emit(`change:${key}`, value);
- }
- this.#emitAnyChange();
- }
-
/**
* When receiving a message from the backend.
* We want to notify all listeners with `msg:custom`
*/
#emitCustomMessage(
- message: Extract<AnyWidgetMessage, { method: "custom" }>,
+ message: CustomMessage,
buffers: readonly DataView[] = [],
) {
const listeners = this.#listeners["msg:custom"];
if (!listeners) {
return;
}
- for (const listener of listeners) {
+ // Snapshot before iterating: see `#emit` for rationale.
+ // oxlint-disable-next-line no-useless-spread -- snapshot is intentional
+ for (const listener of [...listeners]) {
try {
listener(message.content, buffers);
} catch (error) {
@@ -311,7 +247,9 @@ export class Model<T extends ModelState> implements AnyModel<T> {
if (!listeners) {
return;
}
- for (const listener of listeners) {
+ // Snapshot before iterating: see `#emit` for rationale.
+ // oxlint-disable-next-line no-useless-spread -- snapshot is intentional
+ for (const listener of [...listeners]) {
try {
listener();
} catch (error) {
@@ -320,121 +258,3 @@ export class Model<T extends ModelState> implements AnyModel<T> {
}
}, 0);
}
-
-/**
- * Handle an incoming model lifecycle notification from the backend.
- *
- * Messages are dispatched by method type:
- * - "open": Initialize a new model or update existing one with initial state
- * - "update": Update model state with new values
- * - "custom": Forward custom message to model listeners
- * - "close": Remove model from manager
- */
-export async function handleWidgetMessage(
- modelManager: ModelManager,
- notification: NotificationMessageData<"model-lifecycle">,
-): Promise<void> {
- const modelId = notification.model_id as WidgetModelId;
- const msg = notification.message;
-
- // Decode base64 buffers to DataViews (present in open/update/custom messages)
- const base64Buffers: Base64String[] = "buffers" in msg ? msg.buffers : [];
- const buffers = base64Buffers.map(base64ToDataView);
-
- switch (msg.method) {
- case "open": {
- const { state, buffer_paths = [] } = msg;
- const stateWithBuffers = decodeFromWire({
- state,
- bufferPaths: buffer_paths,
- buffers,
- });
-
- // Check if a model already exists (created by the plugin using model_id reference)
- // If so, just update its state instead of creating a duplicate
- const existingModel = modelManager.getSync(modelId);
- if (existingModel) {
- getMarimoInternal(existingModel).updateAndEmitDiffs(stateWithBuffers);
- return;
- }
-
- 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(
- `[Model] sendUpdate suppressed for model=${modelId} (signal aborted)`,
- );
- return;
- }
- const { state, buffers, bufferPaths } =
- serializeBuffersToBase64(changeData);
- await getRequestClient().sendModelValue({
- modelId,
- message: { method: "update", state, bufferPaths },
- buffers,
- });
- },
- async sendCustomMessage(content, buffers) {
- if (signal.aborted) {
- Logger.debug(
- `[Model] sendCustomMessage suppressed for model=${modelId} (signal aborted)`,
- );
- return;
- }
- await getRequestClient().sendModelValue({
- modelId,
- message: { method: "custom", content },
- buffers: buffers.map(dataViewToBase64),
- });
- },
- };
-
- return new Model(stateWithBuffers, comm, signal);
- });
- return;
- }
-
- case "custom": {
- const model = await modelManager.get(modelId);
- // For custom messages, we need to reconstruct the AnyWidgetMessage format
- getMarimoInternal(model).emitCustomMessage(
- { method: "custom", content: msg.content },
- buffers,
- );
- return;
- }
-
- case "close":
- BINDING_MANAGER.destroy(modelId);
- modelManager.delete(modelId); // aborts the model's signal, clearing listeners
- return;
-
- case "update": {
- const { state, buffer_paths = [] } = msg;
- const stateWithBuffers = decodeFromWire({
- state,
- bufferPaths: buffer_paths,
- buffers,
- });
- const model = await modelManager.get(modelId);
- getMarimoInternal(model).updateAndEmitDiffs(stateWithBuffers);
- return;
- }
-
- default:
- assertNever(msg);
- }
-}
-
-repl(MODEL_MANAGER, "MODEL_MANAGER");
-
-export const visibleForTesting = {
- ModelManager,
-};
diff --git a/frontend/src/plugins/impl/anywidget/registry.ts b/frontend/src/plugins/impl/anywidget/registry.ts
new file mode 100644
index 0000000000..041ae03ea2
--- /dev/null
+++ b/frontend/src/plugins/impl/anywidget/registry.ts
@@ -0,0 +1,268 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import type { NotificationMessageData } from "@/core/kernel/messages";
+import { getRequestClient } from "@/core/network/requests";
+import { isStaticNotebook } from "@/core/static/static-state";
+import { assertNever } from "@/utils/assertNever";
+import {
+ type Base64String,
+ base64ToDataView,
+ dataViewToBase64,
+} from "@/utils/json/base64";
+import { Logger } from "@/utils/Logger";
+import { repl } from "@/utils/repl";
+import { viewStateAtom } from "@/core/mode";
+import { store } from "@/core/state/jotai";
+import { createHost, type WidgetResolver } from "./host";
+import { getMarimoInternal, type MarimoComm, Model } from "./model";
+import { WidgetRuntime } from "./runtime";
+import { decodeFromWire, serializeBuffersToBase64 } from "./serialization";
+import {
+ isWidgetModelId,
+ type EsmSpec,
+ type ModelState,
+ type WidgetModelId,
+} from "./types";
+
+/**
+ * Only edit sessions may swap widget code ("present" is an edit
+ * session with different chrome); a viewer's widget code is immutable.
+ */
+function defaultIsEditMode(): boolean {
+ const mode = store.get(viewStateAtom).mode;
+ return mode === "edit" || mode === "present";
+}
+
+/**
+ * Maps model ids to stable runtimes and routes callers through their
+ * public behavior. Generation and view lifecycles stay inside each runtime.
+ */
+export class WidgetRegistry implements WidgetResolver {
+ #runtimes = new Map<WidgetModelId, WidgetRuntime>();
+ #timeout: number;
+ #isEditMode: () => boolean;
+
+ constructor(timeout = 10_000, isEditMode: () => boolean = defaultIsEditMode) {
+ this.#timeout = timeout;
+ this.#isEditMode = isEditMode;
+ }
+
+ #getOrCreateRuntime(key: WidgetModelId): WidgetRuntime {
+ let runtime = this.#runtimes.get(key);
+ if (!runtime) {
+ const nextRuntime = new WidgetRuntime(key, {
+ timeout: this.#timeout,
+ isEditMode: this.#isEditMode,
+ createHost: (signal) => createHost(this, signal),
+ onModelTimeout: () => {
+ if (this.#runtimes.get(key) === nextRuntime) {
+ nextRuntime.dispose();
+ this.#runtimes.delete(key);
+ }
+ },
+ });
+ runtime = nextRuntime;
+ this.#runtimes.set(key, runtime);
+ }
+ return runtime;
+ }
+
+ /**
+ * Resolve the model for `key`, waiting for its `open` message if it
+ * hasn't arrived yet. Rejects after the registry timeout so a ref to
+ * a model that never opens fails loudly instead of hanging.
+ */
+ getModel(key: WidgetModelId): Promise<Model<ModelState>> {
+ return this.#getOrCreateRuntime(key).getModel();
+ }
+
+ /**
+ * Get a model synchronously if it exists and has been resolved.
+ * Returns undefined if the model doesn't exist or is still pending.
+ */
+ getModelSync(key: WidgetModelId): Model<ModelState> | undefined {
+ return this.#runtimes.get(key)?.getModelSync();
+ }
+
+ /**
+ * Create a model with a managed lifecycle signal.
+ * The signal is aborted when the entry is deleted.
+ */
+ createModel(
+ key: WidgetModelId,
+ factory: (signal: AbortSignal) => Model<ModelState>,
+ ): void {
+ this.#getOrCreateRuntime(key).createModel(factory);
+ }
+
+ setModel(key: WidgetModelId, model: Model<ModelState>): void {
+ this.#getOrCreateRuntime(key).setModel(model);
+ }
+
+ /**
+ * Record where this widget's code can be imported from and, in an
+ * edit session, hot-swap a live generation whose code changed.
+ *
+ * Specs only come from kernel-authored notifications; model state
+ * must never be treated as code (it is client-writable).
+ */
+ setSpec(key: WidgetModelId, spec: EsmSpec): void {
+ this.#getOrCreateRuntime(key).setSpec(spec);
+ }
+
+ getWidget<T = unknown>(key: WidgetModelId) {
+ return this.#getOrCreateRuntime(key).getWidget<T>();
+ }
+
+ createView(options: {
+ modelId: WidgetModelId;
+ el: HTMLElement;
+ signal: AbortSignal;
+ }): Promise<void> {
+ return this.#getOrCreateRuntime(options.modelId).createView(options);
+ }
+
+ /**
+ * Tear down everything known about `key`: the model's lifecycle
+ * signal and the current generation.
+ */
+ delete(key: WidgetModelId): void {
+ const runtime = this.#runtimes.get(key);
+ if (!runtime) {
+ return;
+ }
+ runtime.dispose();
+ this.#runtimes.delete(key);
+ }
+}
+
+export const WIDGET_REGISTRY = new WidgetRegistry();
+
+// The legacy ipywidgets escape hatch (`model.widget_manager.get_model`)
+// resolves through the registry; assigned here to keep Model free of
+// registry knowledge.
+Model._modelManager = WIDGET_REGISTRY;
+
+/**
+ * Handle an incoming model lifecycle notification from the backend.
+ *
+ * Messages are dispatched by method type:
+ * - "open": Initialize a new model or update existing one with initial state
+ * - "update": Update model state with new values
+ * - "custom": Forward custom message to model listeners
+ * - "close": Remove the model and its binding from the registry
+ */
+export async function handleWidgetMessage(
+ registry: WidgetRegistry,
+ notification: NotificationMessageData<"model-lifecycle">,
+): Promise<void> {
+ const modelId = notification.model_id;
+ if (!isWidgetModelId(modelId)) {
+ throw new Error(`[anywidget] Invalid model id: ${String(modelId)}`);
+ }
+ const msg = notification.message;
+
+ // Decode base64 buffers to DataViews (present in open/update/custom messages)
+ const base64Buffers: Base64String[] = "buffers" in msg ? msg.buffers : [];
+ const buffers = base64Buffers.map(base64ToDataView);
+
+ switch (msg.method) {
+ case "open": {
+ const { state, buffer_paths = [] } = msg;
+ // Record the spec before resolving the model so a waiting
+ // getWidget sees it.
+ if (msg.esm_spec) {
+ registry.setSpec(modelId, msg.esm_spec);
+ }
+ const stateWithBuffers = decodeFromWire({
+ state,
+ bufferPaths: buffer_paths,
+ buffers,
+ });
+
+ // Check if a model already exists (created by the plugin using model_id reference)
+ // If so, just update its state instead of creating a duplicate
+ const existingModel = registry.getModelSync(modelId);
+ if (existingModel) {
+ getMarimoInternal(existingModel).updateAndEmitDiffs(stateWithBuffers);
+ return;
+ }
+
+ registry.createModel(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(
+ `[Model] sendUpdate suppressed for model=${modelId} (signal aborted)`,
+ );
+ return;
+ }
+ const { state, buffers, bufferPaths } =
+ serializeBuffersToBase64(changeData);
+ await getRequestClient().sendModelValue({
+ modelId,
+ message: { method: "update", state, bufferPaths },
+ buffers,
+ });
+ },
+ async sendCustomMessage(content, buffers) {
+ if (signal.aborted) {
+ Logger.debug(
+ `[Model] sendCustomMessage suppressed for model=${modelId} (signal aborted)`,
+ );
+ return;
+ }
+ await getRequestClient().sendModelValue({
+ modelId,
+ message: { method: "custom", content },
+ buffers: buffers.map(dataViewToBase64),
+ });
+ },
+ };
+
+ return new Model(stateWithBuffers, comm, signal);
+ });
+ return;
+ }
+
+ case "custom": {
+ const model = await registry.getModel(modelId);
+ // For custom messages, we need to reconstruct the custom-message shape
+ getMarimoInternal(model).emitCustomMessage(
+ { method: "custom", content: msg.content },
+ buffers,
+ );
+ return;
+ }
+
+ case "close":
+ registry.delete(modelId); // aborts the model's signal, destroys the binding
+ return;
+
+ case "update": {
+ const { state, buffer_paths = [] } = msg;
+ // A spec on an update is a hot reload (handled by setSpec).
+ if (msg.esm_spec) {
+ registry.setSpec(modelId, msg.esm_spec);
+ }
+ const stateWithBuffers = decodeFromWire({
+ state,
+ bufferPaths: buffer_paths,
+ buffers,
+ });
+ const model = await registry.getModel(modelId);
+ getMarimoInternal(model).updateAndEmitDiffs(stateWithBuffers);
+ return;
+ }
+
+ default:
+ assertNever(msg);
+ }
+}
+
+repl(WIDGET_REGISTRY, "WIDGET_REGISTRY");
diff --git a/frontend/src/plugins/impl/anywidget/resolve-widget.ts b/frontend/src/plugins/impl/anywidget/resolve-widget.ts
new file mode 100644
index 0000000000..3f13fdc430
--- /dev/null
+++ b/frontend/src/plugins/impl/anywidget/resolve-widget.ts
@@ -0,0 +1,138 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import type { AnyWidget, Initialize, Render } from "@anywidget/types";
+import { Logger } from "@/utils/Logger";
+import { hasFunctionProperty, isRecord } from "@/utils/records";
+
+function isRenderHook(value: unknown): value is Render {
+ return typeof value === "function";
+}
+
+function isInitializeHook(value: unknown): value is Initialize {
+ return typeof value === "function";
+}
+
+function isWidgetDefinition(
+ value: unknown,
+): value is { render?: Render; initialize?: Initialize } {
+ return (
+ isRecord(value) &&
+ (isRenderHook(value.render) || isInitializeHook(value.initialize))
+ );
+}
+
+function isAnyWidget(value: unknown): value is AnyWidget {
+ return typeof value === "function" || isWidgetDefinition(value);
+}
+
+export function isAnyWidgetModule(mod: unknown): mod is { default: AnyWidget } {
+ return isRecord(mod) && isAnyWidget(mod.default);
+}
+
+const warnedLegacyNamedExportUrls = new Set<string>();
+// Cache the synthesized widget per module namespace so its identity stays
+// stable across re-renders (like a default export), avoiding needless
+// WidgetBinding re-initialization.
+const legacyWidgetCache = new WeakMap<object, AnyWidget>();
+
+/**
+ * Resolve the AnyWidget from a loaded module: prefer the AFM-spec default
+ * export, otherwise synthesize one from legacy named `render`/`initialize`
+ * exports. Returns null if neither is present.
+ */
+export function resolveAnyWidget(
+ mod: unknown,
+ jsUrl: string,
+): AnyWidget | null {
+ if (isAnyWidgetModule(mod)) {
+ return mod.default;
+ }
+
+ if (!isRecord(mod)) {
+ return null;
+ }
+
+ // Only fall back to legacy (pre-AFM) named exports when there is no default
+ // export at all; a present-but-invalid default should surface an error
+ // rather than be masked.
+ if (mod.default !== undefined) {
+ return null;
+ }
+
+ const render = isRenderHook(mod.render) ? mod.render : undefined;
+ const initialize = isInitializeHook(mod.initialize)
+ ? mod.initialize
+ : undefined;
+ const hasNamedRender = render !== undefined;
+ const hasNamedInitialize = initialize !== undefined;
+ if (!hasNamedRender && !hasNamedInitialize) {
+ return null;
+ }
+
+ const cached = legacyWidgetCache.get(mod);
+ if (cached) {
+ return cached;
+ }
+
+ if (!warnedLegacyNamedExportUrls.has(jsUrl)) {
+ warnedLegacyNamedExportUrls.add(jsUrl);
+ Logger.warn(
+ `Anywidget module at ${jsUrl} uses deprecated top-level named ` +
+ "exports (`render`/`initialize`). Per the AFM spec, use a default " +
+ "export instead: `export default { render }`. " +
+ "See https://anywidget.dev/en/afm/",
+ );
+ }
+
+ const widget: AnyWidget = { render, initialize };
+ legacyWidgetCache.set(mod, widget);
+ return widget;
+}
+
+export function getInvalidAnyWidgetModuleError(
+ mod: unknown,
+ jsUrl: string,
+): Error {
+ const afmDocs = "https://anywidget.dev/en/afm/";
+ const hasNamedRender = isRecord(mod) && hasFunctionProperty(mod, "render");
+ const hasNamedInitialize =
+ isRecord(mod) && hasFunctionProperty(mod, "initialize");
+
+ if (isRecord(mod) && mod.default !== undefined) {
+ return new Error(
+ `Anywidget module at ${jsUrl} has an invalid default export. ` +
+ "Expected a factory function or an object with `render` or `initialize`. " +
+ `See ${afmDocs}`,
+ );
+ }
+
+ if (hasNamedRender || hasNamedInitialize) {
+ const namedExports = [
+ hasNamedRender ? "`render`" : null,
+ hasNamedInitialize ? "`initialize`" : null,
+ ]
+ .filter(Boolean)
+ .join(" and ");
+ const lifecycleHooks = [
+ hasNamedRender ? "render" : null,
+ hasNamedInitialize ? "initialize" : null,
+ ].filter((hook): hook is string => hook !== null);
+ const defaultExportExample = `export default { ${lifecycleHooks.join(", ")} }`;
+ const namedExportExample =
+ lifecycleHooks.length === 1
+ ? `export function ${lifecycleHooks[0]}`
+ : "named export function ...";
+ return new Error(
+ `Anywidget module at ${jsUrl} uses named exports (${namedExports}). ` +
+ "Per the AFM spec, use a default export instead: " +
+ `\`${defaultExportExample}\` (not \`${namedExportExample}\`). ` +
+ `See ${afmDocs}`,
+ );
+ }
+
+ return new Error(
+ `Anywidget module at ${jsUrl} is missing a default export. ` +
+ "Per the AFM spec, use `export default { render }` or " +
+ "`export default async () => ({ render })`. " +
+ `See ${afmDocs}`,
+ );
+}
diff --git a/frontend/src/plugins/impl/anywidget/runtime.ts b/frontend/src/plugins/impl/anywidget/runtime.ts
new file mode 100644
index 0000000000..e68e6f773d
--- /dev/null
+++ b/frontend/src/plugins/impl/anywidget/runtime.ts
@@ -0,0 +1,408 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import { Deferred } from "@/utils/Deferred";
+import { Logger } from "@/utils/Logger";
+import type { Host, ResolvedWidget } from "@anywidget/types";
+import type { Model } from "./model";
+import {
+ getInvalidAnyWidgetModuleError,
+ resolveAnyWidget,
+} from "./resolve-widget";
+import type { EsmSpec, ModelState, WidgetModelId } from "./types";
+import { WIDGET_DEF_REGISTRY, WidgetBinding } from "./widget-binding";
+
+interface Generation {
+ hash: string;
+ controller: AbortController;
+ promise: Promise<WidgetBinding<ModelState>>;
+}
+
+interface RuntimeView {
+ el: HTMLElement;
+ signal: AbortSignal;
+ generation?: Generation;
+}
+
+interface StyleMount {
+ references: number;
+ update(css: string): void;
+ dispose(): void;
+}
+
+interface WidgetRuntimeOptions {
+ timeout: number;
+ isEditMode: () => boolean;
+ createHost: (signal: AbortSignal) => Host;
+ onModelTimeout: () => void;
+}
+
+type StyleRoot = Document | ShadowRoot;
+
+/**
+ * The complete browser-side lifetime of one widget model.
+ *
+ * A runtime survives ESM generation changes. It owns initialization,
+ * mounted views, composition hosts, styles, and teardown so callers never
+ * need to coordinate those concerns themselves.
+ */
+export class WidgetRuntime {
+ readonly #key: WidgetModelId;
+ readonly #timeout: number;
+ readonly #isEditMode: () => boolean;
+ readonly #createHost: (signal: AbortSignal) => Host;
+ readonly #onModelTimeout: () => void;
+ readonly #controller = new AbortController();
+ readonly #model = new Deferred<Model<ModelState>>();
+ readonly #views = new Set<RuntimeView>();
+ readonly #styleMounts = new Map<StyleRoot, StyleMount>();
+ #modelTimeout: ReturnType<typeof setTimeout> | undefined;
+ #esmSpec: EsmSpec | undefined;
+ #generation: Generation | undefined;
+ #generationCleanup = Promise.resolve();
+ #css = "";
+
+ constructor(key: WidgetModelId, options: WidgetRuntimeOptions) {
+ this.#key = key;
+ this.#timeout = options.timeout;
+ this.#isEditMode = options.isEditMode;
+ this.#createHost = options.createHost;
+ this.#onModelTimeout = options.onModelTimeout;
+ }
+
+ getModel(): Promise<Model<ModelState>> {
+ if (this.#model.status === "pending" && !this.#modelTimeout) {
+ this.#modelTimeout = setTimeout(() => {
+ if (this.#model.status === "pending") {
+ this.#modelTimeout = undefined;
+ this.#model.reject(
+ new Error(`Model not found for key: ${this.#key}`),
+ );
+ this.#onModelTimeout();
+ }
+ }, this.#timeout);
+ }
+ return this.#model.promise;
+ }
+
+ getModelSync(): Model<ModelState> | undefined {
+ return this.#model.status === "resolved" ? this.#model.value : undefined;
+ }
+
+ createModel(factory: (signal: AbortSignal) => Model<ModelState>): void {
+ if (this.#model.status !== "pending") {
+ return;
+ }
+ this.#resolveModel(factory(this.#controller.signal));
+ }
+
+ setModel(model: Model<ModelState>): void {
+ if (this.#model.status !== "pending") {
+ return;
+ }
+ this.#resolveModel(model);
+ }
+
+ #resolveModel(model: Model<ModelState>): void {
+ if (this.#modelTimeout) {
+ clearTimeout(this.#modelTimeout);
+ this.#modelTimeout = undefined;
+ }
+ this.#model.resolve(model);
+ const css = model.get("_css");
+ this.#css = typeof css === "string" ? css : "";
+ model.on(
+ "change:_css",
+ (value: unknown) => {
+ this.#css = typeof value === "string" ? value : "";
+ for (const mount of this.#styleMounts.values()) {
+ mount.update(this.#css);
+ }
+ },
+ { signal: this.#controller.signal },
+ );
+ }
+
+ setSpec(spec: EsmSpec): void {
+ if (!this.#esmSpec) {
+ this.#esmSpec = spec;
+ return;
+ }
+ // A viewer's code is immutable for the lifetime of its model. This
+ // also covers a viewer that receives an editor's update before its
+ // first view creates a generation.
+ if (!this.#isEditMode()) {
+ return;
+ }
+ this.#esmSpec = spec;
+ if (this.#generation && this.#generation.hash !== spec.hash) {
+ this.#swapGeneration(spec);
+ }
+ }
+
+ async getWidget<T = unknown>(): Promise<ResolvedWidget<T>> {
+ const binding = await this.#getCurrentBinding();
+ return {
+ exports: binding.exports as T,
+ render: async ({ el, signal }) => {
+ await this.createView({
+ el,
+ signal: signal ?? this.#controller.signal,
+ });
+ },
+ };
+ }
+
+ async createView(options: {
+ el: HTMLElement;
+ signal: AbortSignal;
+ }): Promise<void> {
+ if (options.signal.aborted || this.#controller.signal.aborted) {
+ return;
+ }
+ const view: RuntimeView = {
+ el: options.el,
+ signal: options.signal,
+ };
+ this.#views.add(view);
+ this.#mountStyle(view);
+ options.signal.addEventListener("abort", () => this.#views.delete(view), {
+ once: true,
+ });
+ await this.#renderView(view);
+ }
+
+ async #getCurrentBinding(): Promise<WidgetBinding<ModelState>> {
+ while (!this.#controller.signal.aborted) {
+ const model = await this.getModel();
+ let generation = this.#generation;
+ if (!generation) {
+ const spec = this.#esmSpec;
+ if (!spec) {
+ throw new Error(
+ `[anywidget] No ESM spec for model ${this.#key}: ` +
+ "nothing ever provided this widget's code",
+ );
+ }
+ generation = this.#startGeneration(spec, model);
+ }
+ try {
+ const binding = await generation.promise;
+ if (generation === this.#generation) {
+ return binding;
+ }
+ } catch (error) {
+ if (!this.#generation || generation === this.#generation) {
+ throw error;
+ }
+ }
+ }
+ throw new Error("[anywidget] widget runtime destroyed");
+ }
+
+ async #createBinding(options: {
+ spec: EsmSpec;
+ model: Model<ModelState>;
+ controller: AbortController;
+ }): Promise<WidgetBinding<ModelState>> {
+ const { spec, model, controller } = options;
+ const mod = await WIDGET_DEF_REGISTRY.getModule({
+ jsUrl: spec.url,
+ jsHash: spec.hash,
+ kernelAuthored: true,
+ });
+ const widget = resolveAnyWidget(mod, spec.url);
+ if (!widget) {
+ throw getInvalidAnyWidgetModuleError(mod, spec.url);
+ }
+ return WidgetBinding.create({
+ widgetDef: widget,
+ model,
+ createHost: this.#createHost,
+ controller,
+ });
+ }
+
+ #startGeneration(spec: EsmSpec, model: Model<ModelState>): Generation {
+ const controller = new AbortController();
+ const generation: Generation = {
+ hash: spec.hash,
+ controller,
+ promise: this.#createBinding({ spec, model, controller }),
+ };
+ generation.promise.catch(() => {
+ if (this.#generation === generation) {
+ this.#generation = undefined;
+ }
+ });
+ this.#generation = generation;
+ return generation;
+ }
+
+ #swapGeneration(spec: EsmSpec): void {
+ const previous = this.#generation;
+ if (!previous) {
+ return;
+ }
+ Logger.debug(
+ `[WidgetRuntime] Hot-swapping generation for model=${this.#key}`,
+ );
+ const cleanup = this.#queueGenerationCleanup(previous);
+ const model = this.getModelSync();
+ if (!model) {
+ return;
+ }
+ const generation = this.#startGeneration(spec, model);
+ for (const view of this.#views) {
+ view.generation = undefined;
+ void cleanup
+ .then(() => this.#renderView(view, generation))
+ .catch((error) => {
+ Logger.error("[WidgetRuntime] Error replacing widget view", error);
+ });
+ }
+ }
+
+ #queueGenerationCleanup(generation: Generation): Promise<void> {
+ // Abort immediately so pending initialize/render hooks see cancellation,
+ // but serialize their settled cleanup before replacement DOM is rendered.
+ generation.controller.abort();
+ const cleanup = this.#generationCleanup.then(async () => {
+ try {
+ const binding = await generation.promise;
+ await binding.destroy();
+ } catch {
+ // A generation aborted during import/initialize has no binding to
+ // settle. Late initialize cleanup is handled by WidgetBinding.create.
+ }
+ });
+ this.#generationCleanup = cleanup;
+ return cleanup;
+ }
+
+ async #renderView(
+ view: RuntimeView,
+ requestedGeneration?: Generation,
+ ): Promise<void> {
+ if (view.signal.aborted || this.#controller.signal.aborted) {
+ return;
+ }
+ const generation = requestedGeneration ?? this.#generation;
+ const binding = generation
+ ? await generation.promise
+ : await this.#getCurrentBinding();
+ const current = this.#generation;
+ if (!current || current !== (generation ?? current)) {
+ return;
+ }
+ if (view.generation === current) {
+ return;
+ }
+ view.generation = current;
+ try {
+ await binding.createView({ el: view.el }, { signal: view.signal });
+ } catch (error) {
+ if (current !== this.#generation) {
+ view.generation = undefined;
+ return;
+ }
+ throw error;
+ }
+ }
+
+ #mountStyle(view: RuntimeView): void {
+ const root = view.el.getRootNode();
+ if (!(root instanceof Document || root instanceof ShadowRoot)) {
+ return;
+ }
+ let mount = this.#styleMounts.get(root);
+ if (!mount) {
+ mount = createStyleMount(root, this.#css);
+ this.#styleMounts.set(root, mount);
+ }
+ mount.references += 1;
+ let released = false;
+ const release = () => {
+ if (released) {
+ return;
+ }
+ released = true;
+ const current = this.#styleMounts.get(root);
+ if (!current) {
+ return;
+ }
+ current.references -= 1;
+ if (current.references === 0) {
+ current.dispose();
+ this.#styleMounts.delete(root);
+ }
+ };
+ view.signal.addEventListener("abort", release, { once: true });
+ }
+
+ dispose(): void {
+ if (this.#controller.signal.aborted) {
+ return;
+ }
+ Logger.debug(`[WidgetRuntime] Disposing model=${this.#key}`);
+ if (this.#modelTimeout) {
+ clearTimeout(this.#modelTimeout);
+ this.#modelTimeout = undefined;
+ }
+ if (this.#model.status === "pending") {
+ this.#model.promise.catch(() => undefined);
+ this.#model.reject(new Error("[anywidget] widget runtime destroyed"));
+ }
+ if (this.#generation) {
+ void this.#queueGenerationCleanup(this.#generation);
+ }
+ this.#controller.abort();
+ this.#views.clear();
+ for (const mount of this.#styleMounts.values()) {
+ mount.dispose();
+ }
+ this.#styleMounts.clear();
+ }
+}
+
+function createStyleMount(root: StyleRoot, initialCss: string): StyleMount {
+ if (
+ "adoptedStyleSheets" in root &&
+ typeof CSSStyleSheet !== "undefined" &&
+ typeof CSSStyleSheet.prototype.replaceSync === "function"
+ ) {
+ try {
+ const sheet = new CSSStyleSheet();
+ sheet.replaceSync(initialCss);
+ root.adoptedStyleSheets = [...root.adoptedStyleSheets, sheet];
+ return {
+ references: 0,
+ update(css) {
+ sheet.replaceSync(css);
+ },
+ dispose() {
+ root.adoptedStyleSheets = root.adoptedStyleSheets.filter(
+ (candidate) => candidate !== sheet,
+ );
+ },
+ };
+ } catch {
+ // Fall through to a style element when construction or parsing fails.
+ }
+ }
+
+ const style = document.createElement("style");
+ style.textContent = initialCss;
+ if (root instanceof Document) {
+ root.head.append(style);
+ } else {
+ root.append(style);
+ }
+ return {
+ references: 0,
+ update(css) {
+ style.textContent = css;
+ },
+ dispose() {
+ style.remove();
+ },
+ };
+}
diff --git a/frontend/src/plugins/impl/anywidget/schemas.ts b/frontend/src/plugins/impl/anywidget/schemas.ts
deleted file mode 100644
index cefbb4ea2a..0000000000
--- a/frontend/src/plugins/impl/anywidget/schemas.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-/* Copyright 2026 Marimo. All rights reserved. */
-import { z } from "zod";
-
-const BufferPathSchema = z.array(z.array(z.union([z.string(), z.number()])));
-const StateSchema = z.record(z.string(), z.any());
-
-export const AnyWidgetMessageSchema = z.discriminatedUnion("method", [
- z.object({
- method: z.literal("open"),
- state: StateSchema,
- buffer_paths: BufferPathSchema.optional(),
- }),
- z.object({
- method: z.literal("update"),
- state: StateSchema,
- buffer_paths: BufferPathSchema.optional(),
- }),
- z.object({
- method: z.literal("custom"),
- content: z.any(),
- }),
- z.object({
- method: z.literal("echo_update"),
- buffer_paths: BufferPathSchema,
- state: StateSchema,
- }),
- z.object({
- method: z.literal("close"),
- }),
-]);
-
-export type AnyWidgetMessage = z.infer<typeof AnyWidgetMessageSchema>;
diff --git a/frontend/src/plugins/impl/anywidget/types.ts b/frontend/src/plugins/impl/anywidget/types.ts
index 816c32be07..f33a3235bc 100644
--- a/frontend/src/plugins/impl/anywidget/types.ts
+++ b/frontend/src/plugins/impl/anywidget/types.ts
@@ -10,6 +10,10 @@ export type EventHandler = (...args: any[]) => void;
*/
export type WidgetModelId = TypedString<"WidgetModelId">;
+export function isWidgetModelId(value: unknown): value is WidgetModelId {
+ return typeof value === "string" && value.length > 0;
+}
+
/**
* AnyWidget model state with buffers.
*/
@@ -25,3 +29,13 @@ export interface WireFormat<T = Record<string, unknown>> {
bufferPaths: (string | number)[][];
buffers: Base64String[];
}
+
+/**
+ * Where a widget's ESM can be imported from, and which version.
+ * Structural mirror of the backend `EsmSpec`; `hash` keys the module
+ * cache and detects code changes (hot reload).
+ */
+export interface EsmSpec {
+ url: string;
+ hash: string;
+}
diff --git a/frontend/src/plugins/impl/anywidget/widget-binding.ts b/frontend/src/plugins/impl/anywidget/widget-binding.ts
index 4676b1d8b4..c71cb0c2d7 100644
--- a/frontend/src/plugins/impl/anywidget/widget-binding.ts
+++ b/frontend/src/plugins/impl/anywidget/widget-binding.ts
@@ -1,14 +1,19 @@
/* Copyright 2026 Marimo. All rights reserved. */
-/* oxlint-disable typescript/no-explicit-any */
-
-import type { AnyWidget, Experimental } from "@anywidget/types";
+import type {
+ AnyWidget,
+ Experimental,
+ Initialize,
+ Render,
+} from "@anywidget/types";
import { asRemoteURL } from "@/core/runtime/config";
import { resolveVirtualFileURL } from "@/core/static/files";
import { isStaticNotebook } from "@/core/static/static-state";
import { isTrustedVirtualFileUrl } from "@/plugins/core/trusted-url";
import { Logger } from "@/utils/Logger";
+import type { Host } from "./host";
import type { Model } from "./model";
-import type { ModelState, WidgetModelId } from "./types";
+import { modelProxy, type ProxyRegistration } from "./model-proxy";
+import type { ModelState } from "./types";
export const experimental: Experimental = {
invoke: async () => {
@@ -19,8 +24,6 @@ export const experimental: Experimental = {
},
};
-export type RenderFn = (el: HTMLElement, signal: AbortSignal) => Promise<void>;
-
/**
* Polyfill for AbortSignal.any. Returns a signal that aborts when any of the
* input signals abort. This can be removed once the Node.js test environment
@@ -48,19 +51,26 @@ function abortSignalAny(signals: AbortSignal[]): AbortSignal {
* A single import is shared across all widget instances using the same module.
*/
class WidgetDefRegistry {
- #cache = new Map<string, Promise<any>>();
+ #cache = new Map<string, Promise<unknown>>();
/**
- * Get (or start) the ESM import for a widget module.
- * Cached by jsHash so multiple instances share one import.
+ * Get (or start) the ESM import for a widget module, cached by
+ * jsHash so multiple instances share one import. Pass
+ * `kernelAuthored: true` only for URLs from an `EsmSpec`; it widens
+ * the import gate to remote and data URLs.
*/
- getModule(jsUrl: string, jsHash: string): Promise<any> {
+ getModule(options: {
+ jsUrl: string;
+ jsHash: string;
+ kernelAuthored?: boolean;
+ }): Promise<unknown> {
+ const { jsUrl, jsHash, kernelAuthored = false } = options;
const cached = this.#cache.get(jsHash);
if (cached) {
return cached;
}
- const promise = this.#doImport(jsUrl).catch((error) => {
+ const promise = this.#doImport(jsUrl, { kernelAuthored }).catch((error) => {
// On failure, remove from cache so a retry with a new URL can work
this.#cache.delete(jsHash);
throw error;
@@ -70,23 +80,19 @@ class WidgetDefRegistry {
return promise;
}
- /**
- * Invalidate a cached module (e.g. for hot-reload support).
- */
- invalidate(jsHash: string): void {
- Logger.debug(
- `[WidgetDefRegistry] Invalidating module cache for hash=${jsHash}`,
- );
- this.#cache.delete(jsHash);
- }
-
- async #doImport(jsUrl: string): Promise<any> {
- // Only trust marimo virtual file paths. Accepting arbitrary URLs
- // would let a raw `<marimo-anywidget data-js-url=...>` element
- // embedded in a markdown cell dynamically import attacker-controlled
- // JavaScript at same origin (the HTML sanitizer allows any marimo-*
- // custom element with any attribute through to the plugin layer).
- if (!isTrustedVirtualFileUrl(jsUrl)) {
+ async #doImport(
+ jsUrl: string,
+ opts: { kernelAuthored?: boolean } = {},
+ ): Promise<unknown> {
+ // By default, only trust marimo virtual file paths: arbitrary URLs
+ // would let markdown-injected elements import attacker-controlled
+ // JavaScript. Kernel-authored URLs (from an `EsmSpec`) are exempt —
+ // a client cannot forge a notification to its peers. data: URLs
+ // cover runtimes where virtual files are unsupported.
+ const trusted =
+ isTrustedVirtualFileUrl(jsUrl) ||
+ (opts.kernelAuthored === true && /^(https?:|data:)/.test(jsUrl));
+ if (!trusted) {
throw new Error(
`Refusing to load anywidget module from untrusted URL: ${String(
jsUrl,
@@ -102,128 +108,283 @@ class WidgetDefRegistry {
}
/**
- * Connects a Model to a resolved AnyWidget definition.
- * Owns the initialize lifecycle and produces a render function.
+ * Resolved widget def — what `initialize` and `render` are actually called
+ * on. `AnyWidget` is either this shape directly or a factory that returns it.
+ */
+interface ResolvedWidget<T extends ModelState> {
+ initialize?: Initialize<T>;
+ render?: Render<T>;
+}
+
+type HostFactory = (signal: AbortSignal) => Host;
+type Cleanup = () => void | PromiseLike<void>;
+
+function isCleanup(value: unknown): value is Cleanup {
+ return typeof value === "function";
+}
+
+interface CreateWidgetBindingOptions<T extends ModelState> {
+ widgetDef: AnyWidget<T>;
+ model: Model<T>;
+ createHost: HostFactory;
+ controller?: AbortController;
+}
+
+async function safelyRunCleanup(cleanup: Cleanup, reason: string) {
+ try {
+ await cleanup();
+ } catch (error) {
+ Logger.warn(`[WidgetBinding] ${reason} cleanup failed`, error);
+ }
+}
+
+/**
+ * One immutable generation of a widget: a resolved AnyWidget definition
+ * paired with a Model. Constructed by `WidgetBinding.create` and never
+ * rebinds; a code change replaces the whole generation.
*
* Per AFM spec:
- * - initialize() is called once per model (or once per hot-reload)
- * - render() (the returned function) is called once per view
+ * - initialize() ran exactly once, in `create`
+ * - render() runs once per view (zero or more per generation)
*/
-class WidgetBinding<T extends ModelState = ModelState> {
- #controller: AbortController | undefined;
- #widgetDef: AnyWidget<T> | undefined;
- #render: RenderFn | undefined;
+export class WidgetBinding<T extends ModelState = ModelState> {
+ #controller: AbortController;
+ #widget: ResolvedWidget<T>;
+ #model: Model<T>;
+ #exports: unknown;
+ #createHost: HostFactory;
+ #cleanupTasks = new Set<Promise<void>>();
+ #viewTasks = new Set<Promise<void>>();
+
+ private constructor(options: {
+ widget: ResolvedWidget<T>;
+ model: Model<T>;
+ exports: unknown;
+ controller: AbortController;
+ createHost: HostFactory;
+ }) {
+ this.#widget = options.widget;
+ this.#model = options.model;
+ this.#exports = options.exports;
+ this.#controller = options.controller;
+ this.#createHost = options.createHost;
+ }
/**
- * Bind a widget definition to a model.
- * If the same def is already bound, returns the cached render function.
- * If a different def is provided (hot reload), tears down the old binding
- * and re-initializes.
+ * Resolve the widget definition (calling it if it is a factory) and
+ * run `initialize` exactly once, with its listeners scoped to
+ * `controller`'s signal. Aborting the controller mid-initialize
+ * still runs any legacy cleanup callback, and `create` rejects.
*/
- async bind(widgetDef: AnyWidget<T>, model: Model<T>): Promise<RenderFn> {
- // Already initialized with the same widget - return cached render
- if (this.#render && this.#widgetDef === widgetDef) {
- return this.#render;
- }
+ static async create<T extends ModelState>({
+ widgetDef,
+ model,
+ createHost,
+ controller = new AbortController(),
+ }: CreateWidgetBindingOptions<T>): Promise<WidgetBinding<T>> {
+ const signal = controller.signal;
+ const widget: ResolvedWidget<T> =
+ typeof widgetDef === "function" ? await widgetDef() : widgetDef;
- // If widgetDef changed (hot reload), destroy old and re-initialize
- if (this.#render && this.#widgetDef !== widgetDef) {
- Logger.debug(
- "[WidgetBinding] Hot-reload detected, aborting previous binding",
- );
- this.#controller?.abort();
- this.#controller = undefined;
- this.#render = undefined;
- }
+ const initPromise = Promise.resolve(
+ widget.initialize?.({
+ model: modelProxy(model, signal),
+ experimental,
+ signal,
+ }),
+ );
+ // If destroyed mid-initialize, still run a late-arriving legacy
+ // cleanup callback: the widget acquired resources.
+ initPromise
+ .then(async (settled) => {
+ if (signal.aborted && isCleanup(settled)) {
+ await safelyRunCleanup(settled, "late initialize");
+ }
+ })
+ .catch(() => undefined);
- this.#widgetDef = widgetDef;
- this.#controller = new AbortController();
- const bindingSignal = this.#controller.signal;
+ // Race against destruction so a hung `initialize` can't strand
+ // callers whose model already closed.
+ const result = await Promise.race([
+ initPromise,
+ new Promise<never>((_, reject) => {
+ const abort = () => reject(new Error("[anywidget] binding destroyed"));
+ if (signal.aborted) {
+ abort();
+ return;
+ }
+ signal.addEventListener("abort", abort, { once: true });
+ }),
+ ]);
- // Resolve the widget definition (call if it's a function)
- const widget =
- typeof widgetDef === "function" ? await widgetDef() : widgetDef;
+ if (signal.aborted) {
+ throw new Error("[anywidget] binding destroyed");
+ }
- // Call initialize once per model
- const cleanup = await widget.initialize?.({ model, experimental });
- if (cleanup) {
- bindingSignal.addEventListener("abort", cleanup);
+ // Distinguish anywidget's three return shapes:
+ // function → legacy cleanup callback (run on destroy)
+ // object → widget exports (anywidget>=0.11)
+ // void → nothing
+ let exports: unknown;
+ let initializeCleanup: Cleanup | undefined;
+ if (isCleanup(result)) {
+ initializeCleanup = result;
+ exports = undefined;
+ } else if (typeof result === "object" && result !== null) {
+ exports = result;
+ } else {
+ exports = undefined;
}
- // Store and return the render closure
- this.#render = async (el: HTMLElement, viewSignal: AbortSignal) => {
- const renderCleanup = await widget.render?.({
- model,
- el,
- experimental,
- });
- if (renderCleanup) {
- // Cleanup when either the view unmounts or the binding is destroyed
- const combined = abortSignalAny([viewSignal, bindingSignal]);
- combined.addEventListener("abort", () => {
- const reason = viewSignal.aborted
- ? "view unmount"
- : "binding destroyed";
- Logger.debug(
- `[WidgetBinding] Render cleanup triggered (reason: ${reason})`,
- );
- renderCleanup();
- });
- }
- };
+ const binding = new WidgetBinding({
+ widget,
+ model,
+ exports,
+ controller,
+ createHost,
+ });
+ if (initializeCleanup) {
+ signal.addEventListener(
+ "abort",
+ () => void binding.#trackCleanup(initializeCleanup, "initialize"),
+ { once: true },
+ );
+ }
+ return binding;
+ }
- return this.#render;
+ /**
+ * The object returned from `initialize`, or `undefined` if it
+ * returned a cleanup function or nothing.
+ */
+ get exports(): unknown {
+ return this.#exports;
}
/**
- * Destroy this binding, aborting the initialize lifecycle.
+ * Mount a view of this widget into `el`. Each view's signal aborts
+ * when the caller's `signal` fires or the binding is destroyed, and
+ * listeners registered inside `render` auto-clear on abort.
+ *
+ * Hydration guarantee: listeners attached during `render` observe
+ * current model state exactly once, after `render` settles. Scoped
+ * to this view's listeners; re-firing at other views double-paints.
*/
- destroy(): void {
- Logger.debug(
- "[WidgetBinding] Destroying binding, aborting initialize lifecycle",
- );
- this.#controller?.abort();
- this.#controller = undefined;
- this.#widgetDef = undefined;
- this.#render = undefined;
+ async createView(
+ target: { el: HTMLElement },
+ options: { signal: AbortSignal },
+ ): Promise<void> {
+ const task = this.#createView(target, options);
+ this.#viewTasks.add(task);
+ try {
+ await task;
+ } finally {
+ this.#viewTasks.delete(task);
+ }
}
-}
-/**
- * Maps WidgetModelId to WidgetBinding instances.
- * Singleton that manages the lifecycle of all bindings.
- */
-class BindingManager {
- #bindings = new Map<WidgetModelId, WidgetBinding<any>>();
-
- getOrCreate(modelId: WidgetModelId): WidgetBinding<any> {
- let binding = this.#bindings.get(modelId);
- if (!binding) {
- binding = new WidgetBinding();
- this.#bindings.set(modelId, binding);
+ async #createView(
+ target: { el: HTMLElement },
+ options: { signal: AbortSignal },
+ ): Promise<void> {
+ const widget = this.#widget;
+ if (!widget.render) {
+ return;
}
- return binding;
+ // `renderSignal` aborts when either the caller's view unmounts or
+ // the binding itself is destroyed.
+ const renderSignal = abortSignalAny([
+ options.signal,
+ this.#controller.signal,
+ ]);
+ if (renderSignal.aborted) {
+ return;
+ }
+ // Clear whatever a previous generation or render left behind.
+ target.el.innerHTML = "";
+ // Each view gets a host scoped to its own signal so child views tear
+ // down with this view.
+ const host = this.#createHost(renderSignal);
+ const registrations: ProxyRegistration[] = [];
+ const renderCleanup = await widget.render({
+ model: modelProxy(this.#model, renderSignal, (registration) =>
+ registrations.push(registration),
+ ),
+ el: target.el,
+ experimental,
+ signal: renderSignal,
+ host,
+ });
+ if (isCleanup(renderCleanup)) {
+ const runCleanup = () => {
+ const reason = options.signal.aborted
+ ? "view unmount"
+ : "binding destroyed";
+ Logger.debug(
+ `[WidgetBinding] Render cleanup triggered (reason: ${reason})`,
+ );
+ return this.#trackCleanup(renderCleanup, "render");
+ };
+ if (renderSignal.aborted) {
+ await runCleanup();
+ return;
+ }
+ renderSignal.addEventListener("abort", () => void runCleanup(), {
+ once: true,
+ });
+ }
+ this.#replayState(registrations, renderSignal);
+ }
+
+ #trackCleanup(cleanup: Cleanup, reason: string): Promise<void> {
+ const task = safelyRunCleanup(cleanup, reason);
+ this.#cleanupTasks.add(task);
+ void task.finally(() => this.#cleanupTasks.delete(task));
+ return task;
}
- destroy(modelId: WidgetModelId): void {
- const binding = this.#bindings.get(modelId);
- if (binding) {
- Logger.debug(`[BindingManager] Destroying binding for model=${modelId}`);
- binding.destroy();
- this.#bindings.delete(modelId);
+ /**
+ * The hydration guarantee documented on `createView`.
+ */
+ #replayState(
+ registrations: readonly ProxyRegistration[],
+ renderSignal: AbortSignal,
+ ): void {
+ const changePrefix = "change:";
+ for (const { event, callback } of registrations) {
+ if (renderSignal.aborted) {
+ return;
+ }
+ try {
+ if (event.startsWith(changePrefix)) {
+ const key = event.slice(changePrefix.length);
+ callback(this.#model.get(key));
+ } else if (event === "change") {
+ callback();
+ }
+ } catch (error) {
+ Logger.error("[WidgetBinding] Error replaying state", error);
+ }
}
}
- has(modelId: WidgetModelId): boolean {
- return this.#bindings.has(modelId);
+ /**
+ * Destroy this generation, running initialize/render cleanups and
+ * clearing listeners registered through its model proxies.
+ */
+ async destroy(): Promise<void> {
+ Logger.debug("[WidgetBinding] Destroying binding generation");
+ this.#controller.abort();
+ await Promise.allSettled(this.#viewTasks);
+ while (this.#cleanupTasks.size > 0) {
+ await Promise.all(this.#cleanupTasks);
+ }
}
}
export const WIDGET_DEF_REGISTRY = new WidgetDefRegistry();
-export const BINDING_MANAGER = new BindingManager();
export const visibleForTesting = {
WidgetDefRegistry,
WidgetBinding,
- BindingManager,
};
diff --git a/frontend/src/plugins/impl/anywidget/widget-ref.ts b/frontend/src/plugins/impl/anywidget/widget-ref.ts
new file mode 100644
index 0000000000..3b569e5147
--- /dev/null
+++ b/frontend/src/plugins/impl/anywidget/widget-ref.ts
@@ -0,0 +1,29 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { isWidgetModelId, type WidgetModelId } from "./types";
+
+export const WIDGET_REF_PREFIX = "anywidget:";
+
+/**
+ * Parse a widget reference string into its model id.
+ *
+ * Per anywidget>=0.11, widget refs are serialized as
+ * `anywidget:<model_id>` strings embedded directly in widget state.
+ * `host.getWidget(ref)` consumes these strings.
+ *
+ * The legacy `IPY_MODEL_<id>` prefix used by ipywidgets'
+ * `widget_serialization` is intentionally NOT accepted here — widgets
+ * using that path resolve children manually via
+ * `model.widget_manager.get_model(id)` after stripping the prefix.
+ */
+export function parseWidgetRef(ref: unknown): WidgetModelId {
+ if (typeof ref === "string" && ref.startsWith(WIDGET_REF_PREFIX)) {
+ const modelId = ref.slice(WIDGET_REF_PREFIX.length);
+ if (isWidgetModelId(modelId)) {
+ return modelId;
+ }
+ }
+ throw new Error(
+ `[anywidget] Invalid widget reference: ${JSON.stringify(ref)}`,
+ );
+}
diff --git a/frontend/src/plugins/impl/mpl-interactive/MplInteractivePlugin.tsx b/frontend/src/plugins/impl/mpl-interactive/MplInteractivePlugin.tsx
index 7fd3d6461e..b82da725f9 100644
--- a/frontend/src/plugins/impl/mpl-interactive/MplInteractivePlugin.tsx
+++ b/frontend/src/plugins/impl/mpl-interactive/MplInteractivePlugin.tsx
@@ -6,7 +6,8 @@ import { z } from "zod";
import { useEventListener } from "@/hooks/useEventListener";
import { createPlugin } from "@/plugins/core/builder";
import { isTrustedVirtualFileUrl } from "@/plugins/core/trusted-url";
-import { MODEL_MANAGER, type Model } from "@/plugins/impl/anywidget/model";
+import type { Model } from "@/plugins/impl/anywidget/model";
+import { WIDGET_REGISTRY } from "@/plugins/impl/anywidget/registry";
import type { ModelState, WidgetModelId } from "@/plugins/impl/anywidget/types";
import type { IPluginProps } from "@/plugins/types";
import { downloadBlob } from "@/utils/download";
@@ -204,7 +205,7 @@ const MplInteractiveSlot = (props: IPluginProps<ModelIdRef, Data>) => {
let model: Model<ModelState>;
try {
- model = await MODEL_MANAGER.get(id);
+ model = await WIDGET_REGISTRY.getModel(id);
} catch {
Logger.error("Failed to get model for mpl interactive", id);
return;
diff --git a/frontend/src/plugins/impl/mpl-interactive/__tests__/MplInteractivePlugin.test.tsx b/frontend/src/plugins/impl/mpl-interactive/__tests__/MplInteractivePlugin.test.tsx
index 62bfcdb68d..9ccfc9ec83 100644
--- a/frontend/src/plugins/impl/mpl-interactive/__tests__/MplInteractivePlugin.test.tsx
+++ b/frontend/src/plugins/impl/mpl-interactive/__tests__/MplInteractivePlugin.test.tsx
@@ -11,8 +11,9 @@ import { parseUserConfig } from "@/core/config/config-schema";
import { initialModeAtom } from "@/core/mode";
import { store } from "@/core/state/jotai";
import { Logger } from "@/utils/Logger";
-import { MODEL_MANAGER, Model } from "@/plugins/impl/anywidget/model";
-import type { WidgetModelId } from "@/plugins/impl/anywidget/types";
+import { Model } from "@/plugins/impl/anywidget/model";
+import { WIDGET_REGISTRY } from "@/plugins/impl/anywidget/registry";
+import type { ModelState, WidgetModelId } from "@/plugins/impl/anywidget/types";
import { visibleForTesting } from "../MplInteractivePlugin";
const { ensureMplJs, injectCss, MplInteractiveSlot, resetMplJsLoading } =
@@ -118,7 +119,9 @@ describe("MplInteractivePlugin URL validation", () => {
describe("injectCss", () => {
it("refuses to append <link> for the PoC attack CSS URL", () => {
const container = document.createElement("div");
- const loggerSpy = vi.spyOn(Logger, "error").mockImplementation(() => {});
+ const loggerSpy = vi
+ .spyOn(Logger, "error")
+ .mockImplementation(() => undefined);
const cleanup = injectCss(container, "http://127.0.0.1:8820/x.css");
@@ -136,7 +139,7 @@ describe("MplInteractivePlugin URL validation", () => {
"data:text/css,body{background:red}",
])("refuses to append <link> for %s", (url) => {
const container = document.createElement("div");
- vi.spyOn(Logger, "error").mockImplementation(() => {});
+ vi.spyOn(Logger, "error").mockImplementation(() => undefined);
injectCss(container, url);
@@ -194,8 +197,8 @@ function installMplFigureMock(): ReturnType<typeof vi.fn> {
return ctor;
}
-function makeModel(): Model<Record<string, never>> {
- return new Model(
+function makeModel(): Model<ModelState> {
+ return new Model<ModelState>(
{},
{
sendUpdate: vi.fn().mockResolvedValue(undefined),
@@ -222,7 +225,7 @@ function makeProps(modelId: WidgetModelId) {
describe("MplInteractiveSlot rerun rebinding", () => {
beforeEach(() => {
- vi.spyOn(Logger, "error").mockImplementation(() => {});
+ vi.spyOn(Logger, "error").mockImplementation(() => undefined);
resetMplJsLoading();
});
@@ -235,8 +238,8 @@ describe("MplInteractiveSlot rerun rebinding", () => {
const ctor = installMplFigureMock();
const idA = asModelId("model-a");
const idB = asModelId("model-b");
- MODEL_MANAGER.set(idA, makeModel());
- MODEL_MANAGER.set(idB, makeModel());
+ WIDGET_REGISTRY.setModel(idA, makeModel());
+ WIDGET_REGISTRY.setModel(idB, makeModel());
const { container, rerender } = render(
<MplInteractiveSlot {...makeProps(idA)} />,
@@ -267,7 +270,7 @@ describe("MplInteractiveSlot rerun rebinding", () => {
it("detaches the previous model's listener on each rerun (no buildup)", async () => {
installMplFigureMock();
- // Unique ids: MODEL_MANAGER is a module singleton whose deferreds resolve
+ // Unique ids: WIDGET_REGISTRY is a module singleton whose deferreds resolve
// once, so reusing ids from another test would return that test's models.
const idA = asModelId("leak-a");
const idB = asModelId("leak-b");
@@ -275,9 +278,9 @@ describe("MplInteractiveSlot rerun rebinding", () => {
const modelA = makeModel();
const modelB = makeModel();
const modelC = makeModel();
- MODEL_MANAGER.set(idA, modelA);
- MODEL_MANAGER.set(idB, modelB);
- MODEL_MANAGER.set(idC, modelC);
+ WIDGET_REGISTRY.setModel(idA, modelA);
+ WIDGET_REGISTRY.setModel(idB, modelB);
+ WIDGET_REGISTRY.setModel(idC, modelC);
const onA = vi.spyOn(modelA, "on");
const offA = vi.spyOn(modelA, "off");
diff --git a/frontend/src/plugins/impl/mpl-interactive/mpl-websocket-shim.ts b/frontend/src/plugins/impl/mpl-interactive/mpl-websocket-shim.ts
index 5eb11ccdd9..4093ff631b 100644
--- a/frontend/src/plugins/impl/mpl-interactive/mpl-websocket-shim.ts
+++ b/frontend/src/plugins/impl/mpl-interactive/mpl-websocket-shim.ts
@@ -1,7 +1,7 @@
/* Copyright 2026 Marimo. All rights reserved. */
/**
- * Fake WebSocket that routes messages through MarimoComm / MODEL_MANAGER
+ * Fake WebSocket that routes messages through MarimoComm / WIDGET_REGISTRY
* instead of a real network WebSocket.
*
* mpl.js expects a WebSocket-like object with:
diff --git a/marimo/_messaging/notification.py b/marimo/_messaging/notification.py
index 2b5f578d66..be0acb7344 100644
--- a/marimo/_messaging/notification.py
+++ b/marimo/_messaging/notification.py
@@ -176,20 +176,73 @@ class UIElementMessageNotification(
buffers: list[bytes] | None = None
+class EsmSpec(msgspec.Struct):
+ """Where the frontend imports a widget's ESM from, and which version.
+
+ Specs travel only on kernel-authored notifications, never in model
+ state: state is client-writable and echoed to peers, so executing
+ code from it would let one client run code on another.
+
+ Attributes:
+ url: URL to import the ESM from. A virtual file for inline
+ source; an external URL when `_esm` is itself a URL.
+ hash: Hash of the `_esm` string. Keys the frontend module cache
+ and signals code changes (hot reload).
+ """
+
+ url: str
+ hash: str
+
+ @staticmethod
+ def from_esm(esm: str) -> EsmSpec:
+ """Mint a spec for an `_esm` trait value."""
+ # Imported lazily: this module is low-level messaging, and
+ # mo_data pulls in the runtime/output machinery.
+ import marimo._output.data.data as mo_data
+ from marimo._utils.code import hash_code
+
+ return EsmSpec(url=mo_data.js(esm).url, hash=hash_code(esm))
+
+
class ModelOpen(msgspec.Struct, tag="open", tag_field="method"):
- """Initial widget state on creation."""
+ """Initial widget state on creation.
+
+ For anywidgets, the widget's ESM does not travel in `state`: the
+ comm strips `_esm` and sends an `EsmSpec` instead. `None` for
+ models with no ESM (e.g. traditional ipywidgets).
+
+ Attributes:
+ state: Initial trait values, minus `_esm`.
+ buffer_paths: Paths into `state` whose binary values were
+ extracted into `buffers`.
+ buffers: Binary payloads, parallel to `buffer_paths`.
+ esm_spec: Where to import this widget's ESM from.
+ """
state: dict[str, Any]
buffer_paths: list[list[str | int]]
buffers: list[bytes]
+ esm_spec: EsmSpec | None = None
class ModelUpdate(msgspec.Struct, tag="update", tag_field="method"):
- """State sync - changed traits only."""
+ """State sync - changed traits only.
+
+ Attributes:
+ state: Changed trait values, minus `_esm` (see `ModelOpen`).
+ buffer_paths: Paths into `state` whose binary values were
+ extracted into `buffers`.
+ buffers: Binary payloads, parallel to `buffer_paths`.
+ esm_spec: Present only when the widget's `_esm` changed on a
+ live model (hot reload, edit mode only). A spec whose
+ `hash` differs from the current one tells the frontend the
+ widget's code changed and views must be rebuilt.
+ """
state: dict[str, Any]
buffer_paths: list[list[str | int]]
buffers: list[bytes]
+ esm_spec: EsmSpec | None = None
class ModelCustom(msgspec.Struct, tag="custom", tag_field="method"):
diff --git a/marimo/_output/formatters/repr_formatters.py b/marimo/_output/formatters/repr_formatters.py
index 74e4cb0dcd..7ea22106f0 100644
--- a/marimo/_output/formatters/repr_formatters.py
+++ b/marimo/_output/formatters/repr_formatters.py
@@ -28,7 +28,7 @@ def _maybe_as_anywidget_html(
Converts `application/vnd.jupyter.widget-view+json` mimebundles
into the same `<marimo-anywidget>` HTML that `mo.ui.anywidget()`
- produces. Works for any comm whose open state included `_esm`
+ produces. Works for any comm whose open minted a def pointer
(both descriptor-based and ipywidgets-based anywidgets).
Traditional (non-anywidget) jupyter widgets are left untouched so
@@ -41,7 +41,10 @@ def _maybe_as_anywidget_html(
if not model_id:
return None
- # Look up the comm and get the _esm that was stashed during open.
+ # Look up the comm; its ESM spec was minted at open. A comm without
+ # one belongs to a traditional jupyter widget — those are left for
+ # the frontend's error banner. The spec itself travels on the open
+ # notification; the component only names the model it displays.
try:
from marimo._plugins.ui._impl.anywidget.init import (
WIDGET_COMM_MANAGER,
@@ -50,25 +53,16 @@ def _maybe_as_anywidget_html(
return None
comm = WIDGET_COMM_MANAGER.comms.get(model_id) # type: ignore[arg-type]
- if comm is None or not comm.esm:
+ if comm is None or comm.esm_spec is None:
return None
- import marimo._output.data.data as mo_data
from marimo._plugins.core.web_component import build_ui_plugin
- from marimo._utils.code import hash_code
-
- js_url = mo_data.js(comm.esm).url
- js_hash = hash_code(comm.esm)
inner = build_ui_plugin(
component_name="marimo-anywidget",
initial_value={},
label=None,
- args={
- "js-url": js_url,
- "js-hash": js_hash,
- "model-id": model_id,
- },
+ args={"model-id": model_id},
)
# Wrap in <marimo-ui-element> so the plugin gets proper lifecycle
# management (remount on re-run via random-id change).
diff --git a/marimo/_plugins/ui/_impl/anywidget/widget_ref.py b/marimo/_plugins/ui/_impl/anywidget/widget_ref.py
new file mode 100644
index 0000000000..14ffb829bd
--- /dev/null
+++ b/marimo/_plugins/ui/_impl/anywidget/widget_ref.py
@@ -0,0 +1,102 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import sys
+from typing import Any
+
+_WIDGET_REF_PREFIX = "anywidget:"
+
+
+def _is_anywidget_state(value: Any) -> bool:
+ """Return whether an opening model state belongs to an anywidget."""
+ return isinstance(value, dict) and (
+ "_esm" in value or value.get("_model_module") == "anywidget"
+ )
+
+
+def _try_get_widget_model_id(value: Any) -> str | None:
+ """Return the model id of a value if it looks like an anywidget.
+
+ Detects ipywidgets-derived `AnyWidget` instances through `model_id` and
+ protocol-based widgets through anywidget's `MimeBundleDescriptor`.
+ Accessing the descriptor intentionally opens the child's comm when it has
+ not been displayed independently.
+ """
+ model_id = getattr(value, "model_id", None)
+ if isinstance(model_id, str) and model_id:
+ return model_id
+
+ # A descriptor-backed widget can only exist after this module has been
+ # imported. Reuse it instead of importing an optional dependency while
+ # inspecting arbitrary state values. A failed submodule import can leave a
+ # partial `anywidget` module in `sys.modules`.
+ descriptor_module = sys.modules.get("anywidget._descriptor")
+ if descriptor_module is None:
+ return None
+ descriptor_type = getattr(descriptor_module, "MimeBundleDescriptor", None)
+ repr_type = getattr(descriptor_module, "ReprMimeBundle", None)
+ if not isinstance(descriptor_type, type) or not isinstance(
+ repr_type, type
+ ):
+ return None
+
+ bundle = getattr(value, "_repr_mimebundle_", None)
+ if isinstance(bundle, descriptor_type):
+ descriptor_get = getattr(bundle, "__get__", None)
+ if not callable(descriptor_get):
+ return None
+ bundle = descriptor_get(value, type(value))
+ if isinstance(bundle, repr_type):
+ bundle_id = getattr(bundle, "model_id", None)
+ if not isinstance(bundle_id, str) or not bundle_id:
+ comm = getattr(bundle, "_comm", None)
+ bundle_id = getattr(comm, "comm_id", None)
+ if isinstance(bundle_id, str) and bundle_id:
+ return bundle_id
+ return None
+
+
+def _replace_widget_refs(value: Any) -> Any:
+ """Recursively replace anywidget instances with wire-format references.
+
+ Walks dictionaries, lists, and tuples. Returns a new container when a
+ replacement occurs and otherwise preserves the original container's
+ identity.
+ """
+ model_id = _try_get_widget_model_id(value)
+ if model_id is not None:
+ return f"{_WIDGET_REF_PREFIX}{model_id}"
+ if isinstance(value, dict):
+ replaced = {k: _replace_widget_refs(v) for k, v in value.items()}
+ if all(replaced[k] is value[k] for k in value):
+ return value
+ return replaced
+ if isinstance(value, list):
+ replaced_list = [_replace_widget_refs(v) for v in value]
+ if all(a is b for a, b in zip(replaced_list, value, strict=True)):
+ return value
+ return replaced_list
+ if isinstance(value, tuple):
+ replaced_tuple = tuple(_replace_widget_refs(v) for v in value)
+ if all(a is b for a, b in zip(replaced_tuple, value, strict=True)):
+ return value
+ return replaced_tuple
+ return value
+
+
+class AnyWidgetStateSerializer:
+ """Serialize widget references for one anywidget comm.
+
+ Classification happens once from the complete opening state. Subsequent
+ updates are partial and therefore cannot reliably identify the model on
+ their own.
+ """
+
+ def __init__(self, initial_state: Any) -> None:
+ self._enabled = _is_anywidget_state(initial_state)
+
+ def serialize(self, state: Any) -> Any:
+ """Replace widget references when this comm belongs to an anywidget."""
+ if not self._enabled:
+ return state
+ return _replace_widget_refs(state)
diff --git a/marimo/_plugins/ui/_impl/comm.py b/marimo/_plugins/ui/_impl/comm.py
index 8168d33767..ec61a0688d 100644
--- a/marimo/_plugins/ui/_impl/comm.py
+++ b/marimo/_plugins/ui/_impl/comm.py
@@ -3,10 +3,11 @@ from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass, field
-from typing import Any
+from typing import TYPE_CHECKING, Any
from marimo._loggers import marimo_logger
from marimo._messaging.notification import (
+ EsmSpec,
ModelClose,
ModelCustom,
ModelLifecycleNotification,
@@ -15,12 +16,19 @@ from marimo._messaging.notification import (
ModelUpdate,
)
from marimo._messaging.notification_utils import broadcast_notification
+from marimo._plugins.ui._impl.anywidget.widget_ref import (
+ AnyWidgetStateSerializer,
+)
from marimo._runtime.commands import (
ModelCommand,
ModelUpdateMessage,
)
from marimo._types.ids import WidgetModelId
+if TYPE_CHECKING:
+ from marimo._messaging.types import Stream
+ from marimo._runtime.context.utils import RunMode
+
LOGGER = marimo_logger()
@@ -56,10 +64,19 @@ class MarimoCommManager:
return (None, None)
comm = self.comms[command.model_id]
+
+ # Clients may write widget state, never code or style: anything
+ # surviving this reaches `widget.set_state` and is echoed to
+ # peers. Filter by known-key list; other underscore traits are
+ # legitimate widget state.
+ message = command.message
+ if isinstance(message, ModelUpdateMessage):
+ for key in ("_esm", "_css"):
+ message.state.pop(key, None)
+
comm.handle_msg(command.into_comm_payload())
# For update messages, return ui_element_id and state for cell re-run
- message = command.message
if isinstance(message, ModelUpdateMessage) and comm.ui_element_id:
return (comm.ui_element_id, message.state)
@@ -92,12 +109,17 @@ def _ensure_bytes(buf: object) -> bytes:
def _create_model_message(
data: dict[str, Any],
buffers: list[Buffer],
+ esm_spec: EsmSpec | None = None,
) -> ModelMessage | None:
"""Create the appropriate ModelMessage based on the method field.
- Returns None for unknown methods that should be skipped.
- `echo_update` is converted to `ModelUpdate` to preserve
- frontend-driven trait changes for reconnect replay.
+ Returns None for unknown methods that should be skipped. `data` is
+ the ipywidgets-shaped comm payload; `esm_spec` is minted by the
+ comm itself, never supplied by comm callers.
+
+ `echo_update` is coerced to `ModelUpdate`: marimo has no echo
+ protocol, and dropping echoes would lose frontend-driven trait
+ changes from reconnect replay.
"""
bbuffers = [_ensure_bytes(b) for b in buffers]
method = data.get("method", "update")
@@ -109,12 +131,14 @@ def _create_model_message(
state=state,
buffer_paths=buffer_paths,
buffers=bbuffers,
+ esm_spec=esm_spec,
)
elif method == "update":
return ModelUpdate(
state=state,
buffer_paths=buffer_paths,
buffers=bbuffers,
+ esm_spec=esm_spec,
)
elif method == "custom":
return ModelCustom(
@@ -165,6 +189,17 @@ class MarimoComm:
self.comm_manager = comm_manager
self.target_name = target_name
self.ui_element_id: str | None = None
+
+ # Library-owned callbacks (such as anywidget's file watcher) may send
+ # from a plain background thread, which has no marimo runtime context.
+ # Bind the comm to the session in which it was opened so those sends
+ # retain both their transport and edit/run policy.
+ from marimo._runtime.context import safe_get_context
+ from marimo._runtime.context.utils import get_mode
+
+ ctx = safe_get_context()
+ self._stream: Stream | None = ctx.stream if ctx is not None else None
+ self._mode: RunMode | None = get_mode()
self._open(data=data, buffers=buffers)
def _open(
@@ -172,17 +207,30 @@ class MarimoComm:
data: DataType = None,
buffers: BufferType = None,
) -> None:
- """Open the comm and send initial state."""
+ """Open the comm and send initial state.
+
+ Mints the widget's ESM spec, kept on the comm so repr
+ formatters can reference this model without re-minting.
+ Traditional ipywidgets have no `_esm` and get no spec.
+ """
LOGGER.debug("Opening comm %s", self.comm_id)
- # Stash anywidget ESM info from the open state so it can be
- # looked up later by model_id (used by repr_formatters to
- # produce <marimo-anywidget> HTML).
- state = (data or {}).get("state", {})
+ data = dict(data or {})
+ state = data.get("state", {})
+ self._state_serializer = AnyWidgetStateSerializer(state)
+ state = self._state_serializer.serialize(state)
+ if "state" in data:
+ data["state"] = state
esm = state.get("_esm")
- self.esm: str | None = esm if isinstance(esm, str) and esm else None
+ self.esm_spec: EsmSpec | None = (
+ EsmSpec.from_esm(esm) if isinstance(esm, str) and esm else None
+ )
+ if self.esm_spec is not None:
+ # Code travels only via the spec (see EsmSpec); copy the
+ # state dict since callers may still own it.
+ data["state"] = {k: v for k, v in state.items() if k != "_esm"}
self.comm_manager.register_comm(self)
try:
- self._broadcast(data or {}, buffers or [])
+ self._broadcast(data, buffers or [], esm_spec=self.esm_spec)
self._closed = False
except Exception:
self.comm_manager.unregister_comm(self)
@@ -205,10 +253,27 @@ class MarimoComm:
metadata: MetadataType = None,
buffers: BufferType = None,
) -> None:
- """Send a message to the frontend (state update or custom message)."""
+ """Send a message to the frontend (state update or custom message).
+
+ An `_esm` change (e.g. anywidget's file watcher) becomes a
+ fresh spec on the update in edit sessions (hot reload) and is
+ dropped everywhere else, so a viewer's widget code is immutable.
+ """
del metadata # unused
LOGGER.debug("Sending comm message %s", self.comm_id)
- self._broadcast(data or {}, buffers or [])
+ data = dict(data or {})
+ state = data.get("state")
+ state = self._state_serializer.serialize(state)
+ if "state" in data:
+ data["state"] = state
+ changed_spec: EsmSpec | None = None
+ if isinstance(state, dict) and "_esm" in state:
+ esm = state["_esm"]
+ data["state"] = {k: v for k, v in state.items() if k != "_esm"}
+ if self._mode == "edit" and isinstance(esm, str) and esm:
+ self.esm_spec = EsmSpec.from_esm(esm)
+ changed_spec = self.esm_spec
+ self._broadcast(data, buffers or [], esm_spec=changed_spec)
def close(
self,
@@ -228,7 +293,8 @@ class MarimoComm:
ModelLifecycleNotification(
model_id=self.comm_id,
message=ModelClose(),
- )
+ ),
+ stream=self._stream,
)
if not deleting:
@@ -237,16 +303,22 @@ class MarimoComm:
def __del__(self) -> None:
self.close(deleting=True)
- def _broadcast(self, data: dict[str, Any], buffers: list[Buffer]) -> None:
+ def _broadcast(
+ self,
+ data: dict[str, Any],
+ buffers: list[Buffer],
+ esm_spec: EsmSpec | None = None,
+ ) -> None:
"""Broadcast a model lifecycle notification."""
- message = _create_model_message(data, buffers)
+ message = _create_model_message(data, buffers, esm_spec=esm_spec)
if message is None:
return
broadcast_notification(
ModelLifecycleNotification(
model_id=self.comm_id,
message=message,
- )
+ ),
+ stream=self._stream,
)
# This is the method that ipywidgets.widgets.Widget uses to respond to
diff --git a/marimo/_plugins/ui/_impl/from_anywidget.py b/marimo/_plugins/ui/_impl/from_anywidget.py
index 3ca83ebb8a..287f4e5a21 100644
--- a/marimo/_plugins/ui/_impl/from_anywidget.py
+++ b/marimo/_plugins/ui/_impl/from_anywidget.py
@@ -13,14 +13,15 @@ from typing import (
cast,
)
-import marimo._output.data.data as mo_data
from marimo import _loggers
from marimo._messaging.mimetypes import KnownMimeType
from marimo._output.rich_help import mddoc
from marimo._plugins.ui._core.ui_element import InitializationArgs, UIElement
+from marimo._plugins.ui._impl.anywidget.widget_ref import (
+ AnyWidgetStateSerializer,
+)
from marimo._plugins.ui._impl.comm import MarimoComm
from marimo._types.ids import WidgetModelId
-from marimo._utils.code import hash_code
from marimo._utils.methods import getcallable
AnyWidgetState: TypeAlias = dict[str, Any]
@@ -138,11 +139,20 @@ def get_anywidget_state(widget: AnyWidget) -> AnyWidgetState:
}
state: dict[str, Any] = widget.get_state()
+ serializer = AnyWidgetStateSerializer(state)
# Filter out system traits from the serialized state
# This should include the binary data,
# see marimo/_smoke_tests/issues/2366-anywidget-binary.py
- return {k: v for k, v in state.items() if k not in ignored_traits}
+ filtered = {k: v for k, v in state.items() if k not in ignored_traits}
+
+ # Replace nested AnyWidget values with `anywidget:<model_id>` strings
+ # so the frontend can resolve them via `host.getWidget(ref)`. Children
+ # already have their comms opened (ipywidgets'
+ # `Widget.on_widget_constructed` fires `init_marimo_widget` on
+ # construction), so the frontend has the model registered by the time
+ # the parent's state arrives.
+ return cast(AnyWidgetState, serializer.serialize(filtered))
def get_anywidget_model_id(widget: AnyWidget) -> WidgetModelId:
@@ -190,10 +200,9 @@ class anywidget(UIElement[ModelIdRef, AnyWidgetState]):
# This gets set to True in super().__init__()
self._initialized = False
- js: str = getattr(widget, "_esm", "") # type: ignore [unused-ignore]
- js_hash = hash_code(js)
-
- # Trigger comm initialization early to ensure _model_id is set
+ # Trigger comm initialization early to ensure _model_id is set.
+ # Opening the comm broadcasts the widget's state and its ESM
+ # spec; the component only needs to say which model it displays.
_ = widget.comm
# Get the model_id from the widget (should always be set after comm init)
@@ -205,11 +214,7 @@ class anywidget(UIElement[ModelIdRef, AnyWidgetState]):
component_name="marimo-anywidget",
initial_value=ModelIdRef(model_id=model_id),
label=None,
- args={
- "js-url": mo_data.js(js).url if js else "", # type: ignore [unused-ignore]
- "js-hash": js_hash,
- "model-id": model_id,
- },
+ args={"model-id": model_id},
on_change=None,
)
diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.py
index bd37dce652..a48f13afaa 100644
--- a/marimo/_server/export/exporter.py
+++ b/marimo/_server/export/exporter.py
@@ -34,6 +34,7 @@ from marimo._convert.ipynb.from_ir import (
)
from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.mimetypes import KnownMimeType
+from marimo._messaging.notification import ModelOpen
from marimo._runtime.virtual_file import read_virtual_file
from marimo._schemas.notebook import NotebookV1
from marimo._schemas.session import NotebookSessionV1
@@ -174,9 +175,19 @@ class Exporter:
request.include_code, app_code, notebook_snapshot, session_snapshot
)
- # Build fallback virtual_files dict for files not in HTML outputs
+ # Build fallback virtual_files dict for files not in HTML outputs.
+ # Widget ESM referenced only by model notifications (e.g. a
+ # composed child never displayed on its own) appears in no HTML
+ # output, so the inline pass above cannot see it.
+ model_notifications = session_view.get_model_notifications()
+ esm_urls = [
+ self._normalize_virtual_file_url(n.message.esm_spec.url)
+ for n in model_notifications
+ if isinstance(n.message, ModelOpen)
+ and n.message.esm_spec is not None
+ ]
virtual_files = self._build_virtual_files_dict(
- request.files,
+ [*request.files, *esm_urls],
replaced_files,
max_inline_bytes=MAX_VIRTUAL_FILE_INLINE_BYTES,
)
@@ -195,7 +206,7 @@ class Exporter:
session_snapshot=session_snapshot,
notebook_snapshot=notebook_snapshot,
files=virtual_files,
- model_notifications=session_view.get_model_notifications(),
+ model_notifications=model_notifications,
asset_url=request.asset_url,
)
@@ -343,8 +354,15 @@ class Exporter:
)
continue
- # Process virtual file URLs
- if self._VIRTUAL_FILE_PREFIX_WITH_SLASH not in file_url:
+ # Process virtual file URLs. Export requests use `/@file/`,
+ # while runtime-created virtual files use the relative
+ # `./@file/` form.
+ if not file_url.startswith(
+ (
+ self._VIRTUAL_FILE_PREFIX_WITH_SLASH,
+ self._VIRTUAL_FILE_PATTERN,
+ )
+ ):
continue
data_uri = self._read_virtual_file_as_data_uri(
@@ -363,17 +381,24 @@ class Exporter:
"""Read a virtual file and convert it to a data URI.
Args:
- file_url: Virtual file URL in format /@file/{byte_length}-{filename}
+ file_url: Virtual file URL in `/@file/{byte_length}-{filename}`
+ or `./@file/{byte_length}-{filename}` format.
max_inline_bytes: Maximum file size in bytes to inline.
Files larger than this are skipped. None means no limit.
Returns:
Data URI string, or None if file cannot be read
"""
- # Extract byte_length and filename from URL
- # Format: /@file/{byte_length}-{filename}
- prefix_len = len(self._VIRTUAL_FILE_PREFIX_WITH_SLASH)
- virtual_file = file_url[prefix_len:]
+ # Extract byte_length and filename from either URL form.
+ if file_url.startswith(self._VIRTUAL_FILE_PATTERN):
+ virtual_file = file_url[len(self._VIRTUAL_FILE_PATTERN) :]
+ elif file_url.startswith(self._VIRTUAL_FILE_PREFIX_WITH_SLASH):
+ virtual_file = file_url[
+ len(self._VIRTUAL_FILE_PREFIX_WITH_SLASH) :
+ ]
+ else:
+ LOGGER.warning("Invalid virtual file URL in export: %s", file_url)
+ return None
try:
byte_length_str, basename = virtual_file.split("-", 1)
diff --git a/marimo/_session/state/session_view.py b/marimo/_session/state/session_view.py
index 894b00483e..780dd7b402 100644
--- a/marimo/_session/state/session_view.py
+++ b/marimo/_session/state/session_view.py
@@ -15,6 +15,7 @@ from marimo._messaging.notification import (
CellNotification,
DatasetsNotification,
DataSourceConnectionsNotification,
+ EsmSpec,
InstallingPackageAlertNotification,
InterruptedNotification,
ModelClose,
@@ -72,6 +73,7 @@ class ModelReplayState:
model_id: WidgetModelId
state: dict[str, Any]
buffers: dict[BufferPath, bytes]
+ esm_spec: EsmSpec | None = None
@staticmethod
def from_open(model_id: WidgetModelId, msg: ModelOpen) -> ModelReplayState:
@@ -83,6 +85,7 @@ class ModelReplayState:
model_id=model_id,
state=dict(msg.state),
buffers=buffers,
+ esm_spec=msg.esm_spec,
)
def apply_update(self, msg: ModelUpdate) -> None:
@@ -98,6 +101,10 @@ class ModelReplayState:
self.state.update(msg.state)
for path, buf in zip(msg.buffer_paths, msg.buffers, strict=False):
self.buffers[tuple(path)] = buf
+ # A spec on an update is a hot reload; late joiners must replay
+ # the current code, not the original open's.
+ if msg.esm_spec is not None:
+ self.esm_spec = msg.esm_spec
def to_notification(self) -> ModelLifecycleNotification:
paths = list(self.buffers.keys())
@@ -108,6 +115,7 @@ class ModelReplayState:
state=dict(self.state),
buffer_paths=[list(p) for p in paths],
buffers=bufs,
+ esm_spec=self.esm_spec,
),
)
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index 8b118dfedb..cac0fa362c 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -1513,6 +1513,25 @@ components:
- theme
title: DisplayConfig
type: object
+ EsmSpec:
+ description: "Where the frontend imports a widget's ESM from, and which version.\n\
+ \n Specs travel only on kernel-authored notifications, never in model\n\
+ \ state: state is client-writable and echoed to peers, so executing\n \
+ \ code from it would let one client run code on another.\n\n Attributes:\n\
+ \ url: URL to import the ESM from. A virtual file for inline\n \
+ \ source; an external URL when `_esm` is itself a URL.\n hash:\
+ \ Hash of the `_esm` string. Keys the frontend module cache\n and\
+ \ signals code changes (hot reload)."
+ properties:
+ hash:
+ type: string
+ url:
+ type: string
+ required:
+ - url
+ - hash
+ title: EsmSpec
+ type: object
ExecuteCellCommand:
description: "Execute a single cell.\n\n Executes a cell with the provided\
\ code. Dependent cells may be\n re-executed based on the reactive execution\
@@ -3591,7 +3610,14 @@ components:
title: ModelLifecycleNotification
type: object
ModelOpen:
- description: Initial widget state on creation.
+ description: "Initial widget state on creation.\n\n For anywidgets, the widget's\
+ \ ESM does not travel in `state`: the\n comm strips `_esm` and sends an\
+ \ `EsmSpec` instead. `None` for\n models with no ESM (e.g. traditional\
+ \ ipywidgets).\n\n Attributes:\n state: Initial trait values, minus\
+ \ `_esm`.\n buffer_paths: Paths into `state` whose binary values were\n\
+ \ extracted into `buffers`.\n buffers: Binary payloads,\
+ \ parallel to `buffer_paths`.\n esm_spec: Where to import this widget's\
+ \ ESM from."
properties:
buffer_paths:
items:
@@ -3605,6 +3631,11 @@ components:
items:
$ref: '#/components/schemas/Base64String'
type: array
+ esm_spec:
+ anyOf:
+ - type: 'null'
+ - $ref: '#/components/schemas/EsmSpec'
+ default: null
method:
enum:
- open
@@ -3643,7 +3674,14 @@ components:
title: ModelRequest
type: object
ModelUpdate:
- description: State sync - changed traits only.
+ description: "State sync - changed traits only.\n\n Attributes:\n \
+ \ state: Changed trait values, minus `_esm` (see `ModelOpen`).\n buffer_paths:\
+ \ Paths into `state` whose binary values were\n extracted into\
+ \ `buffers`.\n buffers: Binary payloads, parallel to `buffer_paths`.\n\
+ \ esm_spec: Present only when the widget's `_esm` changed on a\n \
+ \ live model (hot reload, edit mode only). A spec whose\n \
+ \ `hash` differs from the current one tells the frontend the\n \
+ \ widget's code changed and views must be rebuilt."
properties:
buffer_paths:
items:
@@ -3657,6 +3695,11 @@ components:
items:
$ref: '#/components/schemas/Base64String'
type: array
+ esm_spec:
+ anyOf:
+ - type: 'null'
+ - $ref: '#/components/schemas/EsmSpec'
+ default: null
method:
enum:
- update
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index 7812a6d95c..82659a5519 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -4366,6 +4366,24 @@ export interface components {
/** @enum {unknown} */
theme: "dark" | "light" | "system";
};
+ /**
+ * EsmSpec
+ * @description Where the frontend imports a widget's ESM from, and which version.
+ *
+ * Specs travel only on kernel-authored notifications, never in model
+ * state: state is client-writable and echoed to peers, so executing
+ * code from it would let one client run code on another.
+ *
+ * Attributes:
+ * url: URL to import the ESM from. A virtual file for inline
+ * source; an external URL when `_esm` is itself a URL.
+ * hash: Hash of the `_esm` string. Keys the frontend module cache
+ * and signals code changes (hot reload).
+ */
+ EsmSpec: {
+ hash: string;
+ url: string;
+ };
/**
* ExecuteCellCommand
* @description Execute a single cell.
@@ -5614,10 +5632,23 @@ export interface components {
/**
* ModelOpen
* @description Initial widget state on creation.
+ *
+ * For anywidgets, the widget's ESM does not travel in `state`: the
+ * comm strips `_esm` and sends an `EsmSpec` instead. `None` for
+ * models with no ESM (e.g. traditional ipywidgets).
+ *
+ * Attributes:
+ * state: Initial trait values, minus `_esm`.
+ * buffer_paths: Paths into `state` whose binary values were
+ * extracted into `buffers`.
+ * buffers: Binary payloads, parallel to `buffer_paths`.
+ * esm_spec: Where to import this widget's ESM from.
*/
ModelOpen: {
buffer_paths: (string | number)[][];
buffers: components["schemas"]["Base64String"][];
+ /** @default null */
+ esm_spec?: null | components["schemas"]["EsmSpec"];
/** @enum {unknown} */
method: "open";
state: Record<string, any>;
@@ -5634,10 +5665,22 @@ export interface components {
/**
* ModelUpdate
* @description State sync - changed traits only.
+ *
+ * Attributes:
+ * state: Changed trait values, minus `_esm` (see `ModelOpen`).
+ * buffer_paths: Paths into `state` whose binary values were
+ * extracted into `buffers`.
+ * buffers: Binary payloads, parallel to `buffer_paths`.
+ * esm_spec: Present only when the widget's `_esm` changed on a
+ * live model (hot reload, edit mode only). A spec whose
+ * `hash` differs from the current one tells the frontend the
+ * widget's code changed and views must be rebuilt.
*/
ModelUpdate: {
buffer_paths: (string | number)[][];
buffers: components["schemas"]["Base64String"][];
+ /** @default null */
+ esm_spec?: null | components["schemas"]["EsmSpec"];
/** @enum {unknown} */
method: "update";
state: Record<string, any>;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c1c823d1ca..c95b69c8d5 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -41,8 +41,8 @@ importers:
specifier: ^3.0.134
'@anywidget/types':
- specifier: ^0.2.0
- version: 0.2.0
+ specifier: ^0.4.0
+ version: 0.4.0
'@codemirror/autocomplete':
specifier: ^6.20.1
version: 6.20.1
@@ -747,8 +747,8 @@ packages:
resolution: {integrity: sha512-Oq1d9BGZakE/FyoEtcNeSwM7MpDO2vUBi11RWBZXf75zPsbUVWmUs03EqkRFrcgbXyKTas0BdZWC1wcuSoqSAw==}
- '@anywidget/[email protected]':
- resolution: {integrity: sha512-+XtK4uwxRd4JpuevUMhirrbvC0V4yCA/i0lEjhmSAtOaxiXIg/vBKzaSonDuoZ1a9LEjUXTW2+m7w+ULgsJYvg==}
+ '@anywidget/[email protected]':
+ resolution: {integrity: sha512-Qno/7V0lKHCMq3DJuSKKHMwilFKPSe8wFftL5xWmgaMCc938mNTtv+i19UrvDfpj9cQTnlPqyXy8t3JOgQ8laA==}
'@asamuzakjp/[email protected]':
resolution: {integrity: sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==}
@@ -9909,7 +9909,7 @@ snapshots:
'@antfu/[email protected]': {}
- '@anywidget/[email protected]': {}
+ '@anywidget/[email protected]': {}
'@asamuzakjp/[email protected]':
dependencies:
diff --git a/tests/_plugins/ui/_impl/anywidget/test_comm_provider.py b/tests/_plugins/ui/_impl/anywidget/test_comm_provider.py
index 96551a905b..cd0484080f 100644
--- a/tests/_plugins/ui/_impl/anywidget/test_comm_provider.py
+++ b/tests/_plugins/ui/_impl/anywidget/test_comm_provider.py
@@ -48,7 +48,12 @@ class TestPatchCommCreate:
},
)
assert isinstance(c, MarimoComm)
- assert c.esm == "export default {}"
+ # The comm mints the ESM spec at open (used later by repr
+ # formatters); the raw source itself is not kept.
+ from marimo._utils.code import hash_code
+
+ assert c.esm_spec is not None
+ assert c.esm_spec.hash == hash_code("export default {}")
c.close()
finally:
comm.create_comm = original
diff --git a/tests/_plugins/ui/_impl/test_anywidget.py b/tests/_plugins/ui/_impl/test_anywidget.py
index 45e9d4f370..4b569e4b3c 100644
--- a/tests/_plugins/ui/_impl/test_anywidget.py
+++ b/tests/_plugins/ui/_impl/test_anywidget.py
@@ -3,12 +3,12 @@ from __future__ import annotations
import gc
import weakref
-from hashlib import md5
import pytest
from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins.ui._core.ui_element import UIElement
+from marimo._plugins.ui._impl.comm import MarimoComm
from marimo._plugins.ui._impl.from_anywidget import (
WeakCache,
anywidget,
@@ -22,6 +22,7 @@ from marimo._runtime.commands import (
)
from marimo._runtime.runtime import Kernel
from marimo._types.ids import WidgetModelId
+from marimo._utils.code import hash_code
from tests.conftest import ExecReqProvider
HAS_DEPS = (
@@ -201,10 +202,8 @@ x = as_marimo_element.count
assert "model_id" in wrapped._initial_value_frontend
assert len(wrapped._initial_value_frontend) == 1
assert isinstance(wrapped._initial_value_frontend["model_id"], str)
- assert wrapped._component_args["js-url"] == ""
- assert wrapped._component_args["js-hash"] == md5(b"").hexdigest()
assert isinstance(wrapped._component_args["model-id"], str)
- assert len(wrapped._component_args) == 3
+ assert len(wrapped._component_args) == 1
@staticmethod
async def test_initialization_with_dataview() -> None:
@@ -216,10 +215,8 @@ x = as_marimo_element.count
assert "model_id" in wrapped._initial_value_frontend
assert len(wrapped._initial_value_frontend) == 1
assert isinstance(wrapped._initial_value_frontend["model_id"], str)
- assert wrapped._component_args["js-url"] == ""
- assert wrapped._component_args["js-hash"] == md5(b"").hexdigest()
assert isinstance(wrapped._component_args["model-id"], str)
- assert len(wrapped._component_args) == 3
+ assert len(wrapped._component_args) == 1
@staticmethod
async def test_custom_methods_and_attributes() -> None:
@@ -355,23 +352,29 @@ x = as_marimo_element.count
assert "css" not in wrapped._component_args
@staticmethod
- async def test_js_hash() -> None:
+ async def test_esm_spec_hash() -> None:
+ # The component no longer carries the code hash; it lives on
+ # the ESM spec the comm minted at open.
class JSWidget(_anywidget.AnyWidget):
_esm = ""
value = traitlets.Int(0).tag(sync=True)
wrapped = anywidget(JSWidget())
- assert wrapped._component_args["js-hash"] == md5(b"").hexdigest()
+ assert "js-hash" not in wrapped._component_args
+ comm = wrapped.widget.comm
+ assert isinstance(comm, MarimoComm)
+ # An empty `_esm` mints no spec at all.
+ assert comm.esm_spec is None
class JSWidget2(_anywidget.AnyWidget):
_esm = "function render({ model, el }) { el.innerHTML = 'hello'; }"
value = traitlets.Int(0).tag(sync=True)
wrapped2 = anywidget(JSWidget2())
- assert (
- wrapped2._component_args["js-hash"]
- != wrapped._component_args["js-hash"]
- )
+ comm2 = wrapped2.widget.comm
+ assert isinstance(comm2, MarimoComm)
+ assert comm2.esm_spec is not None
+ assert comm2.esm_spec.hash == hash_code(JSWidget2._esm)
@staticmethod
def test_state_merging() -> None:
@@ -506,6 +509,119 @@ x = as_marimo_element.count
assert "_model_module" not in state
assert "_view_name" not in state
+ @staticmethod
+ async def test_nested_widget_serializes_as_anywidget_ref() -> None:
+ """A widget-valued trait should produce `anywidget:<id>` on the wire.
+
+ Composition (RFC 0001): the parent's frontend `render` calls
+ `host.getWidget(model.get("child"))` which expects this format.
+ """
+
+ class Child(_anywidget.AnyWidget):
+ _esm = "export default { render() {} }"
+ value = traitlets.Int(0).tag(sync=True)
+
+ class Parent(_anywidget.AnyWidget):
+ _esm = "export default { render() {} }"
+ child = traitlets.Instance(Child, allow_none=True).tag(sync=True)
+
+ child = Child(value=7)
+ parent = Parent(child=child)
+
+ state = get_anywidget_state(parent)
+ assert state["child"] == f"anywidget:{child._model_id}"
+
+ @staticmethod
+ async def test_nested_widget_in_dict_serializes_as_ref() -> None:
+ class Child(_anywidget.AnyWidget):
+ _esm = "export default { render() {} }"
+
+ class Parent(_anywidget.AnyWidget):
+ _esm = "export default { render() {} }"
+ # Avoid the name `layout` — it's a reserved ipywidgets system
+ # trait that `get_anywidget_state` filters out.
+ slots = traitlets.Dict().tag(sync=True)
+
+ left = Child()
+ right = Child()
+ parent = Parent(slots={"left": left, "right": right, "gap": 8})
+
+ state = get_anywidget_state(parent)
+ assert state["slots"] == {
+ "left": f"anywidget:{left._model_id}",
+ "right": f"anywidget:{right._model_id}",
+ "gap": 8,
+ }
+
+ @staticmethod
+ async def test_nested_widget_in_list_serializes_as_ref() -> None:
+ class Child(_anywidget.AnyWidget):
+ _esm = "export default { render() {} }"
+
+ class Parent(_anywidget.AnyWidget):
+ _esm = "export default { render() {} }"
+ items = traitlets.List().tag(sync=True)
+
+ c1 = Child()
+ c2 = Child()
+ parent = Parent(items=[c1, "spacer", c2])
+
+ state = get_anywidget_state(parent)
+ assert state["items"] == [
+ f"anywidget:{c1._model_id}",
+ "spacer",
+ f"anywidget:{c2._model_id}",
+ ]
+
+ @staticmethod
+ async def test_state_without_widgets_passes_through() -> None:
+ """Walker should not change values when nothing is a widget."""
+
+ class Plain(_anywidget.AnyWidget):
+ _esm = "export default { render() {} }"
+ data = traitlets.Dict().tag(sync=True)
+
+ widget = Plain(data={"a": 1, "b": [2, 3], "c": {"d": "x"}})
+ state = get_anywidget_state(widget)
+ assert state["data"] == {"a": 1, "b": [2, 3], "c": {"d": "x"}}
+
+ @staticmethod
+ async def test_protocol_widget_serializes_as_anywidget_ref() -> None:
+ """RFC 0001 protocol widgets — plain classes with a
+ `MimeBundleDescriptor` for `_repr_mimebundle_` — should be detected
+ and serialized the same way as ipywidgets-derived AnyWidget."""
+ from dataclasses import dataclass
+
+ from anywidget._descriptor import MimeBundleDescriptor
+
+ @dataclass
+ class ProtocolChild:
+ value: int = 0
+ # Dataclass autodetect lets the descriptor expose `value` as
+ # synced state without a manual `_get_anywidget_state` method.
+ _repr_mimebundle_ = MimeBundleDescriptor(_esm="")
+
+ class Parent(_anywidget.AnyWidget):
+ _esm = "export default { render() {} }"
+ child = traitlets.Any(allow_none=True).tag(sync=True)
+
+ protocol_child = ProtocolChild(value=7)
+ # Important: do NOT touch `_repr_mimebundle_` first — the walker
+ # must trigger comm creation itself. Otherwise the test isn't
+ # exercising the lazy-init path that protocol widgets rely on.
+ parent = Parent(child=protocol_child)
+ state = get_anywidget_state(parent)
+
+ ref = state["child"]
+ assert isinstance(ref, str)
+ assert ref.startswith("anywidget:")
+ # The id baked into the ref should match the live bundle's id.
+ # `model_id` lands on `ReprMimeBundle` in anywidget>=0.11; older
+ # versions only expose the underlying comm.
+ bundle = protocol_child._repr_mimebundle_
+ expected_id = getattr(bundle, "model_id", None) or bundle._comm.comm_id
+ assert ref == f"anywidget:{expected_id}"
+
@staticmethod
async def test_partial_state_updates() -> None:
class MultiTraitWidget(_anywidget.AnyWidget):
diff --git a/tests/_plugins/ui/_impl/test_comm.py b/tests/_plugins/ui/_impl/test_comm.py
index 479bb37e5f..31f0102b20 100644
--- a/tests/_plugins/ui/_impl/test_comm.py
+++ b/tests/_plugins/ui/_impl/test_comm.py
@@ -1,11 +1,16 @@
from __future__ import annotations
import sys
+import threading
+from dataclasses import dataclass
from unittest.mock import MagicMock, patch
import pytest
from marimo._plugins.ui._impl.anywidget.init import CommLifecycleItem
+from marimo._plugins.ui._impl.anywidget.widget_ref import (
+ AnyWidgetStateSerializer,
+)
from marimo._plugins.ui._impl.comm import (
MarimoComm,
MarimoCommManager,
@@ -78,14 +83,18 @@ def test_comm_initialization(comm: MarimoComm):
def test_comm_open(comm: MarimoComm):
with patch.object(comm, "_broadcast") as mock_broadcast:
comm.open(data={"test": "data"})
- mock_broadcast.assert_called_once_with({"test": "data"}, [])
+ mock_broadcast.assert_called_once_with(
+ {"test": "data"}, [], esm_spec=None
+ )
assert not comm._closed
def test_comm_send(comm: MarimoComm):
with patch.object(comm, "_broadcast") as mock_broadcast:
comm.send(data={"test": "data"})
- mock_broadcast.assert_called_once_with({"test": "data"}, [])
+ mock_broadcast.assert_called_once_with(
+ {"test": "data"}, [], esm_spec=None
+ )
def test_comm_close(comm: MarimoComm):
@@ -303,6 +312,205 @@ class TestBroadcastBufferTypes:
_ensure_bytes("not bytes")
+class TestEsmSpecMinting:
+ """`_open` mints the ESM spec — the only channel widget code takes
+ to the frontend."""
+
+ ESM = "export default { render({ model, el }) {} }"
+
+ def _open_comm(self, comm_manager, state):
+ """Open a comm with `state` and return (comm, broadcast message)."""
+ with patch(
+ "marimo._plugins.ui._impl.comm.broadcast_notification"
+ ) as mock_broadcast:
+ comm = MarimoComm(
+ comm_id=WidgetModelId("esm-test"),
+ comm_manager=comm_manager,
+ target_name="jupyter.widget",
+ data={"state": state, "buffer_paths": [], "method": "open"},
+ )
+ notification = mock_broadcast.call_args[0][0]
+ # Prevent __del__ from broadcasting outside the patch scope.
+ comm._closed = True
+ return comm, notification.message
+
+ def test_inline_esm_is_minted_and_stripped(self, comm_manager):
+ from marimo._utils.code import hash_code
+
+ state = {"_esm": self.ESM, "count": 1}
+ comm, message = self._open_comm(comm_manager, state)
+
+ assert message.esm_spec is not None
+ # Without a runtime context, virtual files degrade to data URLs
+ # (see VirtualFile.create_and_register); in a live kernel this
+ # is a ./@file/ URL instead. Either way it is importable.
+ assert message.esm_spec.url.startswith("data:")
+ assert message.esm_spec.hash == hash_code(self.ESM)
+ # Code must not travel in state; everything else must.
+ assert "_esm" not in message.state
+ assert message.state["count"] == 1
+ # The comm keeps the spec for repr formatters.
+ assert comm.esm_spec == message.esm_spec
+
+ def test_url_form_esm_passes_through(self, comm_manager):
+ from marimo._utils.code import hash_code
+
+ url = "https://esm.sh/[email protected]"
+ _, message = self._open_comm(comm_manager, {"_esm": url})
+
+ assert message.esm_spec is not None
+ assert message.esm_spec.url == url
+ assert message.esm_spec.hash == hash_code(url)
+
+ def test_no_esm_means_no_spec(self, comm_manager):
+ comm, message = self._open_comm(comm_manager, {"value": 5})
+
+ assert message.esm_spec is None
+ assert comm.esm_spec is None
+ assert message.state == {"value": 5}
+
+ def test_empty_esm_means_no_spec(self, comm_manager):
+ _, message = self._open_comm(comm_manager, {"_esm": ""})
+ assert message.esm_spec is None
+
+ def test_caller_state_is_not_mutated(self, comm_manager):
+ # ipywidgets may still own the state dict it hands to open();
+ # stripping must happen on a copy.
+ state = {"_esm": self.ESM, "count": 1}
+ self._open_comm(comm_manager, state)
+ assert state["_esm"] == self.ESM
+
+ def test_spec_survives_serde_roundtrip(self, comm_manager):
+ from marimo._messaging.serde import (
+ deserialize_kernel_message,
+ serialize_kernel_message,
+ )
+
+ with patch(
+ "marimo._plugins.ui._impl.comm.broadcast_notification"
+ ) as mock_broadcast:
+ comm = MarimoComm(
+ comm_id=WidgetModelId("esm-roundtrip"),
+ comm_manager=comm_manager,
+ target_name="jupyter.widget",
+ data={
+ "state": {"_esm": self.ESM},
+ "buffer_paths": [],
+ "method": "open",
+ },
+ )
+ notification = mock_broadcast.call_args[0][0]
+ comm._closed = True
+
+ result = deserialize_kernel_message(
+ serialize_kernel_message(notification)
+ )
+ assert result.message.esm_spec == notification.message.esm_spec
+
+
+@dataclass(frozen=True)
+class _ModelIdWidget:
+ """Minimal ipywidgets-backed anywidget shape for wire transport tests."""
+
+ model_id: str
+
+
+class TestAnywidgetWireReferences:
+ ESM = "export default { render() {} }"
+
+ def test_plain_state_does_not_import_optional_anywidget(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ for module_name in list(sys.modules):
+ if module_name == "anywidget" or module_name.startswith(
+ "anywidget."
+ ):
+ monkeypatch.delitem(sys.modules, module_name)
+
+ serializer = AnyWidgetStateSerializer({"_esm": self.ESM})
+ state = {"count": 1, "label": "counter"}
+
+ assert serializer.serialize(state) is state
+ assert "anywidget" not in sys.modules
+
+ def test_model_open_replaces_direct_and_nested_widget_refs(
+ self, comm_manager: MarimoCommManager
+ ) -> None:
+ from marimo._messaging.serde import (
+ deserialize_kernel_message,
+ serialize_kernel_message,
+ )
+
+ child = _ModelIdWidget("child-open")
+ with patch(
+ "marimo._plugins.ui._impl.comm.broadcast_notification"
+ ) as mock_broadcast:
+ comm = MarimoComm(
+ comm_id=WidgetModelId("parent-open"),
+ comm_manager=comm_manager,
+ target_name="jupyter.widget",
+ data={
+ "state": {
+ "_esm": self.ESM,
+ "child": child,
+ "layout": {"items": [child, {"nested": child}]},
+ },
+ "buffer_paths": [],
+ "method": "open",
+ },
+ )
+ notification = mock_broadcast.call_args[0][0]
+ comm._closed = True
+
+ expected_state = {
+ "child": "anywidget:child-open",
+ "layout": {
+ "items": [
+ "anywidget:child-open",
+ {"nested": "anywidget:child-open"},
+ ]
+ },
+ }
+ assert notification.message.state == expected_state
+
+ roundtripped = deserialize_kernel_message(
+ serialize_kernel_message(notification)
+ )
+ assert roundtripped.message.state == expected_state
+
+ def test_model_update_replaces_reassigned_widget_ref(
+ self, comm_manager: MarimoCommManager
+ ) -> None:
+ replacement = _ModelIdWidget("child-update")
+ with patch(
+ "marimo._plugins.ui._impl.comm.broadcast_notification"
+ ) as mock_broadcast:
+ comm = MarimoComm(
+ comm_id=WidgetModelId("parent-update"),
+ comm_manager=comm_manager,
+ target_name="jupyter.widget",
+ data={
+ "state": {"_esm": self.ESM},
+ "buffer_paths": [],
+ "method": "open",
+ },
+ )
+ mock_broadcast.reset_mock()
+ comm.send(
+ data={
+ "state": {"child": replacement},
+ "buffer_paths": [],
+ "method": "update",
+ }
+ )
+ notification = mock_broadcast.call_args[0][0]
+ comm._closed = True
+
+ assert notification.message.state == {
+ "child": "anywidget:child-update"
+ }
+
+
def test_comm_lifecycle_item_dispose_idempotent(comm: MarimoComm):
"""Calling dispose twice should not error (comm.close is idempotent)."""
item = CommLifecycleItem(comm)
@@ -314,3 +522,156 @@ def test_comm_lifecycle_item_dispose_idempotent(comm: MarimoComm):
assert result is True
assert comm._closed
+
+
+class TestEsmHotReload:
+ """`send` intercepts `_esm` in updates: a code change on a live
+ model becomes a fresh spec in edit sessions and is dropped
+ everywhere else."""
+
+ ESM_V2 = "export default { render({ model, el }) { /* v2 */ } }"
+
+ def _send_update(self, comm_manager, mode):
+ with patch(
+ "marimo._plugins.ui._impl.comm.broadcast_notification"
+ ) as mock_broadcast:
+ with patch(
+ "marimo._runtime.context.utils.get_mode", return_value=mode
+ ):
+ comm = MarimoComm(
+ comm_id=WidgetModelId("hmr-test"),
+ comm_manager=comm_manager,
+ target_name="jupyter.widget",
+ data={
+ "state": {"_esm": "export default {}"},
+ "buffer_paths": [],
+ "method": "open",
+ },
+ )
+ comm.send(
+ data={
+ "state": {"_esm": self.ESM_V2, "count": 1},
+ "buffer_paths": [],
+ "method": "update",
+ }
+ )
+ update = mock_broadcast.call_args[0][0].message
+ comm._closed = True
+ return comm, update
+
+ def test_edit_mode_mints_new_spec(self, comm_manager):
+ from marimo._utils.code import hash_code
+
+ comm, update = self._send_update(comm_manager, "edit")
+ assert "_esm" not in update.state
+ assert update.state["count"] == 1
+ assert update.esm_spec is not None
+ assert update.esm_spec.hash == hash_code(self.ESM_V2)
+ # The comm's spec follows the live code so late repr formatters
+ # and replay see the current generation.
+ assert comm.esm_spec == update.esm_spec
+
+ def test_run_mode_drops_code_entirely(self, comm_manager):
+ from marimo._utils.code import hash_code
+
+ comm, update = self._send_update(comm_manager, "run")
+ assert "_esm" not in update.state
+ assert update.state["count"] == 1
+ # Viewers' widget code is immutable for the model's lifetime.
+ assert update.esm_spec is None
+ assert comm.esm_spec is not None
+ assert comm.esm_spec.hash == hash_code("export default {}")
+
+ def test_plain_thread_send_uses_creation_session(
+ self, executing_kernel, comm_manager
+ ):
+ """A library-owned watcher thread keeps the comm's mode and stream."""
+ from marimo._messaging.notification import (
+ ModelLifecycleNotification,
+ ModelUpdate,
+ )
+ from marimo._utils.code import hash_code
+
+ comm = MarimoComm(
+ comm_id=WidgetModelId("thread-hmr-test"),
+ comm_manager=comm_manager,
+ target_name="jupyter.widget",
+ data={
+ "state": {"_esm": "export default {}", "_css": ""},
+ "buffer_paths": [],
+ "method": "open",
+ },
+ )
+ stream = executing_kernel.stream
+ stream.messages.clear()
+ errors: list[BaseException] = []
+
+ def send_update() -> None:
+ try:
+ comm.send(
+ data={
+ "state": {
+ "_esm": self.ESM_V2,
+ "_css": "button { color: hotpink; }",
+ },
+ "buffer_paths": [],
+ "method": "update",
+ }
+ )
+ except BaseException as exc:
+ errors.append(exc)
+
+ watcher = threading.Thread(target=send_update)
+ watcher.start()
+ watcher.join(timeout=1)
+
+ assert not watcher.is_alive()
+ assert not errors
+ assert len(stream.operations) == 1
+ notification = stream.operations[0]
+ assert isinstance(notification, ModelLifecycleNotification)
+ assert isinstance(notification.message, ModelUpdate)
+ assert notification.message.state == {
+ "_css": "button { color: hotpink; }"
+ }
+ assert notification.message.esm_spec is not None
+ assert notification.message.esm_spec.hash == hash_code(self.ESM_V2)
+ # The callback thread intentionally does not inherit the mutable
+ # runtime context; inline HMR modules therefore use the supported
+ # data-URL transport instead of touching the virtual-file registry.
+ assert notification.message.esm_spec.url.startswith("data:")
+ comm.close()
+
+
+class TestClientUpdateStrip:
+ """Clients may write widget state, never widget code or style."""
+
+ def test_strips_esm_and_css_from_client_updates(
+ self, comm_manager, comm: MarimoComm
+ ):
+ received: list[dict] = []
+ comm.on_msg(received.append)
+ comm.ui_element_id = "el-1"
+
+ command = ModelCommand(
+ model_id=comm.comm_id,
+ message=ModelUpdateMessage(
+ state={
+ "_esm": "alert('pwned')",
+ "_css": "body { display: none }",
+ "count": 2,
+ },
+ buffer_paths=[],
+ ),
+ buffers=[],
+ )
+ ui_element_id, state = comm_manager.receive_comm_message(command)
+
+ assert ui_element_id == "el-1"
+ assert state == {"count": 2}
+ # The comm callback (ipywidgets set_state) never sees them
+ # either — otherwise the kernel would echo them back to peers.
+ payload_state = received[0]["content"]["data"]["state"]
+ assert "_esm" not in payload_state
+ assert "_css" not in payload_state
+ assert payload_state["count"] == 2
diff --git a/tests/_server/export/test_exporter.py b/tests/_server/export/test_exporter.py
index ebacfc8543..f51f2e0672 100644
--- a/tests/_server/export/test_exporter.py
+++ b/tests/_server/export/test_exporter.py
@@ -19,7 +19,12 @@ from marimo._dependencies.dependencies import Dependency, DependencyManager
from marimo._dependencies.errors import ManyModulesNotFoundError
from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._messaging.msgspec_encoder import encode_json_str
-from marimo._messaging.notification import CellNotification
+from marimo._messaging.notification import (
+ CellNotification,
+ EsmSpec,
+ ModelLifecycleNotification,
+ ModelOpen,
+)
from marimo._server.export import (
export_as_md,
export_as_wasm,
@@ -34,6 +39,7 @@ from marimo._server.models.export import ExportAsHTMLRequest
from marimo._session.notebook import AppFileManager
from marimo._session.state.serialize import get_session_cache_file
from marimo._session.state.session_view import SessionView
+from marimo._types.ids import WidgetModelId
from marimo._utils.marimo_path import MarimoPath
from tests.mocks import delete_lines_with_files, snapshotter
@@ -516,6 +522,60 @@ def test_export_as_html_with_files(session_view: SessionView) -> None:
assert "data:" in html
+def test_export_as_html_includes_composed_widget_esm(
+ session_view: SessionView,
+) -> None:
+ """A composed-only widget's ESM is embedded in standalone HTML."""
+ app = App()
+
+ @app.cell()
+ def parent_cell():
+ return "parent"
+
+ file_manager = AppFileManager.from_app(InternalApp(app))
+ cell_id = next(iter(file_manager.app.cell_manager.cell_ids()))
+ session_view.cell_notifications[cell_id] = CellNotification(
+ cell_id=cell_id,
+ status="idle",
+ output=None,
+ console=[],
+ timestamp=0,
+ )
+ session_view.last_executed_code[cell_id] = "return 'parent'"
+
+ widget_code = b"export default { render() {} }"
+ widget_url = f"./@file/{len(widget_code)}-child-widget.js"
+ session_view.add_notification(
+ ModelLifecycleNotification(
+ model_id=WidgetModelId("child-widget"),
+ message=ModelOpen(
+ state={},
+ buffer_paths=[],
+ buffers=[],
+ esm_spec=EsmSpec(url=widget_url, hash="child-hash"),
+ ),
+ )
+ )
+
+ with patch(
+ "marimo._server.export.exporter.read_virtual_file",
+ return_value=widget_code,
+ ):
+ html, _filename = Exporter().export_as_html(
+ filename=file_manager.filename,
+ app=file_manager.app,
+ session_view=session_view,
+ display_config=DEFAULT_CONFIG["display"],
+ request=ExportAsHTMLRequest(
+ download=True,
+ files=[],
+ include_code=True,
+ ),
+ )
+
+ assert base64.b64encode(widget_code).decode("ascii") in html
+
+
def test_export_as_html_with_cell_configs(session_view: SessionView) -> None:
"""Test HTML export preserves cell configurations through serialization."""
diff --git a/tests/_session/state/test_session_view.py b/tests/_session/state/test_session_view.py
index aed92ad19b..d9b3f0e259 100644
--- a/tests/_session/state/test_session_view.py
+++ b/tests/_session/state/test_session_view.py
@@ -21,6 +21,7 @@ from marimo._messaging.notification import (
CellNotification,
DatasetsNotification,
DataSourceConnectionsNotification,
+ EsmSpec,
InstallingPackageAlertNotification,
ModelClose,
ModelCustom,
@@ -427,6 +428,56 @@ class TestModelReplayState:
)
assert view.state == {"a": 1, "b": 99, "c": 3}
+ def test_esm_spec_round_trips(self) -> None:
+ """Late joiners must receive the spec from the original open."""
+ spec = EsmSpec(url="./@file/10-w.js", hash="abc123")
+ view = ModelReplayState.from_open(
+ WidgetModelId("m"),
+ ModelOpen(
+ state={"count": 1},
+ buffer_paths=[],
+ buffers=[],
+ esm_spec=spec,
+ ),
+ )
+ assert view.esm_spec == spec
+ assert view.to_notification().message.esm_spec == spec
+
+ def test_apply_update_preserves_spec_by_default(self) -> None:
+ """Ordinary state updates carry no spec and must not clear it."""
+ spec = EsmSpec(url="./@file/10-w.js", hash="abc123")
+ view = ModelReplayState(
+ model_id=WidgetModelId("m"),
+ state={"count": 1},
+ buffers={},
+ esm_spec=spec,
+ )
+ view.apply_update(
+ ModelUpdate(state={"count": 2}, buffer_paths=[], buffers=[])
+ )
+ assert view.esm_spec == spec
+
+ def test_apply_update_with_spec_replaces_it(self) -> None:
+ """A spec on an update is an edit-mode hot reload; late joiners
+ must replay the new code, not the original open's."""
+ view = ModelReplayState(
+ model_id=WidgetModelId("m"),
+ state={},
+ buffers={},
+ esm_spec=EsmSpec(url="./@file/10-old.js", hash="old"),
+ )
+ new_spec = EsmSpec(url="./@file/10-new.js", hash="new")
+ view.apply_update(
+ ModelUpdate(
+ state={},
+ buffer_paths=[],
+ buffers=[],
+ esm_spec=new_spec,
+ )
+ )
+ assert view.esm_spec == new_spec
+ assert view.to_notification().message.esm_spec == new_spec
+
def test_apply_update_replaces_buffer_for_updated_key(self) -> None:
view = ModelReplayState(
model_id=WidgetModelId("m"),