Skip to content

The agent that grows with you

test: restore TUI gateway regression guards dropped by #120071

teknium148340244dc94
diff --git a/tests/tui_gateway/test_cold_start_gil_stall.py b/tests/tui_gateway/test_cold_start_gil_stall.py
index 0533c380830..d101462cba5 100644
--- a/tests/tui_gateway/test_cold_start_gil_stall.py
+++ b/tests/tui_gateway/test_cold_start_gil_stall.py
@@ -73,8 +73,49 @@ class TestCopilotAuthSkipsGhCli:
# ─── Fix 2: resolve_skin runs via to_thread in handle_ws ───────────────
+def test_handle_ws_resolves_skin_off_the_loop_thread(monkeypatch):
+ """Driving the real handle_ws: resolve_skin runs on a worker thread, never the
+ event-loop thread, and its result still reaches the gateway.ready frame
+ (#60800 cold-start stall; #72720 salvage)."""
+ import asyncio
+ import json
+ import threading
+ from tui_gateway import server, ws as ws_mod
+ idents = {}
+ frames = []
+
+ def _resolve_skin():
+ idents["skin"] = threading.get_ident()
+ return {"palette": "wired"}
+
+ monkeypatch.setattr(server, "resolve_skin", _resolve_skin)
+ monkeypatch.setattr(server, "_ensure_skin_watcher", lambda: None)
+ monkeypatch.setattr(server, "register_live_transport", lambda *_a, **_k: None)
+ monkeypatch.setattr(server, "_start_backend_heartbeat_refresher", lambda: None)
+ monkeypatch.setattr(server, "_schedule_startup_orphan_sweep", lambda: None, raising=False)
+ monkeypatch.setattr(server, "_WS_ORPHAN_REAP_GRACE_S", 0)
+
+ class FakeWS:
+ async def accept(self):
+ idents["loop"] = threading.get_ident()
+
+ async def send_text(self, line):
+ frames.append(json.loads(line))
+
+ async def receive_text(self):
+ raise ws_mod._WebSocketDisconnect()
+
+ async def close(self):
+ pass
+
+ asyncio.run(ws_mod.handle_ws(FakeWS()))
+
+ assert idents["skin"] != idents["loop"], (
+ "resolve_skin ran on the event loop thread — the #60800 cold-start stall is back")
+ ready = [f for f in frames if f.get("params", {}).get("type") == "gateway.ready"]
+ assert ready and ready[0]["params"]["payload"]["skin"] == {"palette": "wired"}
# ─── Fix 3: _warm_gateway_module pre-imports heavy chains ──────────────
diff --git a/tests/tui_gateway/test_entry_sys_path.py b/tests/tui_gateway/test_entry_sys_path.py
new file mode 100644
index 00000000000..392c1431f21
--- /dev/null
+++ b/tests/tui_gateway/test_entry_sys_path.py
@@ -0,0 +1,45 @@
+"""Regression test for tui_gateway/entry.py sys.path hardening (#15989, #51286).
+
+The TUI backend is spawned by Node with the user's launch directory as CWD. A
+local package there (e.g. ``utils/``, ``proxy/``, ``ui/`` in tg-ws-proxy) shadowed
+Hermes's own top-level modules and crashed the backend on import
+(``ImportError: cannot import name ... from 'utils'``). entry.py must run
+``hermes_bootstrap.harden_import_path()`` before its first non-stdlib import.
+Sibling guard for the slash worker: test_slash_worker_sys_path.py.
+"""
+
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+PROJECT_ROOT = Path(__file__).resolve().parents[2]
+
+
+def test_entry_imports_from_cwd_with_colliding_packages(tmp_path):
+ """Importing the TUI entry point from a CWD that ships its own ``utils/``
+ (and friends) must succeed — the guard strips CWD so Hermes's modules win."""
+ for pkg in ("utils", "proxy", "ui"):
+ (tmp_path / pkg).mkdir()
+ (tmp_path / pkg / "__init__.py").write_text("", encoding="utf-8")
+
+ env = {k: v for k, v in os.environ.items() if k != "HERMES_PYTHON_SRC_ROOT"}
+ # Source importable via PYTHONPATH; CWD ('') still precedes it on sys.path
+ # for ``-c``, so the shadow (and thus the guard) is exercised.
+ env["PYTHONPATH"] = str(PROJECT_ROOT)
+ env["HERMES_HOME"] = str(tmp_path / "hermes_home")
+
+ result = subprocess.run(
+ [sys.executable, "-c", "import tui_gateway.entry"],
+ cwd=tmp_path,
+ env=env,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=120,
+ )
+ assert result.returncode == 0, (
+ "tui_gateway.entry failed to import from a CWD with a colliding utils/ "
+ f"package (#51286):\n{result.stderr[-2000:]}"
+ )
diff --git a/tests/tui_gateway/test_protocol.py b/tests/tui_gateway/test_protocol.py
index a02ffbac72a..6ec0eb7bd98 100644
--- a/tests/tui_gateway/test_protocol.py
+++ b/tests/tui_gateway/test_protocol.py
@@ -1365,8 +1365,48 @@ def test_dispatch_runs_short_handlers_inline(server):
assert resp == {"jsonrpc": "2.0", "id": "r1", "result": {"pong": True}}
+ "slow_method",
+ ["complete.path", "complete.slash", "voice.toggle", "voice.record", "voice.tts", "wake.start", "wake.status"],
+)
+def test_slow_handlers_run_off_the_reader_thread(slow_method, server, monkeypatch):
+ """dispatch() must hand these RPCs to the pool and return at once, so a stalled handler never blocks
+ the stdin/WS reader behind it. Completion (#21123: git ls-files / skill scan froze prompt.submit for
+ the 120s RPC timeout) and voice/wake (synchronous faster-whisper lazy install, up to 300s: sent
+ messages never reached the agent) are the same bug class as #50005."""
+ release = threading.Event()
+ written = []
+
+ class _Transport:
+ def write(self, obj):
+ written.append(obj)
+ return True
+
+ def close(self):
+ pass
+ ran_on = []
+ def _stalled(rid, params):
+ ran_on.append(threading.get_ident())
+ release.wait(timeout=10)
+ return server._ok(rid, {})
+
+ monkeypatch.setitem(server._methods, slow_method, _stalled)
+
+ t0 = time.monotonic()
+ resp = server.dispatch({"id": "slow", "method": slow_method, "params": {}}, _Transport())
+ elapsed = time.monotonic() - t0
+ release.set()
+
+ assert resp is None, f"{slow_method} ran inline on the reader thread"
+ assert elapsed < 5
+ deadline = time.monotonic() + 10
+ while not written and time.monotonic() < deadline:
+ time.sleep(0.01)
+ # The pool worker, not the reader, ran the handler and wrote its response frame.
+ assert written and written[0]["id"] == "slow", written
+ assert ran_on and ran_on[0] != threading.get_ident()
def test_skin_live_switch_end_to_end(server, tmp_path, monkeypatch):
diff --git a/tests/tui_gateway/test_subprocess_encoding.py b/tests/tui_gateway/test_subprocess_encoding.py
new file mode 100644
index 00000000000..467c322c202
--- /dev/null
+++ b/tests/tui_gateway/test_subprocess_encoding.py
@@ -0,0 +1,64 @@
+"""Regression tests for lossy UTF-8 decoding of TUI gateway subprocess output (#53137).
+
+On Windows with a non-UTF-8 system locale (e.g. GBK on Chinese Windows), text-mode
+subprocess reads defaulted to the locale encoding, and a child emitting bytes invalid in
+that encoding raised UnicodeDecodeError inside the RPC handler / gateway thread.
+#53137 decodes every captured child stream as UTF-8 with ``errors="replace"``.
+
+These tests drive the real RPC handlers against a real child process that writes
+invalid UTF-8, so they fail on any host if the lossy decode is dropped (strict UTF-8
+raises on ``b"\\xff\\xfe"`` just like GBK does on the reported bytes).
+
+# Test pattern adapted from @devorun's PR #52700 (salvage convention).
+"""
+
+from __future__ import annotations
+
+import sys
+
+import pytest
+
+from tui_gateway import server
+
+def bad_bytes_cmd(tmp_path):
+ """A shell command running a child that writes bytes invalid in UTF-8 (and in most
+ locale codepages), then text. A script file rather than ``-c`` so the shell.exec
+ approval gate lets it through; quoted paths work under /bin/sh and cmd.exe."""
+ script = tmp_path / "emit_bad_bytes.py"
+ script.write_text(
+ "import sys\nsys.stdout.buffer.write(bytes([255, 254]) + b' tail-ok')\nsys.stdout.flush()\n",
+ encoding="utf-8",
+ )
+ return f'"{sys.executable}" "{script}"'
+
+
+def test_shell_exec_survives_non_utf8_child_output(bad_bytes_cmd):
+ """``!cmd`` via shell.exec returns the output (with replacement chars) instead of a
+ decode failure surfaced as a 5003 error."""
+ resp = server.handle_request(
+ {"id": "enc", "method": "shell.exec", "params": {"command": bad_bytes_cmd}}
+ )
+
+ assert "error" not in resp, resp
+ assert resp["result"]["code"] == 0
+ assert "tail-ok" in resp["result"]["stdout"]
+ assert "\ufffd" in resp["result"]["stdout"]
+
+
+def test_quick_command_exec_survives_non_utf8_child_output(monkeypatch, bad_bytes_cmd):
+ """A ``type: exec`` quick command runs subprocess.run outside any try block, so a
+ strict decode would raise straight out of command.dispatch."""
+ monkeypatch.setattr(
+ server,
+ "_load_cfg",
+ lambda: {"quick_commands": {"badbytes": {"type": "exec", "command": bad_bytes_cmd}}},
+ )
+
+ resp = server.handle_request(
+ {"id": "enc", "method": "command.dispatch", "params": {"name": "badbytes"}}
+ )
+
+ assert "error" not in resp, resp
+ assert resp["result"]["type"] == "exec"
+ assert "tail-ok" in resp["result"]["output"]
diff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.py
index b61c9d0dbd5..b3c95201b15 100644
--- a/tests/tui_gateway/test_tui_gateway_server.py
+++ b/tests/tui_gateway/test_tui_gateway_server.py
@@ -16424,6 +16424,60 @@ def test_model_save_key_reconciles_the_launch_profiles_stale_setup_record(monkey
+def test_prompt_submit_releases_old_history_before_heap_trim(monkeypatch, tmp_path):
+ """The post-turn heap trim must run after the turn's pre-turn history snapshots are dropped:
+ malloc_trim cannot return pages still referenced, so a retained snapshot of a large tool
+ result pins them for the life of the process. Observed through a weak reference to the old
+ message, not by reading the finisher's local variable names."""
+ import contextlib
+ import gc
+ import weakref
+
+ class _Msg(dict):
+ """dict itself is not weakref-able."""
+
+ observed = {}
+ order = []
+
+ class _Agent:
+ def run_conversation(self, prompt, conversation_history=None, stream_callback=None, **_kw):
+ return {"final_response": "reply", "messages": [{"role": "assistant", "content": "reply"}]}
+
+ def _trim(**_kwargs):
+ order.append("trim")
+ gc.collect()
+ observed["alive_at_trim"] = old_ref() is not None
+
+ old = _Msg(role="tool", tool_call_id="old", content="x" * 20_000)
+ old_ref = weakref.ref(old)
+ session = _session(agent=_Agent())
+ profile_home = tmp_path / "profiles" / "worker"
+ profile_home.mkdir(parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ session["profile_home"] = str(profile_home)
+ session["history"] = [old]
+ del old
+ server._sessions["sid_trim"] = session
+ try:
+ monkeypatch.setattr(server.threading, "Thread", _ImmediateThread)
+ monkeypatch.setattr(server, "_get_usage", lambda _a: {})
+ monkeypatch.setattr(server, "render_message", lambda _t, _c: "")
+ monkeypatch.setattr(server, "_emit", lambda *a: None)
+ monkeypatch.setattr(server, "set_hermes_home_override", lambda _home: object())
+ monkeypatch.setattr(server, "reset_hermes_home_override", lambda _token: order.append("reset_home"))
+ monkeypatch.setattr(server, "_session_profile_runtime_scope", lambda _session: contextlib.nullcontext())
+ monkeypatch.setattr("hermes_cli.mem_trim.trim_memory", _trim)
+
+ resp = server.handle_request(
+ {"id": "1", "method": "prompt.submit", "params": {"session_id": "sid_trim", "text": "hi"}})
+
+ assert resp is not None and resp.get("result")
+ assert order == ["trim", "reset_home"]
+ assert observed["alive_at_trim"] is False, "a pre-turn history snapshot survived to the heap trim"
+ finally:
+ server._sessions.pop("sid_trim", None)
+
+
class _ImmediateThread:
"""Runs the target callable synchronously so assertions can follow."""