Skip to content

The agent that grows with you

fix(web): offload dashboard media encoding

wangtao3505e4ce771b
diff --git a/hermes_cli/web_routers/files.py b/hermes_cli/web_routers/files.py
index 296b88578cf..46b45815986 100644
--- a/hermes_cli/web_routers/files.py
+++ b/hermes_cli/web_routers/files.py
@@ -240,6 +240,11 @@ def _media_serve_roots() -> list[Path]:
return out
+def _read_base64_file(path: Path) -> str:
+ """Read and encode a bounded file from a worker thread."""
+ return base64.b64encode(path.read_bytes()).decode("ascii")
+
+
@router.get("/api/media")
async def get_media(path: str):
"""Return a gateway-local image as a base64 data URL for remote clients
@@ -260,7 +265,7 @@ async def get_media(path: str):
if target.stat().st_size > _MEDIA_MAX_BYTES:
raise HTTPException(status_code=413, detail="File too large")
- encoded = base64.b64encode(target.read_bytes()).decode("ascii")
+ encoded = await asyncio.to_thread(_read_base64_file, target)
return {"data_url": f"data:{_MEDIA_CONTENT_TYPES[target.suffix.lower()]};base64,{encoded}"}
diff --git a/tests/hermes_cli/test_web_server_media_async.py b/tests/hermes_cli/test_web_server_media_async.py
new file mode 100644
index 00000000000..a7ad164fc7c
--- /dev/null
+++ b/tests/hermes_cli/test_web_server_media_async.py
@@ -0,0 +1,34 @@
+"""Dashboard media reads must not run on the event-loop thread."""
+
+import threading
+from pathlib import Path
+
+import pytest
+
+from hermes_cli.web_routers import files
+
+
+async def test_get_media_reads_and_encodes_off_event_loop(monkeypatch, tmp_path):
+ """The bounded media payload is read from a worker thread."""
+ image_dir = tmp_path / "images"
+ image_dir.mkdir()
+ image = image_dir / "sample.png"
+ image.write_bytes(b"\x89PNG\r\n\x1a\nimage-data")
+
+ monkeypatch.setattr(files, "get_hermes_home", lambda: tmp_path)
+ original_read_bytes = Path.read_bytes
+ read_threads = []
+
+ def _tracking_read_bytes(path):
+ read_threads.append(threading.current_thread())
+ return original_read_bytes(path)
+
+ monkeypatch.setattr(Path, "read_bytes", _tracking_read_bytes)
+ event_loop_thread = threading.current_thread()
+
+ response = await files.get_media(str(image))
+
+ assert response["data_url"].startswith("data:image/png;base64,")
+ assert read_threads
+ assert all(thread is not event_loop_thread for thread in read_threads)