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: anywidget refresh value (#9454)

Shamikf7b1571e0883
diff --git a/.gitignore b/.gitignore
index a117d6d11f..d2f74087b3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -132,3 +132,6 @@ pixi.lock
# mkdocs
site
+
+.agents/
+*skills*
diff --git a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
index 2a3e67b9c1..0e9080b531 100644
--- a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
+++ b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
@@ -11,7 +11,7 @@ import type { IPluginProps } from "@/plugins/types";
import { prettyError } from "@/utils/errors";
import { Logger } from "@/utils/Logger";
import { ErrorBanner } from "../common/error-banner";
-import { MODEL_MANAGER, type Model } from "./model";
+import { getMarimoInternal, MODEL_MANAGER, type Model } from "./model";
import type { ModelState, WidgetModelId } from "./types";
import { BINDING_MANAGER, WIDGET_DEF_REGISTRY } from "./widget-binding";
@@ -178,6 +178,9 @@ async function runAnyWidgetModule<T extends AnyWidgetState>(
const binding = BINDING_MANAGER.getOrCreate(modelId);
const render = await binding.bind(widgetDef, model);
await render(el, signal);
+ // Replay current model values so render listeners observe hydrated state
+ // even if backend updates arrived before listeners were attached.
+ getMarimoInternal(model).reemitState();
} catch (error) {
Logger.error("Error rendering anywidget", error);
el.classList.add("text-error");
diff --git a/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.tsx b/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.tsx
index 7ff5d06a23..a6e080cc56 100644
--- a/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.tsx
+++ b/frontend/src/plugins/impl/anywidget/__tests__/AnyWidgetPlugin.test.tsx
@@ -115,4 +115,38 @@ describe("LoadedSlot", () => {
expect(newMockWidget.render).toHaveBeenCalled();
});
});
+
+ it("should hydrate view state even when listener attaches late", async () => {
+ mockModel = new Model(
+ { count: 8 },
+ {
+ sendUpdate: vi.fn().mockResolvedValue(undefined),
+ sendCustomMessage: vi.fn().mockResolvedValue(undefined),
+ },
+ );
+ MODEL_MANAGER.set(modelId, mockModel);
+
+ const lateListenerWidget = {
+ initialize: vi.fn(),
+ render: vi.fn(({ model, el }) => {
+ // Simulate a widget view that starts with a local default and
+ // relies on change events for hydration.
+ el.textContent = "count is 5";
+ const onCount = () => {
+ el.textContent = `count is ${model.get("count")}`;
+ };
+ model.on("change:count", onCount);
+ return () => model.off("change:count", onCount);
+ }),
+ };
+
+ const { container } = render(
+ <LoadedSlot {...mockProps} widget={lateListenerWidget} />,
+ );
+
+ await waitFor(() => {
+ expect(lateListenerWidget.render).toHaveBeenCalled();
+ expect(container.textContent).toContain("count is 8");
+ });
+ });
});
diff --git a/frontend/src/plugins/impl/anywidget/__tests__/model.test.ts b/frontend/src/plugins/impl/anywidget/__tests__/model.test.ts
index 850369a644..99c86f6930 100644
--- a/frontend/src/plugins/impl/anywidget/__tests__/model.test.ts
+++ b/frontend/src/plugins/impl/anywidget/__tests__/model.test.ts
@@ -272,6 +272,25 @@ describe("Model", () => {
});
});
+ describe("reemitState", () => {
+ it("should emit change events for current values without state changes", async () => {
+ const onFoo = vi.fn();
+ const onBar = vi.fn();
+ const onAny = vi.fn();
+
+ model.on("change:foo", onFoo);
+ model.on("change:bar", onBar);
+ model.on("change", onAny);
+
+ getMarimoInternal(model).reemitState();
+ await TestUtils.nextTick();
+
+ expect(onFoo).toHaveBeenCalledWith("test");
+ expect(onBar).toHaveBeenCalledWith(123);
+ expect(onAny).toHaveBeenCalledTimes(1);
+ });
+ });
+
describe("emitCustomMessage", () => {
it("should handle custom messages", () => {
const callback = vi.fn();
diff --git a/frontend/src/plugins/impl/anywidget/model.ts b/frontend/src/plugins/impl/anywidget/model.ts
index 8471411a52..a3150d8b35 100644
--- a/frontend/src/plugins/impl/anywidget/model.ts
+++ b/frontend/src/plugins/impl/anywidget/model.ts
@@ -112,6 +112,10 @@ interface MarimoInternalApi<T extends ModelState> {
* Update model state and emit change events for any differences.
*/
updateAndEmitDiffs: (value: T) => void;
+ /**
+ * Re-emit current state as change events.
+ */
+ reemitState: () => void;
/**
* Emit a custom message to listeners.
*/
@@ -160,6 +164,7 @@ export class Model<T extends ModelState> implements AnyModel<T> {
*/
[marimoSymbol]: MarimoInternalApi<T> = {
updateAndEmitDiffs: (value: T) => this.#updateAndEmitDiffs(value),
+ reemitState: () => this.#reemitState(),
emitCustomMessage: (
message: Extract<AnyWidgetMessage, { method: "custom" }>,
buffers?: readonly DataView[],
@@ -269,6 +274,16 @@ export class Model<T extends ModelState> implements AnyModel<T> {
});
}
+ #reemitState() {
+ for (const [key, value] of Object.entries(this.#data) as [
+ keyof T & string,
+ T[keyof T],
+ ][]) {
+ this.#emit(`change:${key}`, value);
+ }
+ this.#emitAnyChange();
+ }
+
/**
* When receiving a message from the backend.
* We want to notify all listeners with `msg:custom`
diff --git a/marimo/_plugins/ui/_impl/comm.py b/marimo/_plugins/ui/_impl/comm.py
index a3d3406aab..8168d33767 100644
--- a/marimo/_plugins/ui/_impl/comm.py
+++ b/marimo/_plugins/ui/_impl/comm.py
@@ -95,7 +95,9 @@ def _create_model_message(
) -> ModelMessage | None:
"""Create the appropriate ModelMessage based on the method field.
- Returns None for methods that should be skipped (e.g., echo_update).
+ Returns None for unknown methods that should be skipped.
+ `echo_update` is converted to `ModelUpdate` to preserve
+ frontend-driven trait changes for reconnect replay.
"""
bbuffers = [_ensure_bytes(b) for b in buffers]
method = data.get("method", "update")
@@ -120,8 +122,14 @@ def _create_model_message(
buffers=bbuffers,
)
elif method == "echo_update":
- # echo_update is for multi-client sync acknowledgment, skip it
- return None
+ # Preserve frontend-driven trait changes for reconnect replay.
+ # anywidget/ipywidgets can emit echo_update as the synchronisation
+ # acknowledgement path; dropping it causes stale replay state.
+ return ModelUpdate(
+ state=state,
+ buffer_paths=buffer_paths,
+ buffers=bbuffers,
+ )
else:
LOGGER.warning("Unknown method: %s, skipping", method)
return None
diff --git a/tests/_plugins/ui/_impl/test_comm.py b/tests/_plugins/ui/_impl/test_comm.py
index dd1124a124..479bb37e5f 100644
--- a/tests/_plugins/ui/_impl/test_comm.py
+++ b/tests/_plugins/ui/_impl/test_comm.py
@@ -159,6 +159,21 @@ def test_comm_broadcast(comm: MarimoComm):
assert notification.model_id == comm.comm_id
+def test_comm_broadcast_echo_update(comm: MarimoComm):
+ """echo_update should still contribute to replay state."""
+ with patch(
+ "marimo._plugins.ui._impl.comm.broadcast_notification"
+ ) as mock_broadcast:
+ comm._broadcast(
+ {"method": "echo_update", "state": {"key": "value"}},
+ [],
+ )
+ mock_broadcast.assert_called_once()
+ notification = mock_broadcast.call_args[0][0]
+ assert notification.model_id == comm.comm_id
+ assert notification.message.state == {"key": "value"}
+
+
def test_comm_manager_receive_update_message(
comm_manager: MarimoCommManager, comm: MarimoComm
):