The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): surface JSON-RPC serialization failures
fangliquanflq87c5658cc874
diff --git a/tests/tui_gateway/test_profiles_ui_meta_cas.py b/tests/tui_gateway/test_profiles_ui_meta_cas.pyindex f7de9e15411..9e4736993fe 100644--- a/tests/tui_gateway/test_profiles_ui_meta_cas.py+++ b/tests/tui_gateway/test_profiles_ui_meta_cas.py@@ -8,6 +8,7 @@ stale writer retry instead of silently replacing somebody else's state.from __future__ import annotations+import jsonfrom concurrent.futures import ThreadPoolExecutorimport pytest@@ -81,6 +82,20 @@ def test_ui_meta_revision_survives_key_deletion(home):assert stale_recreate["ui_meta_conflicts"]["shared-room"]["actual"] == 2+def test_profiles_list_normalizes_yaml_timestamps_in_ui_meta(home):+ """#92506: an unquoted ISO timestamp under ui_meta is parsed by YAML as datetime; the+ profiles.list row must still be JSON-serializable (the value becomes its ISO string)."""+ (home / "profile.yaml").write_text(+ "ui_meta:\n hermes-bots:\n created: 2026-08-22T00:00:00Z\n",+ encoding="utf-8",+ )++ row = _default_profile()++ assert row["ui_meta"]["hermes-bots"]["created"] == "2026-08-22T00:00:00+00:00"+ json.dumps(row)++def test_two_concurrent_writers_cannot_both_replace_the_same_revision(home):def write(label):return _configure(diff --git a/tests/tui_gateway/test_tui_gateway_ws.py b/tests/tui_gateway/test_tui_gateway_ws.pyindex 7dbebed65c1..e6be864696c 100644--- a/tests/tui_gateway/test_tui_gateway_ws.py+++ b/tests/tui_gateway/test_tui_gateway_ws.py@@ -1,5 +1,6 @@import asyncioimport concurrent.futures+import datetimeimport jsonimport threadingimport time@@ -234,6 +235,42 @@ def test_ws_transport_serializes_concurrent_sends():loop.close()+def test_ws_transport_replies_with_error_for_unserializable_response(caplog):+ """#92506: an unserializable payload (datetime from profile.yaml ui_meta) must surface as a+ JSON-RPC error frame with the original id plus a log line — on both the worker-thread+ ``write`` and the loop-side ``write_async`` twin — and leave the transport open, instead of+ killing the pool worker silently so the client waits forever."""+ sent = []++ class FakeWS:+ async def send_text(self, line):+ sent.append(json.loads(line))++ bad = {"jsonrpc": "2.0", "id": "profiles", "result": {"created": datetime.datetime(2026, 8, 22)}}++ loop = asyncio.new_event_loop()+ thread = threading.Thread(target=loop.run_forever, daemon=True)+ thread.start()+ try:+ transport = ws_mod.WSTransport(FakeWS(), loop, peer="serialization-test")+ assert transport.write(bad) is True+ assert transport.write({"jsonrpc": "2.0", "id": "next", "result": {}}) is True+ assert asyncio.run_coroutine_threadsafe(transport.write_async(bad), loop).result(5) is True+ assert transport.closed is False+ finally:+ loop.call_soon_threadsafe(loop.stop)+ thread.join(timeout=2)+ loop.close()++ assert [m.get("id") for m in sent] == ["profiles", "next", "profiles"]+ for frame in (sent[0], sent[2]):+ assert frame["error"]["code"] == -32603+ assert frame["error"]["message"].startswith("response serialization error")+ assert "datetime" in frame["error"]["message"]+ assert sent[1] == {"jsonrpc": "2.0", "id": "next", "result": {}}+ assert caplog.text.count("ws frame serialization failed") == 2++def test_ws_transport_preserves_cross_batch_order():async def scenario():entered = []diff --git a/tui_gateway/methods_profiles.py b/tui_gateway/methods_profiles.pyindex 2b326ba9138..dc76213d104 100644--- a/tui_gateway/methods_profiles.py+++ b/tui_gateway/methods_profiles.py@@ -91,6 +91,12 @@ def _read_profile_yaml(profile_dir) -> dict:return loaded if isinstance(loaded, dict) else {}+def _yaml_scalar_to_json(value):+ """``json.dumps`` default for YAML-only scalars (datetime/date → ISO 8601, else ``str``)."""+ isoformat = getattr(value, "isoformat", None)+ return isoformat() if callable(isoformat) else str(value)++def _clean_revisions(raw: dict) -> dict:"""Normalise a ``_ui_meta_revisions`` map: str keys, non-bool ints clamped at 0."""return {str(k): max(0, int(v)) for k, v in raw.items() if isinstance(v, int) and not isinstance(v, bool)}@@ -232,7 +238,9 @@ def _profile_ui_meta_fields(row: dict, profile_dir) -> None:# Key order is wire-visible: ui_meta_revisions precedes ui_meta.row["ui_meta_revisions"] = _try(lambda: _clean_revisions(revisions), {}) if isinstance(revisions, dict) else {}if isinstance(ui_meta, dict) and ui_meta:- row["ui_meta"] = ui_meta+ # YAML promotes unquoted timestamps to datetime/date; the handler's contract is JSON, so+ # coerce YAML-only scalars to their ISO string at the boundary (#92506).+ row["ui_meta"] = json.loads(json.dumps(ui_meta, default=_yaml_scalar_to_json))# Cheap existence flag so rosters skip a get_asset probe per paint.row["has_avatar"] = _try(lambda: any((profile_dir / "assets" / f"avatar.{e}").is_file() for e in _ASSET_EXTS), False)diff --git a/tui_gateway/ws.py b/tui_gateway/ws.pyindex 2f8d52c215a..40d946f1dc9 100644--- a/tui_gateway/ws.py+++ b/tui_gateway/ws.py@@ -106,10 +106,24 @@ class WSTransport:# Socket writes need an async boundary: several batches can queue on the loop during a stall.self._send_lock = asyncio.Lock()+ def _serialize_frame(self, obj: dict) -> str:+ """``json.dumps`` the frame; an unserializable payload becomes a JSON-RPC error frame+ carrying the original id. Without this the TypeError escaped from a pool worker (the+ executor swallows it), so the client waited forever with no log line (#92506)."""+ try:+ return json.dumps(obj, ensure_ascii=False)+ except (TypeError, ValueError) as exc:+ rid = obj.get("id") if isinstance(obj, dict) else None+ _log.error("ws frame serialization failed peer=%s id=%s error_type=%s error=%s",+ self._peer, rid, type(exc).__name__, exc)+ fallback = {"jsonrpc": "2.0", "id": rid,+ "error": {"code": -32603, "message": f"response serialization error: {exc}"}}+ return json.dumps(fallback, ensure_ascii=False)+def write(self, obj: dict) -> bool:if self._closed:return False- line = json.dumps(obj, ensure_ascii=False)+ line = self._serialize_frame(obj)try:on_loop = asyncio.get_running_loop() is self._loopexcept RuntimeError:@@ -177,7 +191,7 @@ class WSTransport:return Falsewith self._token_lock:batch, self._pending_tokens = self._pending_tokens, []- batch.append(json.dumps(obj, ensure_ascii=False))+ batch.append(self._serialize_frame(obj))await self._safe_send_many(batch)return not self._closed