Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

fix: support multiple anywidget widget models (#4972)

Myles Scolnickf7414117e783
diff --git a/frontend/src/core/dom/uiregistry.ts b/frontend/src/core/dom/uiregistry.ts
index bcce235878..6be8cd075e 100644
--- a/frontend/src/core/dom/uiregistry.ts
+++ b/frontend/src/core/dom/uiregistry.ts
@@ -8,6 +8,9 @@ import {
MarimoValueUpdateEvent,
} from "./events";
import { parseInitialValue } from "./htmlUtils";
+import { byteStringToDataView } from "@/utils/data-views";
+import type { Base64String } from "@/utils/json/base64";
+import { typedAtob } from "@/utils/json/base64";
interface UIElementEntry {
objectId: string;
@@ -132,20 +135,14 @@ export class UIElementRegistry {
broadcastMessage(
objectId: UIElementId,
message: unknown,
- buffers: string[] | undefined | null,
+ buffers: Base64String[] | undefined | null,
): void {
const entry = this.entries.get(objectId);
if (entry === undefined) {
Logger.warn("UIElementRegistry missing entry", objectId);
} else {
- const base64ToDataView = (base64: string) => {
- const bytes = window.atob(base64);
- const buffer = new ArrayBuffer(bytes.length);
- const view = new DataView(buffer);
- for (let i = 0; i < bytes.length; i++) {
- view.setUint8(i, bytes.charCodeAt(i));
- }
- return view;
+ const toDataView = (base64: Base64String) => {
+ return byteStringToDataView(typedAtob(base64));
};
entry.elements.forEach((element) => {
element.dispatchEvent(
@@ -155,7 +152,7 @@ export class UIElementRegistry {
detail: {
objectId: objectId,
message: message,
- buffers: buffers ? buffers.map(base64ToDataView) : undefined,
+ buffers: buffers ? buffers.map(toDataView) : undefined,
},
}),
);
diff --git a/frontend/src/core/islands/bridge.ts b/frontend/src/core/islands/bridge.ts
index ddaef460e5..cffa211d88 100644
--- a/frontend/src/core/islands/bridge.ts
+++ b/frontend/src/core/islands/bridge.ts
@@ -124,6 +124,11 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
return null;
};
+ sendModelValue: RunRequests["sendModelValue"] = async (request) => {
+ await this.putControlRequest(request);
+ return null;
+ };
+
getUsageStats = throwNotImplemented;
sendRename = throwNotImplemented;
sendSave = throwNotImplemented;
diff --git a/frontend/src/core/islands/main.ts b/frontend/src/core/islands/main.ts
index 56c9b9ad07..b82ca03f3b 100644
--- a/frontend/src/core/islands/main.ts
+++ b/frontend/src/core/islands/main.ts
@@ -36,6 +36,7 @@ import {
userTriedToInteractWithIslandsAtom,
} from "./state";
import { dismissIslandsLoadingToast, toastIslandsLoading } from "./toast";
+import type { Base64String } from "@/utils/json/base64";
/**
* Main entry point for the js bundle for embedded marimo apps.
@@ -130,7 +131,7 @@ export async function initialize() {
UI_ELEMENT_REGISTRY.broadcastMessage(
msg.data.ui_element as UIElementId,
msg.data.message,
- msg.data.buffers,
+ msg.data.buffers as Base64String[],
);
return;
diff --git a/frontend/src/core/network/requests-network.ts b/frontend/src/core/network/requests-network.ts
index 4075f89dc3..f59467578b 100644
--- a/frontend/src/core/network/requests-network.ts
+++ b/frontend/src/core/network/requests-network.ts
@@ -14,6 +14,13 @@ export function createNetworkRequests(): EditRequests & RunRequests {
})
.then(handleResponseReturnNull);
},
+ sendModelValue: (request) => {
+ return marimoClient
+ .POST("/api/kernel/set_model_value", {
+ body: request,
+ })
+ .then(handleResponseReturnNull);
+ },
sendRestart: () => {
return marimoClient
.POST("/api/kernel/restart_session")
diff --git a/frontend/src/core/network/requests-static.ts b/frontend/src/core/network/requests-static.ts
index 296b790894..5819e649b3 100644
--- a/frontend/src/core/network/requests-static.ts
+++ b/frontend/src/core/network/requests-static.ts
@@ -18,6 +18,10 @@ export function createStaticRequests(): EditRequests & RunRequests {
Logger.log("Updating UI elements is not supported in static mode");
return null;
},
+ sendModelValue: async () => {
+ Logger.log("Updating model values is not supported in static mode");
+ return null;
+ },
sendInstantiate: async () => {
Logger.log("Viewing as static notebook");
return null;
diff --git a/frontend/src/core/network/requests-toasting.ts b/frontend/src/core/network/requests-toasting.ts
index ae9921eaf1..50b4b106ae 100644
--- a/frontend/src/core/network/requests-toasting.ts
+++ b/frontend/src/core/network/requests-toasting.ts
@@ -10,6 +10,7 @@ export function createErrorToastingRequests(
): EditRequests & RunRequests {
const MESSAGES: Record<RequestKey, string> = {
sendComponentValues: "Failed update value",
+ sendModelValue: "Failed to update model value",
sendInstantiate: "Failed to instantiate",
sendFunctionRequest: "Failed to send function request",
sendRestart: "Failed to restart",
diff --git a/frontend/src/core/network/requests.ts b/frontend/src/core/network/requests.ts
index 0cf61cd4a5..d5bc1b58c3 100644
--- a/frontend/src/core/network/requests.ts
+++ b/frontend/src/core/network/requests.ts
@@ -27,6 +27,7 @@ function getRequest(): EditRequests & RunRequests {
export const {
sendComponentValues,
+ sendModelValue,
sendRename,
sendRestart,
syncCellIds,
diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.ts
index 0cdfd51c17..f8ec5ecba0 100644
--- a/frontend/src/core/network/types.ts
+++ b/frontend/src/core/network/types.ts
@@ -73,6 +73,7 @@ export interface SetCellConfigRequest {
configs: Record<CellId, Partial<CellConfig>>;
}
export type SetUIElementValueRequest = schemas["SetUIElementValueRequest"];
+export type SetModelMessageRequest = schemas["SetModelMessageRequest"];
export type UpdateCellIdsRequest = schemas["UpdateCellIdsRequest"];
export type SetUserConfigRequest = schemas["SetUserConfigRequest"];
export type ShutdownSessionRequest = schemas["ShutdownSessionRequest"];
@@ -96,6 +97,7 @@ export type TutorialId = OpenTutorialRequest["tutorialId"];
*/
export interface RunRequests {
sendComponentValues: (request: UpdateComponentValuesRequest) => Promise<null>;
+ sendModelValue: (request: SetModelMessageRequest) => Promise<null>;
sendInstantiate: (request: InstantiateRequest) => Promise<null>;
sendFunctionRequest: (request: FunctionCallRequest) => Promise<null>;
}
diff --git a/frontend/src/core/wasm/bridge.ts b/frontend/src/core/wasm/bridge.ts
index c49898cb30..d5764743b9 100644
--- a/frontend/src/core/wasm/bridge.ts
+++ b/frontend/src/core/wasm/bridge.ts
@@ -370,6 +370,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
});
return response as FileListResponse;
};
+
sendComponentValues: RunRequests["sendComponentValues"] = async (request) => {
await this.putControlRequest({
...request,
@@ -484,6 +485,11 @@ export class PyodideBridge implements RunRequests, EditRequests {
return null;
};
+ sendModelValue: RunRequests["sendModelValue"] = async (request) => {
+ await this.putControlRequest(request);
+ return null;
+ };
+
syncCellIds = () => Promise.resolve(null);
getUsageStats = throwNotImplemented;
openTutorial = throwNotImplemented;
diff --git a/frontend/src/core/websocket/useMarimoWebSocket.tsx b/frontend/src/core/websocket/useMarimoWebSocket.tsx
index e915c9bf5f..9f35007991 100644
--- a/frontend/src/core/websocket/useMarimoWebSocket.tsx
+++ b/frontend/src/core/websocket/useMarimoWebSocket.tsx
@@ -34,7 +34,7 @@ import {
handleRemoveUIElements,
} from "../kernel/handlers";
import { queryParamHandlers } from "../kernel/queryParamHandlers";
-import type { JsonString } from "@/utils/json/base64";
+import type { Base64String, JsonString } from "@/utils/json/base64";
import { useDatasetsActions } from "../datasets/state";
import type { RequestId } from "../network/DeferredRequestRegistry";
import type { VariableName } from "../variables/types";
@@ -50,6 +50,11 @@ import {
useDataSourceActions,
} from "../datasets/data-source-connections";
import { SECRETS_REGISTRY } from "../secrets/request-registry";
+import {
+ handleWidgetMessage,
+ isMessageWidgetState,
+ MODEL_MANAGER,
+} from "@/plugins/impl/anywidget/model";
/**
* WebSocket that connects to the Marimo kernel and handles incoming messages.
@@ -102,13 +107,26 @@ export function useMarimoWebSocket(opts: {
case "interrupted":
return;
- case "send-ui-element-message":
- UI_ELEMENT_REGISTRY.broadcastMessage(
- msg.data.ui_element as UIElementId,
- msg.data.message,
- msg.data.buffers,
- );
+ case "send-ui-element-message": {
+ const modelId = msg.data.model_id;
+ const uiElement = msg.data.ui_element;
+ const message = msg.data.message;
+ const buffers = (msg.data.buffers ?? []) as Base64String[];
+
+ if (modelId && isMessageWidgetState(message)) {
+ handleWidgetMessage(modelId, message, buffers, MODEL_MANAGER);
+ }
+
+ if (uiElement) {
+ UI_ELEMENT_REGISTRY.broadcastMessage(
+ uiElement as UIElementId,
+ msg.data.message,
+ buffers,
+ );
+ }
+
return;
+ }
case "remove-ui-elements":
handleRemoveUIElements(msg.data);
diff --git a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
index 969add39ea..7fc8d8bcac 100644
--- a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
+++ b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
@@ -17,7 +17,7 @@ import {
} from "@/hooks/useEventListener";
import { MarimoIncomingMessageEvent } from "@/core/dom/events";
import { updateBufferPaths } from "@/utils/data-views";
-import { Model } from "./model";
+import { Model, MODEL_MANAGER } from "./model";
import { isEqual } from "lodash-es";
interface Data {
@@ -190,6 +190,12 @@ export function getDirtyFields(value: T, initialValue: T): Set<keyof T> {
);
}
+function hasModelId(message: unknown): message is { model_id: string } {
+ return (
+ typeof message === "object" && message !== null && "model_id" in message
+ );
+}
+
const LoadedSlot = ({
value,
setValue,
@@ -199,6 +205,7 @@ const LoadedSlot = ({
host,
}: Props & { widget: AnyWidget }) => {
const htmlRef = useRef<HTMLDivElement>(null);
+
const model = useRef<Model<T>>(
new Model(
// Merge the initial value with the current value
@@ -215,7 +222,14 @@ const LoadedSlot = ({
host as HTMLElementNotDerivedFromRef,
MarimoIncomingMessageEvent.TYPE,
(e) => {
- model.current.receiveCustomMessage(e.detail.message, e.detail.buffers);
+ const message = e.detail.message;
+ if (hasModelId(message)) {
+ MODEL_MANAGER.get(message.model_id).then((model) => {
+ model.receiveCustomMessage(message, e.detail.buffers);
+ });
+ } else {
+ model.current.receiveCustomMessage(message, e.detail.buffers);
+ }
},
);
diff --git a/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.tsx b/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.tsx
index 2c1250504a..07c144eec6 100644
--- a/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.tsx
+++ b/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.tsx
@@ -8,242 +8,6 @@ import type { UIElementId } from "@/core/cells/ids";
const { LoadedSlot } = visibleForTesting;
-describe("Model", () => {
- let model: Model<{ foo: string; bar: number }>;
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- let onChange: (value: any) => void;
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- let sendToWidget: (req: { content?: any }) => Promise<null | undefined>;
-
- beforeEach(() => {
- onChange = vi.fn();
- sendToWidget = vi.fn().mockResolvedValue(null);
- model = new Model(
- { foo: "test", bar: 123 },
- onChange,
- sendToWidget,
- new Set(),
- );
- });
-
- describe("get/set", () => {
- it("should get values correctly", () => {
- expect(model.get("foo")).toBe("test");
- expect(model.get("bar")).toBe(123);
- });
-
- it("should set values and emit change events", () => {
- const callback = vi.fn();
- model.on("change:foo", callback);
- model.set("foo", "new value");
-
- expect(callback).toHaveBeenCalledWith("new value");
- expect(model.get("foo")).toBe("new value");
- });
-
- it("should not emit change events for non-subscribed fields", () => {
- const callback = vi.fn();
- model.on("change:foo", callback);
- model.set("bar", 456);
-
- expect(callback).not.toHaveBeenCalled();
- });
- });
-
- describe("save_changes", () => {
- it("should only save dirty fields", () => {
- model.set("foo", "new value");
- model.set("bar", 456);
- model.save_changes();
-
- expect(onChange).toHaveBeenCalledWith({
- foo: "new value",
- bar: 456,
- });
- });
-
- it("should send all dirty fields", () => {
- model.set("foo", "new value");
- model.save_changes();
-
- expect(onChange).toHaveBeenCalledWith({
- foo: "new value",
- });
-
- model.set("bar", 456);
- model.save_changes();
-
- expect(onChange).toHaveBeenCalledWith({
- foo: "new value",
- bar: 456,
- });
- });
-
- // Skip because we don't clear the dirty fields after save
- it.skip("should clear dirty fields after save", () => {
- model.set("foo", "new value");
- model.save_changes();
- model.save_changes(); // Second save should not call onChange
-
- expect(onChange).toHaveBeenCalledTimes(1);
- });
- });
-
- describe("event handling", () => {
- it("should add and remove event listeners", () => {
- const callback = vi.fn();
- model.on("change:foo", callback);
- model.set("foo", "new value");
- expect(callback).toHaveBeenCalledTimes(1);
-
- model.off("change:foo", callback);
- model.set("foo", "another value");
- expect(callback).toHaveBeenCalledTimes(1);
- });
-
- it("should remove all listeners when no event name provided", () => {
- const callback1 = vi.fn();
- const callback2 = vi.fn();
- model.on("change:foo", callback1);
- model.on("change:bar", callback2);
-
- model.off();
- model.set("foo", "new value");
- model.set("bar", 456);
-
- expect(callback1).not.toHaveBeenCalled();
- expect(callback2).not.toHaveBeenCalled();
- });
-
- it("should remove all listeners for specific event", () => {
- const callback1 = vi.fn();
- const callback2 = vi.fn();
- model.on("change:foo", callback1);
- model.on("change:foo", callback2);
-
- model.off("change:foo");
- model.set("foo", "new value");
-
- expect(callback1).not.toHaveBeenCalled();
- expect(callback2).not.toHaveBeenCalled();
- });
- });
-
- describe("send", () => {
- it("should send message and handle callbacks", async () => {
- const callback = vi.fn();
- model.send({ test: true }, callback);
-
- expect(sendToWidget).toHaveBeenCalledWith({ content: { test: true } });
- await new Promise((resolve) => setTimeout(resolve, 0)); // flush
- expect(callback).toHaveBeenCalledWith(null);
- });
-
- it("should warn when buffers are provided", () => {
- const consoleSpy = vi.spyOn(console, "warn").mockImplementation(() => {
- // noop
- });
- model.send({ test: true }, null, [new ArrayBuffer(8)]);
-
- expect(consoleSpy).toHaveBeenCalledWith(
- "buffers not supported in marimo anywidget.send",
- );
- });
- });
-
- describe("widget_manager", () => {
- it("should throw error when accessing widget_manager", () => {
- expect(() => model.widget_manager.get_model("foo")).toThrow(
- "widget_manager not supported in marimo",
- );
- });
- });
-
- describe("updateAndEmitDiffs", () => {
- it("should only update and emit for changed values", () => {
- const callback = vi.fn();
- model.on("change:foo", callback);
-
- model.updateAndEmitDiffs({ foo: "test", bar: 456 });
- expect(callback).not.toHaveBeenCalled(); // foo didn't change
- expect(model.get("bar")).toBe(456);
- });
-
- it("should update and emit for deep changes", () => {
- const modelWithObject = new Model<{ foo: { nested: string } }>(
- { foo: { nested: "test" } },
- onChange,
- sendToWidget,
- new Set(),
- );
- const callback = vi.fn();
- modelWithObject.on("change:foo", callback);
-
- modelWithObject.updateAndEmitDiffs({ foo: { nested: "changed" } });
- expect(callback).toHaveBeenCalledTimes(1);
- });
-
- it("should emit change event for any changes", async () => {
- const callback = vi.fn();
- model.on("change", callback);
- model.updateAndEmitDiffs({ foo: "changed", bar: 456 });
- await new Promise((resolve) => setTimeout(resolve, 0)); // flush
- expect(callback).toHaveBeenCalledTimes(1);
- });
- });
-
- describe("receiveCustomMessage", () => {
- it("should handle update messages", () => {
- model.receiveCustomMessage({
- method: "update",
- state: { foo: "updated", bar: 789 },
- });
-
- expect(model.get("foo")).toBe("updated");
- expect(model.get("bar")).toBe(789);
- });
-
- it("should handle custom messages", () => {
- const callback = vi.fn();
- model.on("msg:custom", callback);
-
- const content = { type: "test" };
- model.receiveCustomMessage({
- method: "custom",
- content,
- });
-
- expect(callback).toHaveBeenCalledWith(content, undefined);
- });
-
- it("should handle custom messages with buffers", () => {
- const callback = vi.fn();
- model.on("msg:custom", callback);
-
- const content = { type: "test" };
- const buffer = new DataView(new ArrayBuffer(8));
- model.receiveCustomMessage(
- {
- method: "custom",
- content,
- },
- [buffer],
- );
-
- expect(callback).toHaveBeenCalledWith(content, [buffer]);
- });
-
- it("should log error for invalid messages", () => {
- const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {
- // noop
- });
- model.receiveCustomMessage({ invalid: "message" });
-
- expect(consoleSpy).toHaveBeenCalledTimes(2);
- });
- });
-});
-
describe("getDirtyFields", () => {
it("should return empty set when values are equal", () => {
const value = { foo: "bar", baz: 123 };
diff --git a/frontend/src/plugins/impl/anywidget/__tests__/model.test.ts b/frontend/src/plugins/impl/anywidget/__tests__/model.test.ts
new file mode 100644
index 0000000000..9b554dc83e
--- /dev/null
+++ b/frontend/src/plugins/impl/anywidget/__tests__/model.test.ts
@@ -0,0 +1,342 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import {
+ describe,
+ beforeEach,
+ it,
+ expect,
+ vi,
+ afterAll,
+ beforeAll,
+} from "vitest";
+import {
+ Model,
+ handleWidgetMessage,
+ type AnyWidgetMessage,
+ visibleForTesting,
+} from "../model";
+import type { Base64String } from "@/utils/json/base64";
+
+const { ModelManager } = visibleForTesting;
+
+describe("Model", () => {
+ let model: Model<{ foo: string; bar: number }>;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ let onChange: (value: any) => void;
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ let sendToWidget: (req: { content?: any }) => Promise<null | undefined>;
+
+ beforeEach(() => {
+ onChange = vi.fn();
+ sendToWidget = vi.fn().mockResolvedValue(null);
+ model = new Model(
+ { foo: "test", bar: 123 },
+ onChange,
+ sendToWidget,
+ new Set(),
+ );
+ });
+
+ describe("get/set", () => {
+ it("should get values correctly", () => {
+ expect(model.get("foo")).toBe("test");
+ expect(model.get("bar")).toBe(123);
+ });
+
+ it("should set values and emit change events", () => {
+ const callback = vi.fn();
+ model.on("change:foo", callback);
+ model.set("foo", "new value");
+
+ expect(callback).toHaveBeenCalledWith("new value");
+ expect(model.get("foo")).toBe("new value");
+ });
+
+ it("should not emit change events for non-subscribed fields", () => {
+ const callback = vi.fn();
+ model.on("change:foo", callback);
+ model.set("bar", 456);
+
+ expect(callback).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("save_changes", () => {
+ it("should only save dirty fields", () => {
+ model.set("foo", "new value");
+ model.set("bar", 456);
+ model.save_changes();
+
+ expect(onChange).toHaveBeenCalledWith({
+ foo: "new value",
+ bar: 456,
+ });
+ });
+
+ it("should send all dirty fields", () => {
+ model.set("foo", "new value");
+ model.save_changes();
+
+ expect(onChange).toHaveBeenCalledWith({
+ foo: "new value",
+ });
+
+ model.set("bar", 456);
+ model.save_changes();
+
+ expect(onChange).toHaveBeenCalledWith({
+ foo: "new value",
+ bar: 456,
+ });
+ });
+
+ // Skip because we don't clear the dirty fields after save
+ it.skip("should clear dirty fields after save", () => {
+ model.set("foo", "new value");
+ model.save_changes();
+ model.save_changes(); // Second save should not call onChange
+
+ expect(onChange).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe("event handling", () => {
+ it("should add and remove event listeners", () => {
+ const callback = vi.fn();
+ model.on("change:foo", callback);
+ model.set("foo", "new value");
+ expect(callback).toHaveBeenCalledTimes(1);
+
+ model.off("change:foo", callback);
+ model.set("foo", "another value");
+ expect(callback).toHaveBeenCalledTimes(1);
+ });
+
+ it("should remove all listeners when no event name provided", () => {
+ const callback1 = vi.fn();
+ const callback2 = vi.fn();
+ model.on("change:foo", callback1);
+ model.on("change:bar", callback2);
+
+ model.off();
+ model.set("foo", "new value");
+ model.set("bar", 456);
+
+ expect(callback1).not.toHaveBeenCalled();
+ expect(callback2).not.toHaveBeenCalled();
+ });
+
+ it("should remove all listeners for specific event", () => {
+ const callback1 = vi.fn();
+ const callback2 = vi.fn();
+ model.on("change:foo", callback1);
+ model.on("change:foo", callback2);
+
+ model.off("change:foo");
+ model.set("foo", "new value");
+
+ expect(callback1).not.toHaveBeenCalled();
+ expect(callback2).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("send", () => {
+ it("should send message and handle callbacks", async () => {
+ const callback = vi.fn();
+ model.send({ test: true }, callback);
+
+ expect(sendToWidget).toHaveBeenCalledWith({ content: { test: true } });
+ await new Promise((resolve) => setTimeout(resolve, 0)); // flush
+ expect(callback).toHaveBeenCalledWith(null);
+ });
+
+ it("should warn when buffers are provided", () => {
+ const consoleSpy = vi.spyOn(console, "warn").mockImplementation(() => {
+ // noop
+ });
+ model.send({ test: true }, null, [new ArrayBuffer(8)]);
+
+ expect(consoleSpy).toHaveBeenCalledWith(
+ "buffers not supported in marimo anywidget.send",
+ );
+ });
+ });
+
+ describe("widget_manager", () => {
+ const childModelId = "test-id";
+ const childModel = new Model({ foo: "test" }, vi.fn(), vi.fn(), new Set());
+ const manager = new ModelManager(10);
+ let previousModelManager = Model._modelManager;
+
+ beforeAll(() => {
+ previousModelManager = Model._modelManager;
+ manager.set(childModelId, childModel);
+ Model._modelManager = manager;
+ });
+
+ afterAll(() => {
+ manager.delete(childModelId);
+ Model._modelManager = previousModelManager;
+ });
+
+ it("should throw error when accessing a model that is not registered", async () => {
+ await expect(model.widget_manager.get_model("random-id")).rejects.toThrow(
+ "Model not found for key: random-id",
+ );
+ });
+
+ it("should return the registered model", async () => {
+ expect(await model.widget_manager.get_model(childModelId)).toBe(
+ childModel,
+ );
+ });
+ });
+
+ describe("updateAndEmitDiffs", () => {
+ it("should only update and emit for changed values", () => {
+ const callback = vi.fn();
+ model.on("change:foo", callback);
+
+ model.updateAndEmitDiffs({ foo: "test", bar: 456 });
+ expect(callback).not.toHaveBeenCalled(); // foo didn't change
+ expect(model.get("bar")).toBe(456);
+ });
+
+ it("should update and emit for deep changes", () => {
+ const modelWithObject = new Model<{ foo: { nested: string } }>(
+ { foo: { nested: "test" } },
+ onChange,
+ sendToWidget,
+ new Set(),
+ );
+ const callback = vi.fn();
+ modelWithObject.on("change:foo", callback);
+
+ modelWithObject.updateAndEmitDiffs({ foo: { nested: "changed" } });
+ expect(callback).toHaveBeenCalledTimes(1);
+ });
+
+ it("should emit change event for any changes", async () => {
+ const callback = vi.fn();
+ model.on("change", callback);
+ model.updateAndEmitDiffs({ foo: "changed", bar: 456 });
+ await new Promise((resolve) => setTimeout(resolve, 0)); // flush
+ expect(callback).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe("receiveCustomMessage", () => {
+ it("should handle update messages", () => {
+ model.receiveCustomMessage({
+ method: "update",
+ state: { foo: "updated", bar: 789 },
+ });
+
+ expect(model.get("foo")).toBe("updated");
+ expect(model.get("bar")).toBe(789);
+ });
+
+ it("should handle custom messages", () => {
+ const callback = vi.fn();
+ model.on("msg:custom", callback);
+
+ const content = { type: "test" };
+ model.receiveCustomMessage({
+ method: "custom",
+ content,
+ });
+
+ expect(callback).toHaveBeenCalledWith(content, undefined);
+ });
+
+ it("should handle custom messages with buffers", () => {
+ const callback = vi.fn();
+ model.on("msg:custom", callback);
+
+ const content = { type: "test" };
+ const buffer = new DataView(new ArrayBuffer(8));
+ model.receiveCustomMessage(
+ {
+ method: "custom",
+ content,
+ },
+ [buffer],
+ );
+
+ expect(callback).toHaveBeenCalledWith(content, [buffer]);
+ });
+
+ it("should log error for invalid messages", () => {
+ const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {
+ // noop
+ });
+ model.receiveCustomMessage({ invalid: "message" });
+
+ expect(consoleSpy).toHaveBeenCalledTimes(2);
+ });
+ });
+});
+
+describe("ModelManager", () => {
+ let modelManager = new ModelManager(50);
+ const handle = (
+ modelId: string,
+ message: AnyWidgetMessage,
+ buffers: Base64String[],
+ ) => {
+ return handleWidgetMessage(modelId, message, buffers, modelManager);
+ };
+
+ beforeEach(() => {
+ // Clear the model manager before each test
+ modelManager = new ModelManager(50);
+ });
+
+ it("should set and get models", async () => {
+ const model = new Model({ count: 0 }, vi.fn(), vi.fn(), new Set());
+ modelManager.set("test-id", model);
+ const retrievedModel = await modelManager.get("test-id");
+ expect(retrievedModel).toBe(model);
+ });
+
+ it("should handle model not found", async () => {
+ await expect(modelManager.get("non-existent")).rejects.toThrow(
+ "Model not found for key: non-existent",
+ );
+ });
+
+ it("should delete models", async () => {
+ const model = new Model({ count: 0 }, vi.fn(), vi.fn(), new Set());
+ modelManager.set("test-id", model);
+ modelManager.delete("test-id");
+ await expect(modelManager.get("test-id")).rejects.toThrow();
+ });
+
+ it("should handle widget messages", async () => {
+ const openMessage: AnyWidgetMessage = {
+ method: "open",
+ state: { count: 0 },
+ buffer_paths: [],
+ };
+
+ await handle("test-id", openMessage, []);
+ const model = await modelManager.get("test-id");
+ expect(model.get("count")).toBe(0);
+
+ const updateMessage: AnyWidgetMessage = {
+ method: "update",
+ state: { count: 1 },
+ buffer_paths: [],
+ };
+
+ await handle("test-id", updateMessage, []);
+ expect(model.get("count")).toBe(1);
+ });
+
+ it("should handle close messages", async () => {
+ const model = new Model({ count: 0 }, vi.fn(), vi.fn(), new Set());
+ modelManager.set("test-id", model);
+
+ await handle("test-id", { method: "close" }, []);
+ await expect(modelManager.get("test-id")).rejects.toThrow();
+ });
+});
diff --git a/frontend/src/plugins/impl/anywidget/model.ts b/frontend/src/plugins/impl/anywidget/model.ts
index 82a6edf7dd..e39ee01b57 100644
--- a/frontend/src/plugins/impl/anywidget/model.ts
+++ b/frontend/src/plugins/impl/anywidget/model.ts
@@ -1,5 +1,11 @@
/* Copyright 2024 Marimo. All rights reserved. */
/* eslint-disable @typescript-eslint/no-explicit-any */
+import { sendModelValue } from "@/core/network/requests";
+import { assertNever } from "@/utils/assertNever";
+import { updateBufferPaths } from "@/utils/data-views";
+import { Deferred } from "@/utils/Deferred";
+import { throwNotImplemented } from "@/utils/functions";
+import type { Base64String } from "@/utils/json/base64";
import { Logger } from "@/utils/Logger";
import type { AnyModel } from "@anywidget/types";
import { dequal } from "dequal";
@@ -8,14 +14,63 @@ import { z } from "zod";
export type EventHandler = (...args: any[]) => void;
+class ModelManager {
+ private models = new Map<string, Deferred<Model<any>>>();
+
+ constructor(private timeout = 10_000) {}
+
+ get(key: string): Promise<Model<any>> {
+ let deferred = this.models.get(key);
+ if (deferred) {
+ return deferred.promise;
+ }
+
+ // If the model is not yet created, create the new deferred promise without resolving it
+ deferred = new Deferred<Model<any>>();
+ 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;
+ }
+
+ set(key: string, model: Model<any>): void {
+ let deferred = this.models.get(key);
+ if (!deferred) {
+ deferred = new Deferred<Model<any>>();
+ this.models.set(key, deferred);
+ }
+ deferred.resolve(model);
+ }
+
+ delete(key: string): void {
+ this.models.delete(key);
+ }
+}
+
+export const MODEL_MANAGER = new ModelManager();
+
export class Model<T extends Record<string, any>> implements AnyModel<T> {
private ANY_CHANGE_EVENT = "change";
private dirtyFields;
+ public static _modelManager: ModelManager = MODEL_MANAGER;
constructor(
private data: T,
private onChange: (value: Partial<T>) => void,
- private sendToWidget: (req: { content?: any }) => Promise<null | undefined>,
+ private sendToWidget: (req: {
+ content?: any;
+ buffers?: ArrayBuffer[] | ArrayBufferView[];
+ }) => Promise<null | undefined>,
initialDirtyFields: Set<keyof T>,
) {
this.dirtyFields = new Set(initialDirtyFields);
@@ -45,14 +100,20 @@ export class Model<T extends Record<string, any>> implements AnyModel<T> {
if (buffers) {
Logger.warn("buffers not supported in marimo anywidget.send");
}
- this.sendToWidget({ content }).then(callbacks);
+ this.sendToWidget({ content, buffers }).then(callbacks);
}
widget_manager = {
- get_model<TT extends Record<string, any>>(
- _model_id: string,
+ async get_model<TT extends Record<string, any>>(
+ model_id: string,
): Promise<AnyModel<TT>> {
- throw new Error("widget_manager not supported in marimo");
+ const model = await Model._modelManager.get(model_id);
+ if (!model) {
+ throw new Error(
+ `Model not found with id: ${model_id}. This is likely because the model was not registered.`,
+ );
+ }
+ return model;
},
};
@@ -99,7 +160,7 @@ export class Model<T extends Record<string, any>> implements AnyModel<T> {
* We want to notify all listeners with `msg:custom`
*/
receiveCustomMessage(message: any, buffers?: DataView[]): void {
- const response = WidgetMessageSchema.safeParse(message);
+ const response = AnyWidgetMessageSchema.safeParse(message);
if (response.success) {
const data = response.data;
switch (data.method) {
@@ -111,6 +172,9 @@ export class Model<T extends Record<string, any>> implements AnyModel<T> {
cb(data.content, buffers),
);
break;
+ case "open":
+ this.updateAndEmitDiffs(data.state as T);
+ break;
}
} else {
Logger.error("Failed to parse message", response.error);
@@ -138,10 +202,19 @@ export class Model<T extends Record<string, any>> implements AnyModel<T> {
}, 0);
}
-const WidgetMessageSchema = z.union([
+const BufferPathSchema = z.array(z.array(z.union([z.string(), z.number()])));
+const StateSchema = z.record(z.any());
+
+const AnyWidgetMessageSchema = z.discriminatedUnion("method", [
+ z.object({
+ method: z.literal("open"),
+ state: StateSchema,
+ buffer_paths: BufferPathSchema.optional(),
+ }),
z.object({
method: z.literal("update"),
- state: z.record(z.any()),
+ state: StateSchema,
+ buffer_paths: BufferPathSchema.optional(),
}),
z.object({
method: z.literal("custom"),
@@ -149,7 +222,87 @@ const WidgetMessageSchema = z.union([
}),
z.object({
method: z.literal("echo_update"),
- buffer_paths: z.array(z.array(z.union([z.string(), z.number()]))),
- state: z.record(z.any()),
+ buffer_paths: BufferPathSchema,
+ state: StateSchema,
+ }),
+ z.object({
+ method: z.literal("close"),
}),
]);
+
+export type AnyWidgetMessage = z.infer<typeof AnyWidgetMessageSchema>;
+
+export function isMessageWidgetState(msg: unknown): msg is AnyWidgetMessage {
+ if (msg == null) {
+ return false;
+ }
+
+ return AnyWidgetMessageSchema.safeParse(msg).success;
+}
+
+export async function handleWidgetMessage(
+ modelId: string,
+ msg: AnyWidgetMessage,
+ buffers: Base64String[],
+ modelManager: ModelManager,
+): Promise<void> {
+ if (msg.method === "echo_update") {
+ // We don't need to do anything with this message
+ return;
+ }
+
+ if (msg.method === "custom") {
+ const model = await modelManager.get(modelId);
+ model.receiveCustomMessage(msg.content);
+ return;
+ }
+
+ if (msg.method === "close") {
+ modelManager.delete(modelId);
+ return;
+ }
+
+ const { method, state, buffer_paths = [] } = msg;
+ const stateWithBuffers = updateBufferPaths(state, buffer_paths, buffers);
+
+ if (method === "open") {
+ const handleDataChange = (changeData: Record<string, any>) => {
+ if (buffer_paths) {
+ Logger.warn(
+ "Changed data with buffer paths may not be supported",
+ changeData,
+ );
+ // TODO: we may want to extract/undo DataView, to get back buffers and buffer_paths
+ }
+ sendModelValue({
+ modelId: modelId,
+ message: {
+ state: changeData,
+ bufferPaths: [],
+ },
+ buffers: [],
+ });
+ };
+
+ const model = new Model(
+ stateWithBuffers,
+ handleDataChange,
+ throwNotImplemented,
+ new Set(),
+ );
+ modelManager.set(modelId, model);
+ return;
+ }
+
+ if (method === "update") {
+ const model = await modelManager.get(modelId);
+ model.updateAndEmitDiffs(stateWithBuffers);
+ return;
+ }
+
+ assertNever(method);
+}
+
+export const visibleForTesting = {
+ ModelManager,
+};
diff --git a/frontend/src/utils/__tests__/data-views.test.ts b/frontend/src/utils/__tests__/data-views.test.ts
index 27c0efda06..33b33524fb 100644
--- a/frontend/src/utils/__tests__/data-views.test.ts
+++ b/frontend/src/utils/__tests__/data-views.test.ts
@@ -1,6 +1,7 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { describe, it, expect } from "vitest";
-import { updateBufferPaths, base64ToDataView } from "../data-views";
+import { updateBufferPaths, byteStringToDataView } from "../data-views";
+import type { ByteString, Base64String } from "../json/base64";
describe("updateBufferPaths", () => {
it("should return the original object if bufferPaths is null", () => {
@@ -35,12 +36,62 @@ describe("updateBufferPaths", () => {
expect(result).toEqual(input);
});
+
+ it("should update buffer paths with provided buffers", () => {
+ const input = {
+ a: 1,
+ b: {
+ c: "Hello",
+ d: "World",
+ },
+ };
+ const bufferPaths = [
+ ["b", "c"],
+ ["b", "d"],
+ ];
+ const buffers: Base64String[] = [
+ "SGVsbG8=" as Base64String,
+ "V29ybGQ=" as Base64String,
+ ]; // Base64 encoded "Hello" and "World"
+ const result = updateBufferPaths(input, bufferPaths, buffers);
+
+ expect(result.a).toBe(1);
+ const cView = result.b.c as unknown as DataView;
+ const dView = result.b.d as unknown as DataView;
+ expect(cView).toBeInstanceOf(DataView);
+ expect(dView).toBeInstanceOf(DataView);
+ expect(cView.byteLength).toBe(5);
+ expect(dView.byteLength).toBe(5);
+ });
+
+ it("should throw error when buffers and paths length mismatch", () => {
+ const input = { a: 1 };
+ const bufferPaths = [
+ ["b", "c"],
+ ["b", "d"],
+ ];
+ const buffers: Base64String[] = ["SGVsbG8=" as Base64String]; // Only one buffer for two paths
+
+ expect(() => updateBufferPaths(input, bufferPaths, buffers)).toThrow(
+ "Buffers and buffer paths not the same length",
+ );
+ });
+
+ it("should handle empty buffers array", () => {
+ const input = { a: 1 };
+ const bufferPaths = [["b", "c"]];
+ const buffers: Base64String[] = [];
+
+ expect(() => updateBufferPaths(input, bufferPaths, buffers)).toThrow(
+ "Buffers and buffer paths not the same length",
+ );
+ });
});
-describe("base64ToDataView", () => {
+describe("byteStringToDataView", () => {
it("should convert a base64 string to a DataView", () => {
- const input = "Hello";
- const result = base64ToDataView(input);
+ const input = "Hello" as ByteString;
+ const result = byteStringToDataView(input);
expect(result).toBeInstanceOf(DataView);
expect(result.byteLength).toBe(5);
@@ -52,8 +103,8 @@ describe("base64ToDataView", () => {
});
it("should handle empty string", () => {
- const input = "";
- const result = base64ToDataView(input);
+ const input = "" as ByteString;
+ const result = byteStringToDataView(input);
expect(result).toBeInstanceOf(DataView);
expect(result.byteLength).toBe(0);
diff --git a/frontend/src/utils/__tests__/errors.test.ts b/frontend/src/utils/__tests__/errors.test.ts
index f86bbb4cb4..fb74ae9c3f 100644
--- a/frontend/src/utils/__tests__/errors.test.ts
+++ b/frontend/src/utils/__tests__/errors.test.ts
@@ -14,6 +14,11 @@ describe("prettyError", () => {
expect(prettyError(error)).toBe("Detailed error message");
});
+ it("extracts details from Error objects with error", () => {
+ const error = { error: "Detailed error message" };
+ expect(prettyError(error)).toBe("Detailed error message");
+ });
+
it("extracts details from Error message if JSON", () => {
const error = new Error('{"detail": "JSON error message"}');
expect(prettyError(error)).toBe("JSON error message");
diff --git a/frontend/src/utils/data-views.ts b/frontend/src/utils/data-views.ts
index af04eaa380..5959974274 100644
--- a/frontend/src/utils/data-views.ts
+++ b/frontend/src/utils/data-views.ts
@@ -1,35 +1,50 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { get, set } from "lodash-es";
import { Logger } from "./Logger";
+import { type ByteString, typedAtob, type Base64String } from "./json/base64";
+import { invariant } from "./invariant";
/**
* Update the object with DataView buffers at the specified paths.
*/
-export function updateBufferPaths<T extends object>(
+export function updateBufferPaths<T extends Record<string, unknown>>(
inputObject: T,
bufferPaths: Array<Array<string | number>> | null | undefined,
+ buffers?: Base64String[] | null | undefined,
): T {
// If no buffer paths, return the original object
if (!bufferPaths || bufferPaths.length === 0) {
return inputObject;
}
+ // If has buffers, assert they are the same size
+ if (buffers) {
+ invariant(
+ buffers.length === bufferPaths.length,
+ "Buffers and buffer paths not the same length",
+ );
+ }
+
let object = structuredClone(inputObject);
- for (const bufferPath of bufferPaths) {
- const bytes = get(object, bufferPath);
+ for (const [i, bufferPath] of bufferPaths.entries()) {
+ // If buffers exists, we use that value
+ // Otherwise we grab it from inside the inputObject
+ const bytes: ByteString = buffers
+ ? typedAtob(buffers[i])
+ : get(object, bufferPath);
if (!bytes) {
Logger.warn("Could not find buffer at path", bufferPath);
continue;
}
- const buffer = base64ToDataView(bytes);
+ const buffer = byteStringToDataView(bytes);
object = set(object, bufferPath, buffer);
}
return object;
}
-export const base64ToDataView = (bytes: string) => {
+export const byteStringToDataView = (bytes: ByteString) => {
const buffer = new ArrayBuffer(bytes.length);
const view = new DataView(buffer);
for (let i = 0; i < bytes.length; i++) {
diff --git a/frontend/src/utils/errors.ts b/frontend/src/utils/errors.ts
index 2ff2931726..698a7f9761 100644
--- a/frontend/src/utils/errors.ts
+++ b/frontend/src/utils/errors.ts
@@ -6,6 +6,10 @@ const DetailsSchema = z.object({
detail: z.string(),
});
+const ErrorSchema = z.object({
+ error: z.string(),
+});
+
export function prettyError(error: unknown): string {
if (!error) {
return "Unknown error";
@@ -22,6 +26,10 @@ export function prettyError(error: unknown): string {
if (details.success) {
return details.data.detail;
}
+ const parsed = ErrorSchema.safeParse(error);
+ if (parsed.success) {
+ return parsed.data.error;
+ }
}
try {
return JSON.stringify(error);
@@ -39,6 +47,10 @@ function maybeExtractDetails(message: string): string {
if (details.success) {
return details.data.detail;
}
+ const error = ErrorSchema.safeParse(parsed);
+ if (error.success) {
+ return error.data.error;
+ }
return message;
}
diff --git a/frontend/src/utils/json/base64.ts b/frontend/src/utils/json/base64.ts
index 532ec113d4..f70262d2de 100644
--- a/frontend/src/utils/json/base64.ts
+++ b/frontend/src/utils/json/base64.ts
@@ -9,6 +9,10 @@ export type Base64String<T = unknown> = TypedString<"Base64"> & {
_of_: T;
};
+export type ByteString<T = unknown> = TypedString<"ByteString"> & {
+ _of_: T;
+};
+
export type DataURLString = `data:${string};base64,${Base64String<string>}`;
// Deserialization: Base64 to String
@@ -25,3 +29,11 @@ export function deserializeJson<T>(jsonString: JsonString<T>): T {
export function base64ToDataURL<T>(base64: Base64String<T>, mimeType: string) {
return `data:${mimeType};base64,${base64}`;
}
+
+export function typedAtob<T>(base64: Base64String<T>): ByteString<T> {
+ return window.atob(base64) as ByteString<T>;
+}
+
+export function typedBtoa<T>(bytes: ByteString<T>): Base64String<T> {
+ return window.btoa(bytes) as Base64String<T>;
+}
diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.py
index b079f47330..c51d598152 100644
--- a/marimo/_cli/development/commands.py
+++ b/marimo/_cli/development/commands.py
@@ -200,6 +200,7 @@ def _generate_server_api_schema() -> dict[str, Any]:
requests.PreviewSQLTableRequest,
requests.RenameRequest,
requests.SetCellConfigRequest,
+ requests.SetModelMessageRequest,
requests.SetUserConfigRequest,
requests.StopRequest,
]
diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.py
index a891d4940f..3e6fe77750 100644
--- a/marimo/_dependencies/dependencies.py
+++ b/marimo/_dependencies/dependencies.py
@@ -180,6 +180,7 @@ class DependencyManager:
openai = Dependency("openai")
matplotlib = Dependency("matplotlib")
anywidget = Dependency("anywidget")
+ traitlets = Dependency("traitlets")
watchdog = Dependency("watchdog")
ipython = Dependency("IPython")
ipywidgets = Dependency("ipywidgets")
diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.py
index eee65d1000..e19e04bfd4 100644
--- a/marimo/_messaging/ops.py
+++ b/marimo/_messaging/ops.py
@@ -54,7 +54,7 @@ from marimo._runtime.context.types import ContextNotInitializedError
from marimo._runtime.context.utils import get_mode
from marimo._runtime.layout.layout import LayoutConfig
from marimo._secrets.models import SecretKeysWithProvider
-from marimo._types.ids import CellId_t, RequestId
+from marimo._types.ids import CellId_t, RequestId, WidgetModelId
from marimo._utils.platform import is_pyodide, is_windows
LOGGER = loggers.marimo_logger()
@@ -394,9 +394,10 @@ class SendUIElementMessage(Op):
"""Send a message to a UI element."""
name: ClassVar[str] = "send-ui-element-message"
- ui_element: str
+ ui_element: Optional[str]
+ model_id: Optional[WidgetModelId]
message: dict[str, Any]
- buffers: Optional[list[str]]
+ buffers: Optional[list[str]] = None
@dataclass
diff --git a/marimo/_output/formatters/repr_formatters.py b/marimo/_output/formatters/repr_formatters.py
index 0085470640..03c24dfb68 100644
--- a/marimo/_output/formatters/repr_formatters.py
+++ b/marimo/_output/formatters/repr_formatters.py
@@ -56,7 +56,11 @@ def maybe_get_repr_formatter(
# N.B. We cannot pass this as an argument to the method
# because this unfortunately could break some libraries
# (e.g. ibis)
- if "text/plain" in contents and len(contents) > 1:
+ if (
+ isinstance(contents, dict)
+ and "text/plain" in contents
+ and len(contents) > 1
+ ):
contents.pop("text/plain")
# Convert markdown/latex to text/html if text/html is
# not present
diff --git a/marimo/_plugins/ui/_core/ui_element.py b/marimo/_plugins/ui/_core/ui_element.py
index 55ba17203f..05aecb3759 100644
--- a/marimo/_plugins/ui/_core/ui_element.py
+++ b/marimo/_plugins/ui/_core/ui_element.py
@@ -438,6 +438,7 @@ class UIElement(Html, Generic[S, T]):
SendUIElementMessage(
ui_element=self._id,
+ model_id=None,
message=message,
buffers=[
base64.b64encode(buffer).decode() for buffer in (buffers or [])
diff --git a/marimo/_plugins/ui/_impl/anywidget/init.py b/marimo/_plugins/ui/_impl/anywidget/init.py
index ab78acf990..f6ef6e909f 100644
--- a/marimo/_plugins/ui/_impl/anywidget/init.py
+++ b/marimo/_plugins/ui/_impl/anywidget/init.py
@@ -21,10 +21,10 @@ def init_marimo_widget(w: ipywidgets.Widget) -> None:
import ipywidgets # type: ignore
__protocol_version__ = ipywidgets._version.__protocol_version__
- _remove_buffers = ipywidgets.widgets.widget._remove_buffers # type: ignore
+ from marimo._plugins.ui._impl.anywidget.utils import extract_buffer_paths
# Get the initial state of the widget
- state, buffer_paths, buffers = _remove_buffers(w.get_state()) # type: ignore
+ state, buffer_paths, buffers = extract_buffer_paths(w.get_state())
# Generate a random model_id so we can assign the same id to the comm
if getattr(w, "_model_id", None) is None:
@@ -33,9 +33,9 @@ def init_marimo_widget(w: ipywidgets.Widget) -> None:
# Initialize the comm...this will also send the initial state of the widget
w.comm = MarimoComm(
comm_id=w._model_id, # pyright: ignore
- comm_manager=COMM_MANAGER,
+ comm_manager=WIDGET_COMM_MANAGER,
target_name="jupyter.widgets",
- data={"state": state, "buffer_paths": buffer_paths},
+ data={"state": state, "buffer_paths": buffer_paths, "method": "open"},
buffers=cast(BufferType, buffers),
# TODO: should this be hard-coded?
metadata={"version": __protocol_version__},
@@ -43,4 +43,4 @@ def init_marimo_widget(w: ipywidgets.Widget) -> None:
)
-COMM_MANAGER = MarimoCommManager()
+WIDGET_COMM_MANAGER = MarimoCommManager()
diff --git a/marimo/_plugins/ui/_impl/anywidget/types.py b/marimo/_plugins/ui/_impl/anywidget/types.py
new file mode 100644
index 0000000000..c0816e1d81
--- /dev/null
+++ b/marimo/_plugins/ui/_impl/anywidget/types.py
@@ -0,0 +1,59 @@
+from __future__ import annotations
+
+from typing import Any, Literal, NewType, TypedDict, Union
+
+# AnyWidget model id
+WidgetModelId = NewType("WidgetModelId", str)
+
+# Buffer paths
+BufferPaths = list[list[Union[str, int]]]
+
+# Widget model state
+WidgetModelState = dict[str, Any]
+
+# Widget model state without buffers
+WidgetModelStateWithoutBuffers = dict[str, Any]
+
+
+# AnyWidget model message
+class TypedModelMessage(TypedDict):
+ """
+ A typed message for AnyWidget models.
+
+ Args:
+ state: The state of the model.
+ buffer_paths: The buffer paths to update.
+ """
+
+ state: WidgetModelStateWithoutBuffers
+ buffer_paths: BufferPaths
+
+
+class TypedModelAction(TypedModelMessage):
+ """
+ A typed message for AnyWidget models.
+
+ Args:
+ method: The method to call on the model.
+ state: The state of the model.
+ buffer_paths: The buffer paths to update.
+ """
+
+ method: Literal["open", "update", "custom", "echo_update"]
+
+
+class TypedModelMessageContent(TypedDict):
+ """A typed payload for AnyWidget models."""
+
+ data: TypedModelAction
+
+
+class TypedModelMessagePayload(TypedDict):
+ """
+ A typed payload for AnyWidget models.
+
+ This interface is what AnyWidget's comm.handle_msg expects
+ """
+
+ content: TypedModelMessageContent
+ buffers: list[bytes]
diff --git a/marimo/_plugins/ui/_impl/anywidget/utils.py b/marimo/_plugins/ui/_impl/anywidget/utils.py
new file mode 100644
index 0000000000..e4f92b4544
--- /dev/null
+++ b/marimo/_plugins/ui/_impl/anywidget/utils.py
@@ -0,0 +1,59 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._plugins.ui._impl.anywidget.types import (
+ BufferPaths,
+ TypedModelMessage,
+ WidgetModelState,
+ WidgetModelStateWithoutBuffers,
+)
+
+if TYPE_CHECKING:
+ from typing_extensions import TypeIs
+
+
+def extract_buffer_paths(
+ message: WidgetModelState,
+) -> tuple[WidgetModelStateWithoutBuffers, BufferPaths, list[bytes]]:
+ """
+ Extract buffer paths from a message.
+ """
+ DependencyManager.ipywidgets.require("for anywidget support.")
+ import ipywidgets # type: ignore
+
+ _remove_buffers = ipywidgets.widgets.widget._remove_buffers # type: ignore
+
+ # Get the initial state of the widget
+ state, buffer_paths, buffers = _remove_buffers(message) # type: ignore
+
+ return state, buffer_paths, buffers # type: ignore
+
+
+def insert_buffer_paths(
+ state: WidgetModelStateWithoutBuffers,
+ buffer_paths: BufferPaths,
+ buffers: list[bytes],
+) -> WidgetModelState:
+ """
+ Insert buffer paths into a message.
+ """
+ DependencyManager.ipywidgets.require("for anywidget support.")
+ import ipywidgets # type: ignore
+
+ _put_buffers = ipywidgets.widgets.widget._put_buffers # type: ignore
+ _put_buffers(state, buffer_paths, buffers)
+ return state
+
+
+def is_model_message(message: object) -> TypeIs[TypedModelMessage]:
+ """
+ Check if a message is a model message.
+ """
+ if not isinstance(message, dict):
+ return False
+ keys = ("method", "state", "buffer_paths")
+ if not all(key in message for key in keys):
+ return False
+ return True
diff --git a/marimo/_plugins/ui/_impl/comm.py b/marimo/_plugins/ui/_impl/comm.py
index 1a0570ab04..127ef31627 100644
--- a/marimo/_plugins/ui/_impl/comm.py
+++ b/marimo/_plugins/ui/_impl/comm.py
@@ -2,11 +2,23 @@
from __future__ import annotations
import base64
-from typing import Any, Callable, Optional
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, Any, Callable, Optional, cast
+
+from marimo._loggers import marimo_logger
+from marimo._types.ids import WidgetModelId
+
+if TYPE_CHECKING:
+ from marimo._plugins.ui._impl.anywidget.types import (
+ TypedModelMessagePayload,
+ )
+ from marimo._runtime.requests import ModelMessage
+
+LOGGER = marimo_logger()
class MarimoCommManager:
- comms: dict[str, MarimoComm] = {}
+ comms: dict[WidgetModelId, MarimoComm] = {}
def register_comm(self, comm: MarimoComm) -> str:
comm_id = comm.comm_id
@@ -16,10 +28,36 @@ class MarimoCommManager:
def unregister_comm(self, comm: MarimoComm) -> MarimoComm:
return self.comms.pop(comm.comm_id)
+ def receive_comm_message(
+ self,
+ comm_id: WidgetModelId,
+ message: ModelMessage,
+ buffers: Optional[list[bytes]],
+ ) -> None:
+ if comm_id not in self.comms:
+ LOGGER.warning("Received message for unknown comm", comm_id)
+ return
+
+ comm = self.comms[comm_id]
+
+ msg: TypedModelMessagePayload = {
+ "content": {
+ "data": {
+ "state": message.state,
+ "method": "update",
+ "buffer_paths": message.buffer_paths,
+ }
+ },
+ "buffers": buffers or [],
+ }
-MsgCallback = Callable[[dict[str, object]], None]
-DataType = Optional[dict[str, object]]
-MetadataType = Optional[dict[str, object]]
+ comm.handle_msg(cast(Msg, msg))
+
+
+Msg = dict[str, Any]
+MsgCallback = Callable[[Msg], None]
+DataType = Optional[dict[str, Any]]
+MetadataType = Optional[dict[str, Any]]
BufferType = Optional[list[bytes]]
COMM_MESSAGE_NAME = "marimo_comm_msg"
@@ -27,6 +65,14 @@ COMM_OPEN_NAME = "marimo_comm_open"
COMM_CLOSE_NAME = "marimo_comm_close"
+@dataclass
+class MessageBufferData:
+ data: dict[str, Any]
+ metadata: dict[str, Any]
+ buffers: list[bytes]
+ model_id: WidgetModelId
+
+
# Compare to `ipykernel.comm.Comm`
# (uses the marimo context instead of a Kernel to send/receive messages).
# Also note that `ipywidgets.widgets.Widget` is responsible to
@@ -36,14 +82,9 @@ class MarimoComm:
# `if self.comm.kernel is not None`
kernel = "marimo"
- _msg_callback: Optional[MsgCallback]
- _close_callback: Optional[MsgCallback]
- _closed: bool = False
- _closed_data: dict[str, object] = {}
-
def __init__(
self,
- comm_id: str,
+ comm_id: WidgetModelId,
comm_manager: MarimoCommManager,
target_name: str,
data: DataType = None,
@@ -51,12 +92,17 @@ class MarimoComm:
buffers: BufferType = None,
**keys: object,
) -> None:
+ self._msg_callback: Optional[MsgCallback] = None
+ self._close_callback: Optional[MsgCallback] = None
+ self._closed: bool = False
+ self._closed_data: dict[str, object] = {}
+
self.comm_id = comm_id
self.comm_manager = comm_manager
self.target_name = target_name
- self.open(data=data, metadata=metadata, buffers=buffers, **keys)
self.ui_element_id: Optional[str] = None
- self._publish_message_buffer: list[Any] = []
+ self._publish_message_buffer: list[MessageBufferData] = []
+ self.open(data=data, metadata=metadata, buffers=buffers, **keys)
def open(
self,
@@ -139,28 +185,53 @@ class MarimoComm:
metadata = {} if metadata is None else metadata
buffers = [] if buffers is None else buffers
+ if msg_type == COMM_OPEN_NAME:
+ self._publish_message_buffer.append(
+ MessageBufferData(
+ data, metadata, buffers, model_id=self.comm_id
+ )
+ )
+ self.flush()
+ return
+
if msg_type == COMM_MESSAGE_NAME:
- self._publish_message_buffer.append((data, metadata, buffers))
+ self._publish_message_buffer.append(
+ MessageBufferData(
+ data, metadata, buffers, model_id=self.comm_id
+ )
+ )
self.flush()
+ return
- def flush(self) -> None:
- if not self.ui_element_id:
- # If there is no ui_element_id, then it has not been rendered
- # to the frontend, and just exists in python
- # We can drop these instead of holding onto them.
- self._publish_message_buffer = []
+ if msg_type == COMM_CLOSE_NAME:
+ self._publish_message_buffer.append(
+ MessageBufferData(
+ data, metadata, buffers, model_id=self.comm_id
+ )
+ )
+ self.flush()
return
+ LOGGER.warning(
+ "Unknown message type",
+ msg_type,
+ data,
+ )
+
+ def flush(self) -> None:
from marimo._messaging.ops import SendUIElementMessage
while self._publish_message_buffer:
- data, _metadata, buffers = self._publish_message_buffer.pop(0)
-
+ item = self._publish_message_buffer.pop(0)
SendUIElementMessage(
+ # ui_element_id can be None. In this case, we are creating a model
+ # not tied to a specific UI element
ui_element=self.ui_element_id,
- message=data,
+ model_id=item.model_id,
+ message=item.data,
buffers=[
- base64.b64encode(buffer).decode() for buffer in buffers
+ base64.b64encode(buffer).decode()
+ for buffer in item.buffers
],
).broadcast()
@@ -172,10 +243,22 @@ class MarimoComm:
def on_close(self, callback: MsgCallback) -> None:
self._close_callback = callback
- def handle_msg(self, msg: dict[str, object]) -> None:
+ def handle_msg(self, msg: Msg) -> None:
if self._msg_callback is not None:
self._msg_callback(msg)
+ else:
+ LOGGER.warning(
+ "Received message for comm but no callback registered",
+ self.comm_id,
+ msg,
+ )
- def handle_close(self, msg: dict[str, object]) -> None:
+ def handle_close(self, msg: Msg) -> None:
if self._close_callback is not None:
self._close_callback(msg)
+ else:
+ LOGGER.warning(
+ "Received close for comm but no callback registered",
+ self.comm_id,
+ msg,
+ )
diff --git a/marimo/_plugins/ui/_impl/from_anywidget.py b/marimo/_plugins/ui/_impl/from_anywidget.py
index 156ec54d81..703880ec57 100644
--- a/marimo/_plugins/ui/_impl/from_anywidget.py
+++ b/marimo/_plugins/ui/_impl/from_anywidget.py
@@ -10,6 +10,10 @@ import marimo._output.data.data as mo_data
from marimo import _loggers
from marimo._output.rich_help import mddoc
from marimo._plugins.ui._core.ui_element import InitializationArgs, UIElement
+from marimo._plugins.ui._impl.anywidget.utils import (
+ extract_buffer_paths,
+ insert_buffer_paths,
+)
from marimo._plugins.ui._impl.comm import MarimoComm
from marimo._runtime.functions import Function
@@ -84,13 +88,9 @@ class anywidget(UIElement[T, T]):
# This gets set to True in super().__init__()
self._initialized = False
- import ipywidgets # type: ignore
-
- _remove_buffers = ipywidgets.widgets.widget._remove_buffers # type: ignore
-
# Get state with custom serializers properly applied
- state = widget.get_state()
- _state_no_buffers, buffer_paths, buffers = _remove_buffers(state) # type: ignore
+ state: dict[str, Any] = widget.get_state()
+ _state_no_buffers, buffer_paths, buffers = extract_buffer_paths(state)
# Remove widget-specific system traits not needed for the frontend
ignored_traits = [
@@ -127,8 +127,7 @@ class anywidget(UIElement[T, T]):
css: str = widget._css if hasattr(widget, "_css") else "" # type: ignore [unused-ignore] # noqa: E501
def on_change(change: T) -> None:
- _put_buffers = ipywidgets.widgets.widget._put_buffers # type: ignore
- _put_buffers(change, buffer_paths, buffers)
+ insert_buffer_paths(change, buffer_paths, buffers)
current_state: dict[str, Any] = widget.get_state()
changed_state: dict[str, Any] = {}
for k, v in change.items():
diff --git a/marimo/_plugins/ui/_impl/from_panel.py b/marimo/_plugins/ui/_impl/from_panel.py
index 320d708cae..7490512faf 100644
--- a/marimo/_plugins/ui/_impl/from_panel.py
+++ b/marimo/_plugins/ui/_impl/from_panel.py
@@ -17,6 +17,7 @@ from marimo._output.rich_help import mddoc
from marimo._plugins.ui._core.ui_element import InitializationArgs, UIElement
from marimo._plugins.ui._impl.comm import MarimoComm, MarimoCommManager
from marimo._runtime.functions import Function
+from marimo._types.ids import WidgetModelId
if TYPE_CHECKING:
from panel.viewable import Viewable
@@ -50,7 +51,7 @@ def _get_comm_class() -> type[Any]:
def __init__(self, *args: Any, **kwargs: Any):
super().__init__(*args, **kwargs)
self._comm = MarimoComm(
- comm_id=str(self.id),
+ comm_id=WidgetModelId(str(self.id)),
target_name="panel.comms",
data={},
comm_manager=COMM_MANAGER,
diff --git a/marimo/_runtime/requests.py b/marimo/_runtime/requests.py
index 7786b203af..ccc4bfcd9f 100644
--- a/marimo/_runtime/requests.py
+++ b/marimo/_runtime/requests.py
@@ -17,7 +17,7 @@ from uuid import uuid4
from marimo._ast.app_config import _AppConfig
from marimo._config.config import MarimoConfig
from marimo._data.models import DataTableSource
-from marimo._types.ids import CellId_t, RequestId, UIElementId
+from marimo._types.ids import CellId_t, RequestId, UIElementId, WidgetModelId
if TYPE_CHECKING:
from starlette.datastructures import URL
@@ -353,6 +353,19 @@ class ListSecretKeysRequest:
request_id: RequestId
+@dataclass
+class ModelMessage:
+ state: dict[str, Any]
+ buffer_paths: list[list[Union[str, int]]]
+
+
+@dataclass
+class SetModelMessageRequest:
+ model_id: WidgetModelId
+ message: ModelMessage
+ buffers: Optional[list[str]] = None
+
+
@dataclass
class RefreshSecretsRequest:
pass
@@ -376,6 +389,7 @@ ControlRequest = Union[
RenameRequest,
SetCellConfigRequest,
SetUIElementValueRequest,
+ SetModelMessageRequest,
SetUserConfigRequest,
StopRequest,
]
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index bbb5cec0c5..91950f6167 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -90,6 +90,7 @@ from marimo._messaging.types import (
from marimo._output.rich_help import mddoc
from marimo._plugins.core.web_component import JSONType
from marimo._plugins.ui._core.ui_element import MarimoConvertValueException
+from marimo._plugins.ui._impl.anywidget.init import WIDGET_COMM_MANAGER
from marimo._runtime import dataflow, handlers, marimo_pdb, patches
from marimo._runtime.app_meta import AppMeta
from marimo._runtime.context import (
@@ -133,6 +134,7 @@ from marimo._runtime.requests import (
RefreshSecretsRequest,
RenameRequest,
SetCellConfigRequest,
+ SetModelMessageRequest,
SetUIElementValueRequest,
SetUserConfigRequest,
StopRequest,
@@ -2053,6 +2055,15 @@ class Kernel:
async def handle_rename(request: RenameRequest) -> None:
await self.rename_file(request.filename)
+ async def handle_receive_model_message(
+ request: SetModelMessageRequest,
+ ) -> None:
+ buffers = request.buffers or []
+ buffers_as_bytes = [buffer.encode("utf-8") for buffer in buffers]
+ WIDGET_COMM_MANAGER.receive_comm_message(
+ request.model_id, request.message, buffers_as_bytes
+ )
+
async def handle_function_call(request: FunctionCallRequest) -> None:
status, ret, _ = await self.function_call_request(request)
LOGGER.debug("Function returned with status %s", status)
@@ -2090,6 +2101,7 @@ class Kernel:
handler.register(RenameRequest, handle_rename)
handler.register(SetCellConfigRequest, self.set_cell_config)
handler.register(SetUIElementValueRequest, handle_set_ui_element_value)
+ handler.register(SetModelMessageRequest, handle_receive_model_message)
handler.register(SetUserConfigRequest, handle_set_user_config)
handler.register(StopRequest, handle_stop)
# Datasets
diff --git a/marimo/_server/api/endpoints/execution.py b/marimo/_server/api/endpoints/execution.py
index fabb18e0b1..b6e1045e3c 100644
--- a/marimo/_server/api/endpoints/execution.py
+++ b/marimo/_server/api/endpoints/execution.py
@@ -15,6 +15,7 @@ from marimo._runtime.requests import (
FunctionCallRequest,
HTTPRequest,
PdbRequest,
+ SetModelMessageRequest,
SetUIElementValueRequest,
)
from marimo._server.api.deps import AppState
@@ -75,6 +76,35 @@ async def set_ui_element_values(
return SuccessResponse()
[email protected]("/set_model_value")
+async def set_model_values(
+ *,
+ request: Request,
+) -> BaseResponse:
+ """
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/SetModelMessageRequest"
+ responses:
+ 200:
+ description: Set model value
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/SuccessResponse"
+ """
+ app_state = AppState(request)
+ body = await parse_request(request, cls=SetModelMessageRequest)
+ app_state.require_current_session().put_control_request(
+ body,
+ from_consumer_id=ConsumerId(app_state.require_current_session_id()),
+ )
+
+ return SuccessResponse()
+
+
@router.post("/instantiate")
async def instantiate(
*,
diff --git a/marimo/_server/session/session_view.py b/marimo/_server/session/session_view.py
index 1ee4477a7d..88fe2b84e0 100644
--- a/marimo/_server/session/session_view.py
+++ b/marimo/_server/session/session_view.py
@@ -13,6 +13,7 @@ from marimo._messaging.ops import (
DataSourceConnections,
Interrupted,
MessageOperation,
+ SendUIElementMessage,
UpdateCellCodes,
UpdateCellIdsRequest,
Variables,
@@ -27,7 +28,7 @@ from marimo._runtime.requests import (
SetUIElementValueRequest,
)
from marimo._sql.engines.duckdb import INTERNAL_DUCKDB_ENGINE
-from marimo._types.ids import CellId_t
+from marimo._types.ids import CellId_t, WidgetModelId
from marimo._utils.lists import as_list
from marimo._utils.parse_dataclass import parse_raw
@@ -82,6 +83,10 @@ class SessionView:
self.last_execution_time: dict[CellId_t, float] = {}
# Any stale code that was read from a file-watcher
self.stale_code: Optional[UpdateCellCodes] = None
+ # Model messages
+ self.model_messages: dict[
+ WidgetModelId, list[SendUIElementMessage]
+ ] = {}
# Auto-saving
self.auto_export_state = AutoExportState()
@@ -240,6 +245,14 @@ class SessionView:
):
self.stale_code = operation
+ elif isinstance(operation, SendUIElementMessage):
+ if operation.model_id is None:
+ return
+ messages = self.model_messages.get(operation.model_id, [])
+ messages.append(operation)
+ # TODO: cleanup/merge previous 'update' messages
+ self.model_messages[operation.model_id] = messages
+
def get_cell_outputs(
self, ids: list[CellId_t]
) -> dict[CellId_t, CellOutput]:
@@ -298,6 +311,9 @@ class SessionView:
all_ops.extend(self.cell_operations.values())
if self.stale_code:
all_ops.append(self.stale_code)
+ if self.model_messages:
+ for messages in self.model_messages.values():
+ all_ops.extend(messages)
return all_ops
def mark_auto_export_html(self) -> None:
diff --git a/marimo/_smoke_tests/anywidget_examples/lonboard_example.py b/marimo/_smoke_tests/anywidget_examples/lonboard_example.py
new file mode 100644
index 0000000000..1fd5ebf480
--- /dev/null
+++ b/marimo/_smoke_tests/anywidget_examples/lonboard_example.py
@@ -0,0 +1,100 @@
+# /// script
+# requires-python = ">=3.13"
+# dependencies = [
+# "geopandas==1.0.1",
+# "lonboard==0.10.4",
+# "marimo",
+# "matplotlib==3.10.3",
+# "palettable==3.3.3",
+# "pandas==2.2.3",
+# "pyarrow==20.0.0",
+# "shapely==2.1.1",
+# ]
+# ///
+
+import marimo
+
+__generated_with = "0.13.10"
+app = marimo.App(width="medium")
+
+
+def _():
+ import marimo as mo
+
+ from pathlib import Path
+
+ import geopandas as gpd
+ import pandas as pd
+ import shapely
+ from palettable.colorbrewer.diverging import BrBG_10
+
+ from lonboard import Map, ScatterplotLayer
+ from lonboard.colormap import apply_continuous_cmap
+ return (
+ BrBG_10,
+ Map,
+ Path,
+ ScatterplotLayer,
+ apply_continuous_cmap,
+ gpd,
+ mo,
+ pd,
+ shapely,
+ )
+
+
+def _(Path, gpd, pd, shapely):
+ _url = "https://ookla-open-data.s3.us-west-2.amazonaws.com/parquet/performance/type=mobile/year=2019/quarter=1/2019-01-01_performance_mobile_tiles.parquet"
+
+ _local_path = Path("internet-speeds.parquet")
+ if _local_path.exists():
+ gdf = gpd.read_parquet(_local_path)
+ else:
+ _columns = ["avg_d_kbps", "tile"]
+ _df = pd.read_parquet(_url, columns=_columns)
+
+ _tile_geometries = shapely.from_wkt(_df["tile"])
+ _tile_centroids = shapely.centroid(_tile_geometries)
+ gdf = gpd.GeoDataFrame(
+ _df[["avg_d_kbps"]], geometry=_tile_centroids, crs="EPSG:4326"
+ )
+ gdf.to_parquet(_local_path)
+
+ gdf
+ return (gdf,)
+
+
+def _(Map, ScatterplotLayer, gdf, mo):
+ layer = ScatterplotLayer.from_geopandas(gdf)
+ min_bound = mo.ui.slider(
+ 0, 100_000, value=5000, show_value=True, label="min bound"
+ )
+ max_bound = mo.ui.slider(
+ 0, 100_000, value=50_000, show_value=True, label="max bound"
+ )
+ mo.vstack([min_bound, max_bound, Map(layer, _height=600)])
+ return layer, max_bound, min_bound
+
+
+def _(BrBG_10, apply_continuous_cmap, gdf, layer, max_bound, min_bound):
+ normalized_download_speed = (gdf["avg_d_kbps"] - min_bound.value) / (
+ max_bound.value - min_bound.value
+ )
+ layer.get_fill_color = apply_continuous_cmap(
+ normalized_download_speed, BrBG_10, alpha=0.7
+ )
+ return
+
+
+def _(layer):
+ layer.get_fill_color[0]
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_smoke_tests/anywidget_smoke_tests/maplibre_example.py b/marimo/_smoke_tests/anywidget_smoke_tests/maplibre_example.py
index 02868967f6..5b40a4a52e 100644
--- a/marimo/_smoke_tests/anywidget_smoke_tests/maplibre_example.py
+++ b/marimo/_smoke_tests/anywidget_smoke_tests/maplibre_example.py
@@ -8,26 +8,26 @@
import marimo
-__generated_with = "0.8.0"
+__generated_with = "0.13.10"
app = marimo.App(width="medium")
@app.cell
-def __():
+def _():
import marimo as mo
import functools
- return functools, mo
+ return (mo,)
@app.cell
-def __():
+def _():
from maplibre.controls import NavigationControl, ScaleControl
from maplibre.ipywidget import MapOptions, MapWidget
return MapOptions, MapWidget, NavigationControl, ScaleControl
@app.cell
-def __():
+def _():
deck_grid_layer = {
"@@type": "GridLayer",
"id": "GridLayer",
@@ -40,65 +40,59 @@ def __():
"cellSize": 200,
"pickable": True,
}
- return deck_grid_layer,
+ return (deck_grid_layer,)
@app.cell
-def __(MapOptions):
+def _(MapOptions):
map_options = MapOptions(
center=(-122.4, 37.74),
zoom=12,
hash=True,
pitch=40,
)
- return map_options,
+ return (map_options,)
@app.cell
-def __(MapWidget, NavigationControl, deck_grid_layer, map_options, mo):
+def _(MapWidget, NavigationControl, deck_grid_layer, map_options, mo):
m = MapWidget(map_options)
m.use_message_queue(False)
m.add_control(NavigationControl())
m.add_deck_layers([deck_grid_layer])
m = mo.ui.anywidget(m)
m
- return m,
+ return (m,)
@app.cell
-def __(mo):
+def _(mo):
add_control_button = mo.ui.run_button(label="add scale control")
add_control_button
- return add_control_button,
+ return (add_control_button,)
@app.cell
-def __(ScaleControl, add_control_button, m):
+def _(ScaleControl, add_control_button, m):
if add_control_button.value:
m.add_control(ScaleControl())
return
@app.cell
-def __(m):
+def _(m):
m.clicked
return
@app.cell
-def __(m):
- m.zoom
- return
-
-
-def __(m):
+def _(m):
m.center
return
@app.cell
-def __():
+def _():
return
diff --git a/marimo/_smoke_tests/anywidget_smoke_tests/mosaic_example.py b/marimo/_smoke_tests/anywidget_smoke_tests/mosaic_example.py
index 9841d9a23f..df3b470e61 100644
--- a/marimo/_smoke_tests/anywidget_smoke_tests/mosaic_example.py
+++ b/marimo/_smoke_tests/anywidget_smoke_tests/mosaic_example.py
@@ -8,14 +8,15 @@
# ]
# ///
# Copyright 2024 Marimo. All rights reserved.
+
import marimo
-__generated_with = "0.7.2"
+__generated_with = "0.13.10"
app = marimo.App(width="medium")
@app.cell
-def __(__file__):
+def _():
import pandas as pd
import marimo as mo
import os
@@ -37,14 +38,20 @@ def __(__file__):
spec.pop("data")
w = mo.ui.anywidget(MosaicWidget(spec, data={"weather": weather}))
- return MosaicWidget, dir_path, f, mo, os, pd, spec, w, weather, yaml
+ return (w,)
@app.cell
-def __(w):
+def _(w):
w
return
+def _(w):
+ w.value
+ return
+
+
if __name__ == "__main__":
app.run()
diff --git a/marimo/_smoke_tests/anywidget_smoke_tests/multiple_models.py b/marimo/_smoke_tests/anywidget_smoke_tests/multiple_models.py
new file mode 100644
index 0000000000..d8a2e27c33
--- /dev/null
+++ b/marimo/_smoke_tests/anywidget_smoke_tests/multiple_models.py
@@ -0,0 +1,68 @@
+import marimo
+
+__generated_with = "0.13.10"
+app = marimo.App(width="medium")
+
+
+def _():
+ import marimo as mo
+ import anywidget
+
+ import ipywidgets
+ import traitlets
+
+
+ class ModelOnlyWidget(ipywidgets.Widget):
+ value = traitlets.Int(1).tag(sync=True)
+
+
+ class Widget(anywidget.AnyWidget):
+ _esm = """
+ async function render({ model, el }) {
+
+ let fooModel = await model.widget_manager.get_model(
+ model.get("foo").slice("IPY_MODEL_".length)
+ )
+ console.log(fooModel)
+
+ let button = document.createElement("button");
+ el.appendChild(button);
+
+ button.innerText = "count is " + fooModel.get("value");
+
+ button.onclick = async () => {
+ fooModel.set("value", fooModel.get("value") + 1);
+ fooModel.save_changes();
+ }
+
+ fooModel.on("change:value", () => {
+ button.innerText = "count is " + fooModel.get("value");
+ });
+
+ }
+ export default { render }
+ """
+ foo = traitlets.Instance(ModelOnlyWidget).tag(
+ sync=True, **ipywidgets.widget_serialization
+ )
+
+
+ m = ModelOnlyWidget()
+ mo.ui.anywidget(Widget(foo=m))
+ return (m,)
+
+
+def _(m):
+ m.value
+ return
+
+
+def _():
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_smoke_tests/third_party/lonboard_example.py b/marimo/_smoke_tests/third_party/lonboard_example.py
new file mode 100644
index 0000000000..315c86cd56
--- /dev/null
+++ b/marimo/_smoke_tests/third_party/lonboard_example.py
@@ -0,0 +1,58 @@
+# /// script
+# requires-python = ">=3.11"
+# dependencies = [
+# "duckdb==1.2.0",
+# "lonboard==0.10.4",
+# "marimo",
+# "polars==1.23.0",
+# "pyarrow==19.0.1",
+# "shapely==2.0.7",
+# "sqlglot==26.6.0",
+# ]
+# ///
+
+import marimo
+
+__generated_with = "0.13.10"
+app = marimo.App(width="full")
+
+
+def _():
+ import duckdb
+ from lonboard import viz
+
+ # Initialize DuckDB connection
+ con = duckdb.connect()
+
+ # Load spatial extension
+ duckdb.install_extension("spatial", connection=con)
+ duckdb.load_extension("spatial", connection=con)
+ return con, viz
+
+
+def _(con):
+ sql = """
+ SELECT 'Polygon 1' AS polygon_name, 'POLYGON((-48.5 -25.4, -48.4 -25.4, -48.4 -25.3, -48.5 -25.3, -48.5 -25.4))'::geometry AS geometry
+ UNION ALL
+ SELECT 'Polygon 2' AS polygon_name, 'POLYGON((-48.3 -25.4, -48.2 -25.4, -48.2 -25.3, -48.3 -25.3, -48.3 -25.4))'::geometry AS geometry
+ UNION ALL
+ SELECT 'Polygon 3' AS polygon_name, 'POLYGON((-48.1 -25.4, -48.0 -25.4, -48.0 -25.3, -48.1 -25.3, -48.1 -25.4))'::geometry AS geometry
+ UNION ALL
+ SELECT 'Polygon 4' AS polygon_name, 'POLYGON((-48.55 -25.35, -48.45 -25.35, -48.45 -25.25, -48.55 -25.25, -48.55 -25.35))'::geometry AS geometry
+ UNION ALL
+ SELECT 'Polygon 5' AS polygon_name, 'POLYGON((-48.35 -25.35, -48.25 -25.35, -48.25 -25.25, -48.35 -25.25, -48.35 -25.35))'::geometry AS geometry
+ """
+ polygons = con.sql(sql)
+ return (polygons,)
+
+
+def _(con, polygons, viz):
+ viz(polygons, con=con)
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_types/ids.py b/marimo/_types/ids.py
index 01227b3beb..983094d98a 100644
--- a/marimo/_types/ids.py
+++ b/marimo/_types/ids.py
@@ -14,3 +14,6 @@ ConsumerId = NewType("ConsumerId", str)
VariableName = NewType("VariableName", str)
RequestId = NewType("RequestId", str)
+
+# AnyWidget model id
+WidgetModelId = NewType("WidgetModelId", str)
diff --git a/openapi/api.yaml b/openapi/api.yaml
index 0552ab0b07..c05e6bc1ca 100644
--- a/openapi/api.yaml
+++ b/openapi/api.yaml
@@ -2251,14 +2251,17 @@ components:
message:
additionalProperties: {}
type: object
+ model_id:
+ nullable: true
+ type: string
name:
enum:
- send-ui-element-message
type: string
ui_element:
+ nullable: true
type: string
required:
- - ui_element
- message
- name
type: object
@@ -2272,6 +2275,36 @@ components:
required:
- configs
type: object
+ SetModelMessageRequest:
+ properties:
+ buffers:
+ items:
+ type: string
+ nullable: true
+ type: array
+ message:
+ properties:
+ bufferPaths:
+ items:
+ items:
+ oneOf:
+ - type: string
+ - type: integer
+ type: array
+ type: array
+ state:
+ additionalProperties: {}
+ type: object
+ required:
+ - state
+ - bufferPaths
+ type: object
+ modelId:
+ type: string
+ required:
+ - modelId
+ - message
+ type: object
SetUIElementValueRequest:
properties:
objectIds:
@@ -2528,7 +2561,7 @@ components:
type: object
info:
title: marimo API
- version: 0.13.7
+ version: 0.13.10
openapi: 3.1.0
paths:
/@file/{filename_and_length}:
@@ -3151,6 +3184,20 @@ paths:
schema:
$ref: '#/components/schemas/SuccessResponse'
description: Set the configuration of a cell
+ /api/kernel/set_model_value:
+ post:
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/SetModelMessageRequest'
+ responses:
+ 200:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/SuccessResponse'
+ description: Set model value
/api/kernel/set_ui_element_value:
post:
requestBody:
diff --git a/openapi/src/api.ts b/openapi/src/api.ts
index d1597ee4f4..e98bad9a2e 100644
--- a/openapi/src/api.ts
+++ b/openapi/src/api.ts
@@ -1785,6 +1785,45 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/api/kernel/set_model_value": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ post: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody?: {
+ content: {
+ "application/json": components["schemas"]["SetModelMessageRequest"];
+ };
+ };
+ responses: {
+ /** @description Set model value */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["SuccessResponse"];
+ };
+ };
+ };
+ };
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/api/kernel/set_ui_element_value": {
parameters: {
query?: never;
@@ -3360,9 +3399,10 @@ export interface components {
message: {
[key: string]: unknown;
};
+ model_id?: string | null;
/** @enum {string} */
name: "send-ui-element-message";
- ui_element: string;
+ ui_element?: string | null;
};
SetCellConfigRequest: {
configs: {
@@ -3371,6 +3411,16 @@ export interface components {
};
};
};
+ SetModelMessageRequest: {
+ buffers?: string[] | null;
+ message: {
+ bufferPaths: (string | number)[][];
+ state: {
+ [key: string]: unknown;
+ };
+ };
+ modelId: string;
+ };
SetUIElementValueRequest: {
objectIds: string[];
request?: components["schemas"]["HTTPRequest"];
diff --git a/tests/_plugins/ui/_impl/anywidget/test_anywidget_utils.py b/tests/_plugins/ui/_impl/anywidget/test_anywidget_utils.py
new file mode 100644
index 0000000000..598b3885a2
--- /dev/null
+++ b/tests/_plugins/ui/_impl/anywidget/test_anywidget_utils.py
@@ -0,0 +1,65 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import pytest
+
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._plugins.ui._impl.anywidget.utils import (
+ extract_buffer_paths,
+ insert_buffer_paths,
+ is_model_message,
+)
+
+HAS_DEPS = DependencyManager.ipywidgets.has()
+
+
[email protected](not HAS_DEPS, reason="ipywidgets is not installed")
+def test_extract_buffer_paths():
+ # Test with a simple message containing buffers
+ message = {
+ "method": "update",
+ "state": {"value": b"test", "other": "not a buffer"},
+ "buffer_paths": [["state", "value"]],
+ }
+
+ state, buffer_paths, buffers = extract_buffer_paths(message["state"])
+
+ assert isinstance(state, dict)
+ assert isinstance(buffer_paths, list)
+ assert isinstance(buffers, list)
+ assert len(buffers) == 1
+ assert buffers[0] == b"test"
+ assert state["other"] == "not a buffer"
+ assert "value" not in state
+
+
[email protected](not HAS_DEPS, reason="ipywidgets is not installed")
+def test_insert_buffer_paths():
+ # Test inserting buffers back into state
+ state = {"method": "update", "state": {"other": "not a buffer"}}
+ buffer_paths = [["state", "value"]]
+ buffers = [b"test"]
+
+ result = insert_buffer_paths(state, buffer_paths, buffers)
+
+ assert isinstance(result, dict)
+ assert result["state"]["value"] == b"test"
+ assert result["state"]["other"] == "not a buffer"
+
+
[email protected](not HAS_DEPS, reason="ipywidgets is not installed")
+def test_is_model_message():
+ # Test valid model message
+ valid_message = {
+ "method": "update",
+ "state": {"value": "test"},
+ "buffer_paths": [],
+ }
+ assert is_model_message(valid_message) is True
+
+ # Test invalid messages
+ assert is_model_message({}) is False
+ assert is_model_message({"method": "update"}) is False
+ assert is_model_message({"state": {}, "buffer_paths": []}) is False
+ assert is_model_message(None) is False
+ assert is_model_message("not a dict") is False
diff --git a/tests/_plugins/ui/_impl/test_anywidget.py b/tests/_plugins/ui/_impl/test_anywidget.py
index 446f977864..bc4502658c 100644
--- a/tests/_plugins/ui/_impl/test_anywidget.py
+++ b/tests/_plugins/ui/_impl/test_anywidget.py
@@ -11,7 +11,9 @@ from marimo._runtime.requests import SetUIElementValueRequest
from marimo._runtime.runtime import Kernel
from tests.conftest import ExecReqProvider
-HAS_DEPS = DependencyManager.anywidget.has()
+HAS_DEPS = (
+ DependencyManager.anywidget.has() and DependencyManager.traitlets.has()
+)
if HAS_DEPS:
import anywidget as _anywidget
diff --git a/tests/_plugins/ui/_impl/test_comm.py b/tests/_plugins/ui/_impl/test_comm.py
new file mode 100644
index 0000000000..3bbb9648a9
--- /dev/null
+++ b/tests/_plugins/ui/_impl/test_comm.py
@@ -0,0 +1,175 @@
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from marimo._plugins.ui._impl.comm import (
+ COMM_CLOSE_NAME,
+ COMM_MESSAGE_NAME,
+ COMM_OPEN_NAME,
+ MarimoComm,
+ MarimoCommManager,
+ MessageBufferData,
+)
+from marimo._types.ids import WidgetModelId
+
+
+def comm_manager():
+ return MarimoCommManager()
+
+
+def comm(comm_manager: MarimoCommManager) -> MarimoComm:
+ comm_id = WidgetModelId("test-comm")
+ return MarimoComm(
+ comm_id=comm_id,
+ comm_manager=comm_manager,
+ target_name="test_target",
+ )
+
+
+def test_comm_manager_register_unregister(
+ comm_manager: MarimoCommManager, comm: MarimoComm
+):
+ # Test registration
+ comm_id = comm_manager.register_comm(comm)
+ assert comm_id in comm_manager.comms
+ assert comm_manager.comms[comm_id] == comm
+
+ # Test unregistration
+ unregistered_comm = comm_manager.unregister_comm(comm)
+ assert unregistered_comm == comm
+ assert comm_id not in comm_manager.comms
+
+
+def test_comm_manager_receive_unknown_message(
+ comm_manager: MarimoCommManager,
+):
+ with patch("marimo._plugins.ui._impl.comm.LOGGER") as mock_logger:
+ comm_manager.receive_comm_message(
+ WidgetModelId("unknown"),
+ MagicMock(),
+ None,
+ )
+ mock_logger.warning.assert_called_once()
+
+
+def test_comm_initialization(comm: MarimoComm):
+ assert comm.comm_id == WidgetModelId("test-comm")
+ assert comm.target_name == "test_target"
+ assert comm.kernel == "marimo"
+ assert not comm._closed
+ assert comm._msg_callback is None
+ assert comm._close_callback is None
+
+
+def test_comm_open(comm: MarimoComm):
+ with patch.object(comm, "_publish_msg") as mock_publish:
+ comm.open(data={"test": "data"})
+ mock_publish.assert_called_once_with(
+ COMM_OPEN_NAME,
+ data={"test": "data"},
+ metadata=None,
+ buffers=None,
+ target_name="test_target",
+ target_module=None,
+ )
+ assert not comm._closed
+
+
+def test_comm_send(comm: MarimoComm):
+ with patch.object(comm, "_publish_msg") as mock_publish:
+ comm.send(data={"test": "data"})
+ mock_publish.assert_called_once_with(
+ COMM_MESSAGE_NAME,
+ data={"test": "data"},
+ metadata=None,
+ buffers=None,
+ )
+
+
+def test_comm_close(comm: MarimoComm):
+ with patch.object(comm, "_publish_msg") as mock_publish:
+ comm.close(data={"test": "data"})
+ mock_publish.assert_called_once_with(
+ COMM_CLOSE_NAME,
+ data={"test": "data"},
+ metadata=None,
+ buffers=None,
+ )
+ assert comm._closed
+
+
+def test_comm_close_already_closed(comm: MarimoComm):
+ comm._closed = True
+ with patch.object(comm, "_publish_msg") as mock_publish:
+ comm.close()
+ mock_publish.assert_not_called()
+
+
+def test_comm_on_msg(comm: MarimoComm):
+ callback = MagicMock()
+ comm.on_msg(callback)
+ assert comm._msg_callback == callback
+
+
+def test_comm_on_close(comm: MarimoComm):
+ callback = MagicMock()
+ comm.on_close(callback)
+ assert comm._close_callback == callback
+
+
+def test_comm_handle_msg(comm: MarimoComm):
+ callback = MagicMock()
+ comm.on_msg(callback)
+ msg = {"test": "message"}
+ comm.handle_msg(msg)
+ callback.assert_called_once_with(msg)
+
+
+def test_comm_handle_msg_no_callback(comm: MarimoComm):
+ with patch("marimo._plugins.ui._impl.comm.LOGGER") as mock_logger:
+ msg = {"test": "message"}
+ comm.handle_msg(msg)
+ mock_logger.warning.assert_called_once()
+
+
+def test_comm_handle_close(comm: MarimoComm):
+ callback = MagicMock()
+ comm.on_close(callback)
+ msg = {"test": "message"}
+ comm.handle_close(msg)
+ callback.assert_called_once_with(msg)
+
+
+def test_comm_handle_close_no_callback(comm: MarimoComm):
+ with patch("marimo._plugins.ui._impl.comm.LOGGER") as mock_logger:
+ msg = {"test": "message"}
+ comm.handle_close(msg)
+ mock_logger.warning.assert_called_once()
+
+
+def test_comm_flush(comm: MarimoComm):
+ test_data = {"test": "data"}
+ test_metadata = {"meta": "data"}
+ test_buffers = [b"test_buffer"]
+
+ comm._publish_message_buffer.append(
+ MessageBufferData(
+ data=test_data,
+ metadata=test_metadata,
+ buffers=test_buffers,
+ model_id=comm.comm_id,
+ )
+ )
+
+ with patch("marimo._messaging.ops.SendUIElementMessage") as mock_send:
+ comm.flush()
+ mock_send.assert_called_once()
+ call_args = mock_send.call_args[1]
+ assert call_args["model_id"] == comm.comm_id
+ assert call_args["message"] == test_data
+ assert len(call_args["buffers"]) == 1
+ assert (
+ call_args["buffers"][0] == "dGVzdF9idWZmZXI="
+ ) # base64 of b"test_buffer"
diff --git a/tests/_server/api/endpoints/test_execution.py b/tests/_server/api/endpoints/test_execution.py
index 3ccc788ccf..ce1faff6f6 100644
--- a/tests/_server/api/endpoints/test_execution.py
+++ b/tests/_server/api/endpoints/test_execution.py
@@ -88,6 +88,25 @@ class TestExecutionRoutes_EditMode:
assert response.headers["content-type"] == "application/json"
assert "success" in response.json()
+ @staticmethod
+ @with_session(SESSION_ID)
+ def test_set_model_value(client: TestClient) -> None:
+ response = client.post(
+ "/api/kernel/set_model_value",
+ headers=HEADERS,
+ json={
+ "model_id": "model-1",
+ "message": {
+ "state": {"key": "value"},
+ "buffer_paths": [["a"], ["b"]],
+ },
+ "buffers": ["buffer1", "buffer2"],
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert response.headers["content-type"] == "application/json"
+ assert "success" in response.json()
+
@staticmethod
@with_session(SESSION_ID)
def test_interrupt(client: TestClient) -> None:
@@ -276,6 +295,25 @@ class TestExecutionRoutes_RunMode:
assert response.headers["content-type"] == "application/json"
assert "success" in response.json()
+ @staticmethod
+ @with_read_session(SESSION_ID)
+ def test_set_model_value(client: TestClient) -> None:
+ response = client.post(
+ "/api/kernel/set_model_value",
+ headers=HEADERS,
+ json={
+ "model_id": "model-1",
+ "message": {
+ "state": {"key": "value"},
+ "buffer_paths": [["a"], ["b"]],
+ },
+ "buffers": ["buffer1", "buffer2"],
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert response.headers["content-type"] == "application/json"
+ assert "success" in response.json()
+
@staticmethod
@with_read_session(SESSION_ID)
def test_interrupt(client: TestClient) -> None:
diff --git a/tests/_server/session/test_session_view.py b/tests/_server/session/test_session_view.py
index 1a2aba63a2..b26d1ba6f8 100644
--- a/tests/_server/session/test_session_view.py
+++ b/tests/_server/session/test_session_view.py
@@ -12,6 +12,7 @@ from marimo._messaging.ops import (
Datasets,
DataSourceConnection,
DataSourceConnections,
+ SendUIElementMessage,
UpdateCellCodes,
UpdateCellIdsRequest,
VariableDeclaration,
@@ -28,7 +29,7 @@ from marimo._runtime.requests import (
)
from marimo._server.session.session_view import SessionView
from marimo._sql.engines.duckdb import INTERNAL_DUCKDB_ENGINE
-from marimo._types.ids import CellId_t
+from marimo._types.ids import CellId_t, WidgetModelId
from marimo._utils.parse_dataclass import parse_raw
cell_id = CellId_t("cell_1")
@@ -176,6 +177,48 @@ def test_ui_values() -> None:
assert "test_ui3" in session_view.ui_values
+def test_model_message_values() -> None:
+ session_view = SessionView()
+ model_id = WidgetModelId("test_model")
+ model_id2 = WidgetModelId("test_model2")
+
+ session_view.add_operation(
+ SendUIElementMessage(
+ model_id=model_id,
+ message={"key": "value"},
+ ui_element=None,
+ )
+ )
+ assert model_id in session_view.model_messages
+ assert session_view.model_messages[model_id][0].message == {"key": "value"}
+
+ # Can add to existing model
+ session_view.add_operation(
+ SendUIElementMessage(
+ model_id=model_id,
+ message={"key": "new_value"},
+ ui_element=None,
+ )
+ )
+ assert len(session_view.model_messages[model_id]) == 2
+ assert session_view.model_messages[model_id][1].message == {
+ "key": "new_value"
+ }
+
+ # Can add multiple models
+ session_view.add_operation(
+ SendUIElementMessage(
+ model_id=model_id2,
+ message={"key2": "value2"},
+ ui_element=None,
+ )
+ )
+ assert model_id2 in session_view.model_messages
+ assert session_view.model_messages[model_id2][0].message == {
+ "key2": "value2"
+ }
+
+
def test_last_run_code() -> None:
session_view = SessionView()
session_view.add_control_request(