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.

Separate anywidget Model from widget binding lifecycle (#8156)

Trevor Manz6c080985cf5b
diff --git a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
index 13109736bf..5b2565b208 100644
--- a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
+++ b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
@@ -4,9 +4,6 @@
import type { AnyWidget } from "@anywidget/types";
import { useEffect, useRef } from "react";
import { z } from "zod";
-import { asRemoteURL } from "@/core/runtime/config";
-import { resolveVirtualFileURL } from "@/core/static/files";
-import { isStaticNotebook } from "@/core/static/static-state";
import { useAsyncData } from "@/hooks/useAsyncData";
import type { HTMLElementNotDerivedFromRef } from "@/hooks/useEventListener";
import { createPlugin } from "@/plugins/core/builder";
@@ -14,8 +11,9 @@ import type { IPluginProps } from "@/plugins/types";
import { prettyError } from "@/utils/errors";
import { Logger } from "@/utils/Logger";
import { ErrorBanner } from "../common/error-banner";
-import { getMarimoInternal, MODEL_MANAGER, type Model } from "./model";
+import { MODEL_MANAGER, type Model } from "./model";
import type { ModelState, WidgetModelId } from "./types";
+import { BINDING_MANAGER, WIDGET_DEF_REGISTRY } from "./widget-binding";
/**
* AnyWidget asset data
@@ -48,12 +46,7 @@ export function useAnyWidgetModule(opts: { jsUrl: string; jsHash: string }) {
error,
refetch,
} = useAsyncData(async () => {
- let url = asRemoteURL(jsUrl).toString();
- // In static notebooks, resolve virtual files to blob URLs for import()
- if (isStaticNotebook()) {
- url = resolveVirtualFileURL(url);
- }
- return await import(/* @vite-ignore */ url);
+ 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).
@@ -66,6 +59,7 @@ export function useAnyWidgetModule(opts: { jsUrl: string; jsHash: string }) {
const hasError = Boolean(error);
useEffect(() => {
if (hasError && jsUrl) {
+ WIDGET_DEF_REGISTRY.invalidate(jsHash);
refetch();
}
}, [hasError, jsUrl]);
@@ -180,6 +174,7 @@ const AnyWidgetSlot = (props: IPluginProps<ModelIdRef, Data>) => {
async function runAnyWidgetModule<T extends AnyWidgetState>(
widgetDef: AnyWidget<T>,
model: Model<T>,
+ modelId: WidgetModelId,
el: HTMLElement,
signal: AbortSignal,
): Promise<void> {
@@ -187,7 +182,8 @@ async function runAnyWidgetModule<T extends AnyWidgetState>(
el.innerHTML = "";
try {
- const render = await getMarimoInternal(model).resolveWidget(widgetDef);
+ const binding = BINDING_MANAGER.getOrCreate(modelId);
+ const render = await binding.bind(widgetDef, model);
await render(el, signal);
} catch (error) {
Logger.error("Error rendering anywidget", error);
@@ -231,7 +227,13 @@ const LoadedSlot = <T extends AnyWidgetState>({
return;
}
const controller = new AbortController();
- runAnyWidgetModule(widget, model, htmlRef.current, controller.signal);
+ runAnyWidgetModule(
+ widget,
+ model,
+ modelId,
+ htmlRef.current,
+ controller.signal,
+ );
return () => controller.abort();
// We re-run the widget when the modelId changes, which means the cell
// that created the Widget has been re-run.
diff --git a/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.tsx b/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.tsx
index 661117d0f4..b49fdcb195 100644
--- a/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.tsx
+++ b/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.tsx
@@ -1,12 +1,13 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { render, waitFor } from "@testing-library/react";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { TestUtils } from "@/__tests__/test-helpers";
import type { HTMLElementNotDerivedFromRef } from "@/hooks/useEventListener";
import { visibleForTesting } from "../AnyWidgetPlugin";
import { MODEL_MANAGER, Model } from "../model";
import type { WidgetModelId } from "../types";
+import { BINDING_MANAGER } from "../widget-binding";
const { LoadedSlot } = visibleForTesting;
@@ -19,14 +20,6 @@ const mockWidget = {
render: vi.fn(),
};
-vi.mock("../AnyWidgetPlugin", async () => {
- const originalModule = await vi.importActual("../AnyWidgetPlugin");
- return {
- ...originalModule,
- runAnyWidgetModule: vi.fn(),
- };
-});
-
describe("LoadedSlot", () => {
const modelId = asModelId("test-model-id");
let mockModel: Model<{ count: number }>;
@@ -56,6 +49,10 @@ describe("LoadedSlot", () => {
MODEL_MANAGER.set(modelId, mockModel);
});
+ afterEach(() => {
+ BINDING_MANAGER.destroy(modelId);
+ });
+
it("should render a div with ref", () => {
const { container } = render(<LoadedSlot {...mockProps} />);
expect(container.querySelector("div")).not.toBeNull();
diff --git a/frontend/src/plugins/impl/anywidget/__tests__/model.test.ts b/frontend/src/plugins/impl/anywidget/__tests__/model.test.ts
index d1ce49b1db..87e2d454de 100644
--- a/frontend/src/plugins/impl/anywidget/__tests__/model.test.ts
+++ b/frontend/src/plugins/impl/anywidget/__tests__/model.test.ts
@@ -16,6 +16,7 @@ import {
visibleForTesting,
} from "../model";
import type { WidgetModelId } from "../types";
+import { BINDING_MANAGER } from "../widget-binding";
const { ModelManager } = visibleForTesting;
@@ -376,4 +377,20 @@ describe("ModelManager", () => {
});
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);
+ });
});
diff --git a/frontend/src/plugins/impl/anywidget/__tests__/widget-binding.test.ts b/frontend/src/plugins/impl/anywidget/__tests__/widget-binding.test.ts
new file mode 100644
index 0000000000..2894c63224
--- /dev/null
+++ b/frontend/src/plugins/impl/anywidget/__tests__/widget-binding.test.ts
@@ -0,0 +1,240 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { Model } from "../model";
+import type { ModelState, WidgetModelId } 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;
+
+function createMockComm() {
+ return {
+ sendUpdate: vi.fn().mockResolvedValue(undefined),
+ sendCustomMessage: vi.fn().mockResolvedValue(undefined),
+ };
+}
+
+describe("WidgetDefRegistry", () => {
+ let registry: InstanceType<typeof WidgetDefRegistry>;
+
+ beforeEach(() => {
+ registry = new 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");
+ 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");
+ // 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");
+ 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");
+ // The import will fail in Node (http: scheme not supported)
+ 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");
+ expect(promise1).not.toBe(promise2);
+ promise2.catch(() => undefined);
+ });
+});
+
+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();
+ const widgetDef = {
+ initialize: vi.fn().mockResolvedValue(initCleanup),
+ render: vi.fn().mockResolvedValue(renderCleanup),
+ };
+
+ const renderFn = await binding.bind(widgetDef, model);
+ expect(widgetDef.initialize).toHaveBeenCalledTimes(1);
+ expect(typeof renderFn).toBe("function");
+
+ // Render into an element
+ const el = document.createElement("div");
+ const controller = new AbortController();
+ await renderFn(el, controller.signal);
+ expect(widgetDef.render).toHaveBeenCalledTimes(1);
+ });
+
+ it("should return cached render for same widget def", async () => {
+ const widgetDef = {
+ initialize: vi.fn(),
+ render: vi.fn(),
+ };
+
+ 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);
+ });
+
+ 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(),
+ };
+
+ const widgetDef2 = {
+ initialize: vi.fn(),
+ render: vi.fn(),
+ };
+
+ const render1 = await binding.bind(widgetDef1, model);
+ const render2 = await binding.bind(widgetDef2, model);
+
+ expect(render1).not.toBe(render2);
+ expect(cleanup1).toHaveBeenCalledTimes(1); // Old binding cleaned up
+ expect(widgetDef2.initialize).toHaveBeenCalledTimes(1);
+ });
+
+ it("should cleanup render on view signal abort", async () => {
+ const renderCleanup = vi.fn();
+ const widgetDef = {
+ initialize: vi.fn(),
+ render: vi.fn().mockResolvedValue(renderCleanup),
+ };
+
+ const renderFn = await binding.bind(widgetDef, model);
+ const el = document.createElement("div");
+ const viewController = new AbortController();
+ await renderFn(el, viewController.signal);
+
+ // Aborting the view signal should trigger render cleanup
+ viewController.abort();
+ expect(renderCleanup).toHaveBeenCalledTimes(1);
+ });
+
+ it("should cleanup everything on destroy", async () => {
+ const initCleanup = vi.fn();
+ const renderCleanup = vi.fn();
+ const widgetDef = {
+ initialize: vi.fn().mockResolvedValue(initCleanup),
+ render: vi.fn().mockResolvedValue(renderCleanup),
+ };
+
+ const renderFn = await binding.bind(widgetDef, model);
+ const el = document.createElement("div");
+ const viewController = new AbortController();
+ await renderFn(el, viewController.signal);
+
+ binding.destroy();
+ expect(initCleanup).toHaveBeenCalledTimes(1);
+ expect(renderCleanup).toHaveBeenCalledTimes(1);
+ });
+
+ it("should handle widget def as a function", async () => {
+ const widget = {
+ initialize: vi.fn(),
+ render: vi.fn(),
+ };
+ const widgetDefFn = vi.fn().mockResolvedValue(widget);
+
+ await binding.bind(widgetDefFn, model);
+ expect(widgetDefFn).toHaveBeenCalledTimes(1);
+ expect(widget.initialize).toHaveBeenCalledTimes(1);
+ });
+
+ it("should handle widget with no initialize or render", async () => {
+ const widgetDef = {};
+ const renderFn = await binding.bind(widgetDef, model);
+ expect(typeof renderFn).toBe("function");
+
+ // Render should not throw
+ const el = document.createElement("div");
+ const controller = new AbortController();
+ await renderFn(el, controller.signal);
+ });
+});
+
+describe("BindingManager", () => {
+ let manager: InstanceType<typeof BindingManager>;
+
+ beforeEach(() => {
+ manager = new BindingManager();
+ });
+
+ it("should create bindings on demand", () => {
+ const modelId = asModelId("model-1");
+ expect(manager.has(modelId)).toBe(false);
+
+ const binding = manager.getOrCreate(modelId);
+ expect(binding).toBeDefined();
+ expect(manager.has(modelId)).toBe(true);
+ });
+
+ 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("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();
+ const widgetDef = {
+ initialize: vi.fn().mockResolvedValue(initCleanup),
+ render: vi.fn(),
+ };
+ await binding.bind(widgetDef, model);
+
+ manager.destroy(modelId);
+ expect(manager.has(modelId)).toBe(false);
+ expect(initCleanup).toHaveBeenCalledTimes(1);
+ });
+
+ 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);
+ });
+});
diff --git a/frontend/src/plugins/impl/anywidget/model.ts b/frontend/src/plugins/impl/anywidget/model.ts
index a3e75a4458..df3f1bf39f 100644
--- a/frontend/src/plugins/impl/anywidget/model.ts
+++ b/frontend/src/plugins/impl/anywidget/model.ts
@@ -1,7 +1,7 @@
/* Copyright 2026 Marimo. All rights reserved. */
/* eslint-disable @typescript-eslint/no-explicit-any */
-import type { AnyModel, AnyWidget, Experimental } from "@anywidget/types";
+import type { AnyModel } from "@anywidget/types";
import { debounce } from "lodash-es";
import type { NotificationMessageData } from "@/core/kernel/messages";
import { getRequestClient } from "@/core/network/requests";
@@ -20,62 +20,62 @@ 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 {
- /**
- * Map of model ids to deferred promises
- */
- #models = new Map<WidgetModelId, Deferred<Model<ModelState>>>();
- /**
- * Timeout for model lookup
- */
+ #entries = new Map<WidgetModelId, ModelEntry>();
#timeout: number;
constructor(timeout = 10_000) {
this.#timeout = timeout;
}
- get(key: WidgetModelId): Promise<Model<any>> {
- let deferred = this.#models.get(key);
- if (deferred) {
- return deferred.promise;
+ #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);
}
-
- // If the model is not yet created, create the new deferred promise without resolving it
- deferred = new Deferred<Model<ModelState>>();
- this.#models.set(key, deferred);
-
- // Add timeout to prevent hanging
- setTimeout(() => {
- // Already settled
- if (deferred.status !== "pending") {
- return;
- }
-
- deferred.reject(new Error(`Model not found for key: ${key}`));
- this.#models.delete(key);
- }, this.#timeout);
-
- return deferred.promise;
+ return entry;
}
- set(key: WidgetModelId, model: Model<any>): void {
- let deferred = this.#models.get(key);
- if (!deferred) {
- deferred = new Deferred<Model<ModelState>>();
- this.#models.set(key, deferred);
+ 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);
}
- deferred.resolve(model);
+ return entry.deferred.promise;
}
/**
- * Check if a model exists and has been resolved (not pending).
- * This is useful for checking if a model was already created by the plugin
- * before the 'open' message arrives.
+ * Create a model with a managed lifecycle signal.
+ * The signal is aborted when the model is deleted.
*/
- has(key: WidgetModelId): boolean {
- const deferred = this.#models.get(key);
- return deferred !== undefined && deferred.status === "resolved";
+ 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);
}
/**
@@ -83,15 +83,19 @@ class ModelManager {
* Returns undefined if the model doesn't exist or is still pending.
*/
getSync(key: WidgetModelId): Model<any> | undefined {
- const deferred = this.#models.get(key);
- if (deferred && deferred.status === "resolved") {
- return deferred.value;
+ const entry = this.#entries.get(key);
+ if (entry && entry.deferred.status === "resolved") {
+ return entry.deferred.value;
}
return undefined;
}
delete(key: WidgetModelId): void {
- this.#models.delete(key);
+ Logger.debug(
+ `[ModelManager] Deleting model=${key}, aborting lifecycle signal`,
+ );
+ this.#entries.get(key)?.controller.abort();
+ this.#entries.delete(key);
}
}
@@ -102,28 +106,7 @@ interface MarimoComm<T> {
const marimoSymbol = Symbol("marimo");
-const experimental: Experimental = {
- invoke: async () => {
- const message =
- "anywidget.invoke not supported in marimo. Please file an issue at https://github.com/marimo-team/marimo/issues";
- Logger.warn(message);
- throw new Error(message);
- },
-};
-
-type RenderFn = (el: HTMLElement, signal: AbortSignal) => Promise<void>;
-
interface MarimoInternalApi<T extends ModelState> {
- /**
- * Resolve the widget definition and initialize if needed.
- * Returns a render function that can be called for each view.
- *
- * Per AFM spec:
- * - widgetDef() is called once per model
- * - initialize() is called once per model
- * - render() (the returned function) is called once per view
- */
- resolveWidget: (widgetDef: AnyWidget<T>) => Promise<RenderFn>;
/**
* Update model state and emit change events for any differences.
*/
@@ -135,10 +118,6 @@ interface MarimoInternalApi<T extends ModelState> {
message: Extract<AnyWidgetMessage, { method: "custom" }>,
buffers?: readonly DataView[],
) => void;
- /**
- * Destroy the model, triggering initialize cleanup.
- */
- destroy: () => void;
}
/**
@@ -159,18 +138,19 @@ export class Model<T extends ModelState> implements AnyModel<T> {
#data: T;
#comm: MarimoComm<T>;
#listeners: Record<string, Set<EventHandler> | undefined> = {};
- #controller = new AbortController();
- #widgetDef: AnyWidget<T> | undefined;
- #render:
- | ((el: HTMLElement, signal: AbortSignal) => Promise<void>)
- | undefined;
static _modelManager: ModelManager = MODEL_MANAGER;
- constructor(data: T, comm: MarimoComm<T>) {
+ constructor(data: T, comm: MarimoComm<T>, signal?: AbortSignal) {
this.#data = data;
this.#comm = comm;
this.#dirtyFields = new Map();
+ if (signal) {
+ signal.addEventListener("abort", () => {
+ Logger.debug("[Model] Signal aborted, clearing all listeners");
+ this.#listeners = {};
+ });
+ }
}
/**
@@ -183,52 +163,6 @@ export class Model<T extends ModelState> implements AnyModel<T> {
message: Extract<AnyWidgetMessage, { method: "custom" }>,
buffers?: readonly DataView[],
) => this.#emitCustomMessage(message, buffers),
- resolveWidget: async (widgetDef: AnyWidget<T>): Promise<RenderFn> => {
- // Already initialized with the same widget - return cached render
- if (this.#render && this.#widgetDef === widgetDef) {
- return this.#render;
- }
-
- // If widgetDef changed (hot reload), destroy old and re-initialize
- if (this.#render && this.#widgetDef !== widgetDef) {
- this.#controller.abort();
- this.#controller = new AbortController();
- this.#render = undefined;
- }
-
- this.#widgetDef = widgetDef;
-
- // Resolve the widget definition (call if it's a function)
- const widget =
- typeof widgetDef === "function" ? await widgetDef() : widgetDef;
-
- // Call initialize once per model
- const cleanup = await widget.initialize?.({ model: this, experimental });
- if (cleanup) {
- this.#controller.signal.addEventListener("abort", cleanup);
- }
-
- // Store and return the render closure
- this.#render = async (el: HTMLElement, signal: AbortSignal) => {
- const renderCleanup = await widget.render?.({
- model: this,
- el,
- experimental,
- });
- if (renderCleanup) {
- // Cleanup when either the view unmounts or the model is destroyed
- AbortSignal.any([signal, this.#controller.signal]).addEventListener(
- "abort",
- renderCleanup,
- );
- }
- };
-
- return this.#render;
- },
- destroy: () => {
- this.#controller.abort();
- },
};
off(eventName?: string | null, callback?: EventHandler | null): void {
@@ -387,8 +321,6 @@ export async function handleWidgetMessage(
const modelId = notification.model_id as WidgetModelId;
const msg = notification.message;
- Logger.debug("AnyWidget message", msg);
-
// Decode base64 buffers to DataViews (present in open/update/custom messages)
const base64Buffers: Base64String[] =
"buffers" in msg ? (msg.buffers as Base64String[]) : [];
@@ -411,25 +343,44 @@ export async function handleWidgetMessage(
return;
}
- const model = new Model(stateWithBuffers, {
- async sendUpdate(changeData) {
- const { state, buffers, bufferPaths } =
- serializeBuffersToBase64(changeData);
- await getRequestClient().sendModelValue({
- modelId,
- message: { method: "update", state, bufferPaths },
- buffers,
- });
- },
- async sendCustomMessage(content, buffers) {
- await getRequestClient().sendModelValue({
- modelId,
- message: { method: "custom", content },
- buffers: buffers.map(dataViewToBase64),
- });
- },
- });
- modelManager.set(modelId, model);
+ modelManager.create(
+ modelId,
+ (signal) =>
+ new Model(
+ stateWithBuffers,
+ {
+ 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),
+ });
+ },
+ },
+ signal,
+ ),
+ );
return;
}
@@ -444,11 +395,8 @@ export async function handleWidgetMessage(
}
case "close": {
- const model = modelManager.getSync(modelId);
- if (model) {
- getMarimoInternal(model).destroy();
- }
- modelManager.delete(modelId);
+ BINDING_MANAGER.destroy(modelId);
+ modelManager.delete(modelId); // aborts the model's signal, clearing listeners
return;
}
diff --git a/frontend/src/plugins/impl/anywidget/widget-binding.ts b/frontend/src/plugins/impl/anywidget/widget-binding.ts
new file mode 100644
index 0000000000..291ef27aa6
--- /dev/null
+++ b/frontend/src/plugins/impl/anywidget/widget-binding.ts
@@ -0,0 +1,216 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+/* eslint-disable @typescript-eslint/no-explicit-any */
+
+import type { AnyWidget, Experimental } from "@anywidget/types";
+import { asRemoteURL } from "@/core/runtime/config";
+import { resolveVirtualFileURL } from "@/core/static/files";
+import { isStaticNotebook } from "@/core/static/static-state";
+import { Logger } from "@/utils/Logger";
+import type { Model } from "./model";
+import type { ModelState, WidgetModelId } from "./types";
+
+export const experimental: Experimental = {
+ invoke: async () => {
+ const message =
+ "anywidget.invoke not supported in marimo. Please file an issue at https://github.com/marimo-team/marimo/issues";
+ Logger.warn(message);
+ throw new Error(message);
+ },
+};
+
+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
+ * (jsdom) supports AbortSignal.any natively.
+ */
+function abortSignalAny(signals: AbortSignal[]): AbortSignal {
+ if (typeof AbortSignal.any === "function") {
+ return AbortSignal.any(signals);
+ }
+ const controller = new AbortController();
+ for (const signal of signals) {
+ if (signal.aborted) {
+ controller.abort(signal.reason);
+ return controller.signal;
+ }
+ signal.addEventListener("abort", () => controller.abort(signal.reason), {
+ once: true,
+ });
+ }
+ return controller.signal;
+}
+
+/**
+ * Deduplicates ESM imports by jsHash.
+ * A single import is shared across all widget instances using the same module.
+ */
+class WidgetDefRegistry {
+ #cache = new Map<string, Promise<any>>();
+
+ /**
+ * Get (or start) the ESM import for a widget module.
+ * Cached by jsHash so multiple instances share one import.
+ */
+ getModule(jsUrl: string, jsHash: string): Promise<any> {
+ const cached = this.#cache.get(jsHash);
+ if (cached) {
+ return cached;
+ }
+
+ const promise = this.#doImport(jsUrl).catch((error) => {
+ // On failure, remove from cache so a retry with a new URL can work
+ this.#cache.delete(jsHash);
+ throw error;
+ });
+
+ this.#cache.set(jsHash, promise);
+ 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> {
+ let url = asRemoteURL(jsUrl).toString();
+ if (isStaticNotebook()) {
+ url = resolveVirtualFileURL(url);
+ }
+ return import(/* @vite-ignore */ url);
+ }
+}
+
+/**
+ * Connects a Model to a resolved AnyWidget definition.
+ * Owns the initialize lifecycle and produces a render function.
+ *
+ * Per AFM spec:
+ * - initialize() is called once per model (or once per hot-reload)
+ * - render() (the returned function) is called once per view
+ */
+class WidgetBinding<T extends ModelState = ModelState> {
+ #controller: AbortController | undefined;
+ #widgetDef: AnyWidget<T> | undefined;
+ #render: RenderFn | undefined;
+
+ /**
+ * 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.
+ */
+ 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;
+ }
+
+ // 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;
+ }
+
+ this.#widgetDef = widgetDef;
+ this.#controller = new AbortController();
+ const bindingSignal = this.#controller.signal;
+
+ // Resolve the widget definition (call if it's a function)
+ const widget =
+ typeof widgetDef === "function" ? await widgetDef() : widgetDef;
+
+ // Call initialize once per model
+ const cleanup = await widget.initialize?.({ model, experimental });
+ if (cleanup) {
+ bindingSignal.addEventListener("abort", cleanup);
+ }
+
+ // 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();
+ });
+ }
+ };
+
+ return this.#render;
+ }
+
+ /**
+ * Destroy this binding, aborting the initialize lifecycle.
+ */
+ destroy(): void {
+ Logger.debug(
+ "[WidgetBinding] Destroying binding, aborting initialize lifecycle",
+ );
+ this.#controller?.abort();
+ this.#controller = undefined;
+ this.#widgetDef = undefined;
+ this.#render = undefined;
+ }
+}
+
+/**
+ * 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);
+ }
+ return binding;
+ }
+
+ 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);
+ }
+ }
+
+ has(modelId: WidgetModelId): boolean {
+ return this.#bindings.has(modelId);
+ }
+}
+
+export const WIDGET_DEF_REGISTRY = new WidgetDefRegistry();
+export const BINDING_MANAGER = new BindingManager();
+
+export const visibleForTesting = {
+ WidgetDefRegistry,
+ WidgetBinding,
+ BindingManager,
+};