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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: anywidget bytes when on save trait (#2557)
Myles Scolnick5483508d2c2e
diff --git a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsxindex 22aa476ba7..d3c3457d9b 100644--- a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx+++ b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx@@ -258,7 +258,8 @@ class Model<T extends Record<string, any>> implements AnyModel<T> {break;}} else {- Logger.error("Failed to parse message", message, response.error);+ Logger.error("Failed to parse message", response.error);+ Logger.error("Message", message);}}@@ -286,4 +287,9 @@ const WidgetMessageSchema = z.union([method: z.literal("custom"),content: z.any(),}),+ z.object({+ method: z.literal("echo_update"),+ buffer_paths: z.array(z.array(z.union([z.string(), z.number()]))),+ state: z.record(z.any()),+ }),]);diff --git a/marimo/_plugins/ui/_impl/from_anywidget.py b/marimo/_plugins/ui/_impl/from_anywidget.pyindex 7bfaf6b8f9..59685a8ef2 100644--- a/marimo/_plugins/ui/_impl/from_anywidget.py+++ b/marimo/_plugins/ui/_impl/from_anywidget.py@@ -122,16 +122,17 @@ class anywidget(UIElement[T, T]):# Handle circular dependenciespass- def on_change(change: T) -> None:- for key, value in change.items():- widget.set_trait(key, value)-js: str = widget._esm if hasattr(widget, "_esm") else "" # type: ignore [unused-ignore] # noqa: E501css: str = widget._css if hasattr(widget, "_css") else "" # type: ignore [unused-ignore] # noqa: E501import ipywidgets # type: ignore_remove_buffers = ipywidgets.widgets.widget._remove_buffers # type: ignore- _state, buffer_paths, _buffers = _remove_buffers(widget.get_state()) # type: ignore+ _state, buffer_paths, buffers = _remove_buffers(widget.get_state()) # type: ignore++ def on_change(change: T) -> None:+ _put_buffers = ipywidgets.widgets.widget._put_buffers # type: ignore+ _put_buffers(change, buffer_paths, buffers)+ widget.set_state(change)super().__init__(component_name="marimo-anywidget",diff --git a/marimo/_smoke_tests/issues/2506_anywidget_buffer_paths.py b/marimo/_smoke_tests/issues/2506_anywidget_buffer_paths.pyindex 4eb8ded774..88e661be5c 100644--- a/marimo/_smoke_tests/issues/2506_anywidget_buffer_paths.py+++ b/marimo/_smoke_tests/issues/2506_anywidget_buffer_paths.py@@ -1,13 +1,13 @@import marimo-__generated_with = "0.9.1"+__generated_with = "0.9.4"app = marimo.App(width="medium")@app.celldef __():# binary data is a png image of a small purple square- CONTENT = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x14\x00\x00\x00\x14\x08\x02\x00\x00\x00\x02\xeb\x8aZ\x00\x00\x00\tpHYs\x00\x00.#\x00\x00.#\x01x\xa5?v\x00\x00\x00\x1dIDAT8\xcbc\xac\x11\xa9g \x1701P\x00F5\x8fj\x1e\xd5<\xaa\x99r\xcd\x00m\xba\x017\xd3\x00\xdf\xcb\x00\x00\x00\x00IEND\xaeB`\x82'+ CONTENT = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x14\x00\x00\x00\x14\x08\x02\x00\x00\x00\x02\xeb\x8aZ\x00\x00\x00\tpHYs\x00\x00.#\x00\x00.#\x01x\xa5?v\x00\x00\x00\x1dIDAT8\xcbc\xac\x11\xa9g \x1701P\x00F5\x8fj\x1e\xd5<\xaa\x99r\xcd\x00m\xba\x017\xd3\x00\xdf\xcb\x00\x00\x00\x00IEND\xaeB`\x82"return (CONTENT,)@@ -16,6 +16,7 @@ def __(CONTENT):import anywidgetimport traitlets+class BytesWidget(anywidget.AnyWidget):_esm = """function render({ model, el }) {@@ -32,6 +33,7 @@ def __(CONTENT):"""value = traitlets.Bytes().tag(sync=True)+# binary data is a png image of a small purple squareBytesWidget(value=CONTENT)return BytesWidget, anywidget, traitlets@@ -51,6 +53,33 @@ def __(CONTENT, mo):return+def __(CONTENT, anywidget, traitlets):+ import numpy as np+ from pathlib import Path+++ class BytesWritesWidget(anywidget.AnyWidget):+ _esm = """+ function render({ model, el }) {+ model.set("other_value", 42)+ model.save_changes()+ const isDataView = document.createElement("div");+ const value = model.get("value")+ isDataView.innerText = `Is DataView: ${value instanceof DataView}`;+ el.appendChild(isDataView);+ }+ export default { render };+ """+ value = traitlets.Bytes().tag(sync=True)+ other_value = traitlets.Integer(0).tag(sync=True)+++ # raises a TraitError+ BytesWritesWidget(value=CONTENT)+ return BytesWritesWidget, Path, np++@app.celldef __():import marimo as modiff --git a/tests/_plugins/ui/_impl/test_anywidget.py b/tests/_plugins/ui/_impl/test_anywidget.pyindex 31d5cf685f..03f919a95a 100644--- a/tests/_plugins/ui/_impl/test_anywidget.py+++ b/tests/_plugins/ui/_impl/test_anywidget.py@@ -198,3 +198,113 @@ x = as_marimo_element.count"css": "","js-url": "",}++ @staticmethod+ async def test_custom_methods_and_attributes() -> None:+ class CustomWidget(_anywidget.AnyWidget):+ _esm = ""+ custom_attr = traitlets.Int(42).tag(sync=True)++ def custom_method(self):+ return self.custom_attr * 2++ wrapped = anywidget(CustomWidget())+ assert wrapped.custom_attr == 42+ assert wrapped.custom_method() == 84++ wrapped.custom_attr = 10+ assert wrapped.custom_attr == 10+ assert wrapped.custom_method() == 20++ @staticmethod+ async def test_non_serializable_traits() -> None:+ class NonSerializableWidget(_anywidget.AnyWidget):+ _esm = ""+ serializable = traitlets.Int(1).tag(sync=True)+ non_serializable = traitlets.Instance(object)++ wrapped = anywidget(NonSerializableWidget())+ assert "serializable" in wrapped._initial_value+ assert wrapped._initial_value["non_serializable"] is None++ @staticmethod+ async def test_frontend_changes(+ k: Kernel, exec_req: ExecReqProvider+ ) -> None:+ await k.run(+ [+ exec_req.get("""+ import marimo as mo+ import traitlets+ import anywidget as _anywidget++ class TestWidget(_anywidget.AnyWidget):+ _esm = ""+ value = traitlets.Int(0).tag(sync=True)++ w = mo.ui.anywidget(TestWidget())+ """)+ ]+ )++ ui_element = k.globals["w"]+ assert ui_element.value == {"value": 0}++ # Simulate a change from the frontend+ await k.set_ui_element_value(+ SetUIElementValueRequest.from_ids_and_values(+ [(ui_element._id, {"value": 42})]+ )+ )++ assert ui_element.value == {"value": 42}+ assert ui_element.widget.value == 42++ @staticmethod+ async def test_buffers() -> None:+ class BufferWidget(_anywidget.AnyWidget):+ _esm = ""+ array = traitlets.Bytes().tag(sync=True)++ data = bytes([1, 2, 3, 4])+ wrapped = anywidget(BufferWidget(array=data))++ assert wrapped._initial_value == {"array": data}+ assert wrapped._component_args["buffer-paths"] == [["array"]]++ # Test updating the buffer+ new_data = bytes([5, 6, 7, 8])+ wrapped.array = new_data+ assert wrapped.value["array"] == b"\x01\x02\x03\x04"++ @staticmethod+ async def test_error_handling() -> None:+ class ErrorWidget(_anywidget.AnyWidget):+ _esm = ""++ @traitlets.validate("value")+ def _validate_value(self, proposal):+ if proposal["value"] < 0:+ raise ValueError("Value must be non-negative")+ return proposal["value"]++ value = traitlets.Int(0).tag(sync=True)++ wrapped = anywidget(ErrorWidget())++ # Test invalid update+ wrapped.value = 5+ assert wrapped.value == {"value": 0}++ # Test invalid update+ with pytest.raises(ValueError):+ wrapped.value = -1++ @staticmethod+ async def test_css_handling() -> None:+ class CSSWidget(_anywidget.AnyWidget):+ _esm = ""+ _css = "button { color: red; }"++ wrapped = anywidget(CSSWidget())+ assert wrapped._component_args["css"] == "button { color: red; }"