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.

Remove dual JSON encoding in pyodide message callback (#6350)

Trevor Manz82bf19be6d99
diff --git a/marimo/_pyodide/bootstrap.py b/marimo/_pyodide/bootstrap.py
index 927d3964ed..2582308b6e 100644
--- a/marimo/_pyodide/bootstrap.py
+++ b/marimo/_pyodide/bootstrap.py
@@ -5,10 +5,7 @@ import json
from typing import TYPE_CHECKING, Callable
from marimo._config.config import merge_config
-from marimo._messaging.msgspec_encoder import (
- encode_json_bytes,
- encode_json_str,
-)
+from marimo._messaging.msgspec_encoder import encode_json_bytes
from marimo._messaging.ops import KernelCapabilities, KernelReady
from marimo._runtime.requests import (
AppMetadata,
@@ -81,7 +78,9 @@ def create_session(
"""
def write_kernel_message(op: KernelMessage) -> None:
- message_callback(encode_json_str({"op": op[0], "data": op[1]}))
+ op_name, data_bytes = op
+ text = f'{{"op": "{op_name}", "data": {data_bytes.decode("utf-8")}}}'
+ message_callback(text)
# Lazy import to decrease startup time
from marimo._config.config import merge_default_config
diff --git a/tests/_pyodide/test_bootstrap.py b/tests/_pyodide/test_bootstrap.py
index acb38556b6..6230974007 100644
--- a/tests/_pyodide/test_bootstrap.py
+++ b/tests/_pyodide/test_bootstrap.py
@@ -1,6 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import json
from typing import TYPE_CHECKING, Any, Callable
import pytest
@@ -176,3 +177,22 @@ def test_save_file(
# Verify the file was saved correctly
saved_content = mock_app_file.read_text()
assert "print('hello')" in saved_content
+
+
+async def test_message_callback_format(
+ mock_app_file: Path,
+) -> None:
+ """Test that message_callback receives properly formatted JSON."""
+ received_messages: list[str] = []
+
+ session, _ = create_session(
+ filename=str(mock_app_file),
+ query_params={},
+ message_callback=lambda text: received_messages.append(text),
+ user_config=DEFAULT_CONFIG,
+ )
+
+ assert len(received_messages) >= 1
+ parsed = json.loads(received_messages[0])
+ assert parsed["op"] == "kernel-ready"
+ assert isinstance(parsed["data"], dict)