The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: purge low-value tests, lane py20 (206 removed)
teknium11693fca97a1b
diff --git a/tests/tui_gateway/test_custom_provider_session_persistence.py b/tests/tui_gateway/test_custom_provider_session_persistence.pyindex 89b73fc9ef6..4618998eed2 100644--- a/tests/tui_gateway/test_custom_provider_session_persistence.py+++ b/tests/tui_gateway/test_custom_provider_session_persistence.py@@ -700,35 +700,7 @@ class TestFollowProfileConfigRuntimeOverrides:}assert _stored_session_runtime_overrides(row) == {}- def test_marked_row_dict_model_config_returns_no_overrides(self):- """Same contract when model_config is already a dict (not JSON)."""- from tui_gateway.server import _stored_session_runtime_overrides-- row = {- "model": "openai/gpt-5.6-luna-pro",- "model_config": {- "model": "openai/gpt-5.6-luna-pro",- "provider": "nous",- "follow_profile_config": True,- },- }- assert _stored_session_runtime_overrides(row) == {}-- def test_unmarked_row_still_restores_stored_runtime(self):- """Normal 1:1 user chats keep the stored-runtime restore — the- contract must not leak into ordinary sessions."""- from tui_gateway.server import _stored_session_runtime_overrides- row = {- "model": "openai/gpt-5.6-luna-pro",- "billing_provider": "nous",- "model_config": json.dumps(- {"model": "openai/gpt-5.6-luna-pro", "provider": "nous"}- ),- }- overrides = _stored_session_runtime_overrides(row)- assert overrides["model_override"]["model"] == "openai/gpt-5.6-luna-pro"- assert overrides["model_override"]["provider"] == "nous"def test_legacy_bot_chat_title_backfills_contract(self):"""Canonical Bot Chats created BEFORE the marker existed carry no@@ -914,38 +886,6 @@ class TestRuntimeModelConfigDropsStaleKeys:assert overrides["model_override"]["provider"] == "nous"assert overrides["provider_override"] == "nous"- def test_real_db_persist_heals_desynced_row(self, tmp_path, monkeypatch):- """A row already desynced (fresh model column + stale model_config- provider) self-heals on the next live metadata persist."""- monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))- db = SessionDB(db_path=tmp_path / "state.db")- db.create_session(session_id="desync1", source="desktop", model="old-model")- db.update_session_meta(- "desync1",- json.dumps(- {- "model": "deepseek/deepseek-v4-flash-0731",- "provider": "stealth-ox-alpha",- "base_url": "https://api.venice.ai/api/v1",- }- ),- model="deepseek/deepseek-v4-flash-0731",- )-- from tui_gateway.server import _runtime_model_config-- row = db.get_session("desync1")- assert row is not None- existing = json.loads(row["model_config"])- merged = _runtime_model_config(_agent_like(), existing)- db.update_session_meta("desync1", json.dumps(merged), model="deepseek/deepseek-v4-flash-0731")-- healed_row = db.get_session("desync1")- assert healed_row is not None- healed = json.loads(healed_row["model_config"])- assert healed["model"] == "deepseek/deepseek-v4-flash-0731"- assert "provider" not in healed, healed- assert "base_url" not in healed, healeddef test_existing_none_returns_only_agent_identity(self):"""First write (no existing row): the merge starts from an empty dictdiff --git a/tests/tui_gateway/test_deferred_agent_build_cwd.py b/tests/tui_gateway/test_deferred_agent_build_cwd.pydeleted file mode 100644index 7b356206f11..00000000000--- a/tests/tui_gateway/test_deferred_agent_build_cwd.py+++ /dev/null@@ -1,59 +0,0 @@-"""Regression coverage for logical cwd propagation in deferred TUI/Desktop builds."""--import threading-import uuid-from types import SimpleNamespace--from tui_gateway import server---def test_deferred_agent_build_threads_session_cwd(monkeypatch, tmp_path):- """A cold Desktop build must not fall back to the serve process cwd."""- workspace = tmp_path / "workspace"- workspace.mkdir()- captured = {}- built = threading.Event()- ready = threading.Event()- sid = f"cwd-build-{uuid.uuid4().hex[:8]}"- session = {- "agent_ready": ready,- "session_key": f"cwd-key-{uuid.uuid4().hex[:8]}",- "cwd": str(workspace),- }-- def fake_set_session_context(key, cwd=None):- captured["context_key"] = key- captured["context_cwd"] = cwd- return []-- def fake_make_agent(*args, **kwargs):- captured["agent_cwd"] = kwargs.get("cwd_override")- built.set()- return SimpleNamespace(model="test", session_id=session["session_key"])-- monkeypatch.setattr(server, "_set_session_context", fake_set_session_context)- monkeypatch.setattr(server, "_clear_session_context", lambda _tokens: None)- monkeypatch.setattr(server, "_make_agent", fake_make_agent)- monkeypatch.setattr(- "tui_gateway.entry.ensure_mcp_discovery_started", lambda: None- )- monkeypatch.setattr(server, "_wire_callbacks", lambda _sid: None)- monkeypatch.setattr(server, "_config_model_target", lambda: ("", ""))- monkeypatch.setattr(server, "_start_notification_poller", lambda *a, **k: None)- monkeypatch.setattr(server, "_schedule_mcp_late_refresh", lambda *a, **k: None)- monkeypatch.setattr(server, "_emit", lambda *a, **k: None)- monkeypatch.setattr(server, "_notify_session_boundary", lambda *a, **k: None)-- server._sessions[sid] = session- try:- server._start_agent_build(sid, session)- assert built.wait(timeout=15), "agent build thread never called _make_agent"- assert ready.wait(timeout=5), "agent_ready never set after build"- finally:- server._sessions.pop(sid, None)- from tools.approval import unregister_gateway_notify-- unregister_gateway_notify(session["session_key"])-- assert captured["context_cwd"] == str(workspace)- assert captured["agent_cwd"] == str(workspace)diff --git a/tests/tui_gateway/test_deferred_model_switch_confirm.py b/tests/tui_gateway/test_deferred_model_switch_confirm.pyindex 5a3b688b2f3..8c184ed37ab 100644--- a/tests/tui_gateway/test_deferred_model_switch_confirm.py+++ b/tests/tui_gateway/test_deferred_model_switch_confirm.py@@ -95,11 +95,6 @@ class TestGuardedPickAsksBeforeStashing:"start would drop it anyway, after the pill already moved")- def test_confirm_message_names_the_guard(self, running_session):- message = _config_set_model(GUARDED_MODEL)["result"]["confirm_message"]-- assert "CONTRIBUTOR TIER" in message- assert "train" in message.lower()def test_reconfirming_queues_the_pick(self, running_session):resp = _config_set_model(GUARDED_MODEL, confirm_expensive_model=True)@@ -163,53 +158,3 @@ class TestGuardFailureIsNotFatal:assert running_session["pending_model_switch"]["raw"] == GUARDED_MODEL-class TestHelperContract:- def test_returns_none_for_an_empty_model(self):- assert server._pending_switch_selection_warning("", "") is None-- def test_returns_none_when_no_guard_fires(self):- assert server._pending_switch_selection_warning(UNGUARDED_MODEL, "") is None-- def test_returns_the_message_when_a_guard_fires(self):- message = server._pending_switch_selection_warning(GUARDED_MODEL, "")-- assert message is not None- assert "CONTRIBUTOR TIER" in message-- def test_an_explicit_provider_reaches_the_guards(self, monkeypatch):- """Provider-keyed guards are useless if the provider is dropped here.-- The docstring promises the early call can only under-fire relative to- the resolved one, and that only holds if what the caller DID say is- forwarded. Asserting on a guarded model id would pass even with- ``provider`` dropped, so record the kwargs instead.- """- seen = {}-- def _fake(model, provider=None, **kwargs):- seen["model"] = model- seen["provider"] = provider- return None-- import hermes_cli.model_selection_guards as guards-- monkeypatch.setattr(guards, "combined_selection_warning", _fake)- server._pending_switch_selection_warning(UNGUARDED_MODEL, "openrouter")-- assert seen == {"model": UNGUARDED_MODEL, "provider": "openrouter"}-- def test_an_empty_provider_is_normalised_to_none(self, monkeypatch):- """`provider or None` is load-bearing: "" is not "no provider" to a- guard that does an `is None` check, and the TUI sends "" for unset."""- seen = {}-- def _fake(model, provider=None, **kwargs):- seen["provider"] = provider- return None-- import hermes_cli.model_selection_guards as guards-- monkeypatch.setattr(guards, "combined_selection_warning", _fake)- server._pending_switch_selection_warning(UNGUARDED_MODEL, "")-- assert seen == {"provider": None}diff --git a/tests/tui_gateway/test_diagnostics_share_nous.py b/tests/tui_gateway/test_diagnostics_share_nous.pyindex bdeea5ad2ff..4294229cd16 100644--- a/tests/tui_gateway/test_diagnostics_share_nous.py+++ b/tests/tui_gateway/test_diagnostics_share_nous.py@@ -107,7 +107,7 @@ def test_share_nous_linkless_success_is_a_failure(monkeypatch):result = _handler()("rid-2c", {})payload = result["result"]assert payload["ok"] is False- assert "no view URL" in payload["error"]+ assert payload["error"]def test_share_nous_extra_files_sanitized_and_redacted(captured_upload):diff --git a/tests/tui_gateway/test_eager_multiplex_activation.py b/tests/tui_gateway/test_eager_multiplex_activation.pyindex 77fcf6a92b9..75846cf4805 100644--- a/tests/tui_gateway/test_eager_multiplex_activation.py+++ b/tests/tui_gateway/test_eager_multiplex_activation.py@@ -53,7 +53,7 @@ def test_a_crashed_profile_create_shell_is_not_a_second_tenant(two_profile_host)assert not secret_scope.is_multiplex_active()-def test_unreadable_profiles_dir_fails_closed_and_says_so(two_profile_host, monkeypatch, caplog):+def test_unreadable_profiles_dir_fails_closed_and_says_so(two_profile_host, monkeypatch):"""Silently returning False left the guard off for the process lifetime with zero log lines."""from hermes_cli import profiles as profiles_mod@@ -62,7 +62,5 @@ def test_unreadable_profiles_dir_fails_closed_and_says_so(two_profile_host, monkmonkeypatch.setattr(profiles_mod, "profiles_to_serve", _boom)- with caplog.at_level("WARNING"):- assert launch_profile_policy.activate_multi_profile_hosting_eagerly() is True+ assert launch_profile_policy.activate_multi_profile_hosting_eagerly() is Trueassert secret_scope.is_multiplex_active()- assert any("profile homes" in r.getMessage() for r in caplog.records), caplog.textdiff --git a/tests/tui_gateway/test_entry_inline_handler_error.py b/tests/tui_gateway/test_entry_inline_handler_error.pyindex 8b51010b40e..e14fc4ee406 100644--- a/tests/tui_gateway/test_entry_inline_handler_error.py+++ b/tests/tui_gateway/test_entry_inline_handler_error.py@@ -42,11 +42,9 @@ def test_main_reports_inline_handler_error_and_keeps_reading(monkeypatch):entry.main()- assert replies[1] == {- "jsonrpc": "2.0",- "id": "broken",- "error": {"code": -32000, "message": "handler error: clipboard backend is unavailable"},- }+ assert replies[1]["id"] == "broken"+ assert replies[1]["error"]["code"] == -32000+ assert "clipboard backend is unavailable" in replies[1]["error"]["message"]assert replies[2] == {"jsonrpc": "2.0", "id": "next", "result": {"ok": True}}# Forensics: the survived crash leaves the same crash-log trail a fatal one would.assert len(breadcrumbs) == 1 and "clipboard.save" in breadcrumbs[0]diff --git a/tests/tui_gateway/test_entry_picker_prewarm.py b/tests/tui_gateway/test_entry_picker_prewarm.pyindex 530cb9530b2..4da3293578f 100644--- a/tests/tui_gateway/test_entry_picker_prewarm.py+++ b/tests/tui_gateway/test_entry_picker_prewarm.py@@ -26,9 +26,7 @@ from __future__ import annotationsimport io-import hermes_cli.model_switch as msfrom tui_gateway import entry-import hermes_cli.model_switch_providersfrom hermes_cli import model_switch_providers@@ -68,24 +66,6 @@ def _run_main(monkeypatch, events, *, prewarm=None):entry.main()-def test_main_prewarms_picker_cache_after_gateway_ready(monkeypatch):- """main() must call the prewarm helper once, after gateway.ready is- written, and still reach the stdin loop (returns on EOF = non-blocking)."""- events: list[tuple] = []-- _run_main(monkeypatch, events) # returning at all proves the loop was reached-- prewarm_calls = [e for e in events if e[0] == "prewarm"]- assert len(prewarm_calls) == 1, (- f"main() must invoke prewarm_picker_cache_async exactly once, got {events!r}"- )-- ready_idx = events.index(("write", "gateway.ready"))- prewarm_idx = events.index(("prewarm",))- assert ready_idx < prewarm_idx, (- "prewarm must fire AFTER the gateway.ready write (idle window, "- f"banner already shown); order was {events!r}"- )def test_main_survives_prewarm_failure(monkeypatch):diff --git a/tests/tui_gateway/test_entry_sys_path.py b/tests/tui_gateway/test_entry_sys_path.pydeleted file mode 100644index 940c004a44f..00000000000--- a/tests/tui_gateway/test_entry_sys_path.py+++ /dev/null@@ -1,71 +0,0 @@-"""Tests for tui_gateway/entry.py sys.path hardening (issues #15989, #51286).--When the TUI backend is spawned by Node.js, the launch directory may shadow-Hermes's own top-level modules (``utils``, ``proxy``, ``ui``). entry.py must-neutralize this before any non-stdlib import is resolved, by delegating to the-shared ``hermes_bootstrap.harden_import_path`` guard.--These tests assert the entry point wires up the real guard (rather than-re-implementing it inline) and that the guard's behavior covers both the-relative-cwd form and the absolute-cwd-path form that was the actual #51286-failure.-"""--import ast-import pathlib--import hermes_bootstrap---def _entry_source() -> str:- here = pathlib.Path(__file__).resolve()- repo_root = here.parent.parent.parent # tests/tui_gateway/ -> repo root- return (repo_root / "tui_gateway" / "entry.py").read_text(encoding="utf-8")---def test_entry_calls_shared_harden_guard_before_heavy_imports():- """entry.py must call hermes_bootstrap.harden_import_path() before it- imports tui_gateway.server (which pulls ``from utils import ...``)."""- source = _entry_source()- tree = ast.parse(source)-- harden_call_line = None- server_import_line = None- for node in ast.walk(tree):- if (- isinstance(node, ast.Call)- and isinstance(node.func, ast.Attribute)- and node.func.attr == "harden_import_path"- ):- harden_call_line = node.lineno- if isinstance(node, ast.ImportFrom) and (node.module or "").startswith(- "tui_gateway"- ):- if server_import_line is None:- server_import_line = node.lineno-- assert harden_call_line is not None, (- "entry.py must call hermes_bootstrap.harden_import_path()"- )- assert server_import_line is not None, "entry.py must import from tui_gateway"- assert harden_call_line < server_import_line, (- "harden_import_path() must run before tui_gateway.server is imported"- )---def test_guard_handles_absolute_cwd_path():- """The #51286 case: the launch dir is on sys.path as its own absolute- path, ahead of the Hermes root. harden_import_path must relocate the- Hermes root to the front so ``from utils import ...`` resolves to Hermes."""- import sys-- original = sys.path[:]- try:- sys.path[:] = ["/home/user/tg-ws-proxy", "/opt/hermes", "/usr/lib"]- hermes_bootstrap.harden_import_path(src_root="/opt/hermes")- assert sys.path[0] == "/opt/hermes"- assert sys.path.index("/opt/hermes") < sys.path.index(- "/home/user/tg-ws-proxy"- )- finally:- sys.path[:] = originaldiff --git a/tests/tui_gateway/test_ephemeral_profile_override.py b/tests/tui_gateway/test_ephemeral_profile_override.pyindex f2588d264cf..aba18754598 100644--- a/tests/tui_gateway/test_ephemeral_profile_override.py+++ b/tests/tui_gateway/test_ephemeral_profile_override.py@@ -100,14 +100,6 @@ class TestBackgroundProfileOverride:override_calls["reset"].assert_called_once_with("TOK")override_calls["agent"].run_conversation.assert_called_once()- def test_background_no_profile_skips_override(self, override_calls):- """With no profile_home the background path never touches the override."""- session = {"agent": MagicMock(), "session_key": "sess_k", "profile_home": None}- _run("prompt.background", {"text": "hi", "session_id": "ui1"}, session)-- override_calls["set"].assert_not_called()- override_calls["reset"].assert_not_called()- override_calls["agent"].run_conversation.assert_called_once()def test_background_restores_override_on_error(self, fake_session, override_calls):"""A failing turn must still restore the override (finally-block parity)."""@@ -144,15 +136,3 @@ class TestPreviewRestartProfileOverride:# tearing down the very background server the restart just launched.override_calls["agent"].close.assert_not_called()- def test_preview_no_profile_skips_override(self, override_calls):- """With no profile_home the preview path never touches the override."""- session = {"agent": MagicMock(), "session_key": "sess_k", "profile_home": None}- _run(- "preview.restart",- {"url": "http://localhost:5173", "cwd": "", "session_id": "ui1"},- session,- )-- override_calls["set"].assert_not_called()- override_calls["reset"].assert_not_called()- override_calls["agent"].close.assert_not_called()diff --git a/tests/tui_gateway/test_fast_session_scope.py b/tests/tui_gateway/test_fast_session_scope.pyindex 8b3e230e75e..c46b41a1ea0 100644--- a/tests/tui_gateway/test_fast_session_scope.py+++ b/tests/tui_gateway/test_fast_session_scope.py@@ -120,7 +120,3 @@ class TestConfigGetFastSessionScope:assert resp["result"]["value"] == "fast"- def test_falls_back_to_global(self) -> None:- with patch.object(server, "_load_service_tier", return_value="priority"):- resp = _get({"key": "fast"})- assert resp["result"]["value"] == "fast"diff --git a/tests/tui_gateway/test_finalize_session_persist.py b/tests/tui_gateway/test_finalize_session_persist.pyindex f5ddf7aa353..f3b8e21ec8c 100644--- a/tests/tui_gateway/test_finalize_session_persist.py+++ b/tests/tui_gateway/test_finalize_session_persist.py@@ -52,45 +52,7 @@ def _make_session(agent=None, history=None, session_key="test_key_001"):class TestFinalizeSessionPersist:"""Verify _finalize_session flushes messages via _persist_session."""- def test_no_session_messages_skips_persist(self):- """When _session_messages is empty/None the agent processed nothing- this session, so there is nothing new to flush. Falling back to- session["history"] here re-appended already-durable resumed rows as- duplicates, so finalize must NOT write in that case.- """- from tui_gateway.server import _finalize_session-- history = [- {"role": "user", "content": "hello"},- {"role": "assistant", "content": "hi there"},- ]- agent = _make_agent() # _session_messages is None- session = _make_session(agent=agent, history=history)-- _finalize_session(session, end_reason="test")-- agent._persist_session.assert_not_called()-- def test_persist_uses_session_messages(self):- """agent._session_messages is flushed via the marker-based dedup path- (no conversation_history — passing the same list neutered the write)."""- from tui_gateway.server import _finalize_session-- history = [{"role": "user", "content": "old"}]- session_msgs = [- {"role": "user", "content": "old"},- {"role": "assistant", "content": "newer"},- ]- agent = _make_agent()- agent._session_messages = session_msgs- session = _make_session(agent=agent, history=history)- _finalize_session(session)-- agent._persist_session.assert_called_once_with(session_msgs)- # conversation_history must NOT be passed — it aliases the snapshot and- # makes _flush_messages_to_session_db skip every message.- assert "conversation_history" not in agent._persist_session.call_args[1]def test_commit_memory_still_called(self):"""Existing memory commit path is preserved."""@@ -105,16 +67,6 @@ class TestFinalizeSessionPersist:agent.commit_memory_session.assert_called_once()- def test_empty_history_skips_persist(self):- """Empty history → _persist_session not called (guard)."""- from tui_gateway.server import _finalize_session-- agent = _make_agent()- session = _make_session(agent=agent, history=[])-- _finalize_session(session)-- agent._persist_session.assert_not_called()def test_already_finalized_skips(self):@@ -130,20 +82,6 @@ class TestFinalizeSessionPersist:agent._persist_session.assert_not_called()- @patch("tui_gateway.server._get_db")- def test_db_end_session_still_called(self, mock_get_db):- """Existing db.end_session() path is preserved after the new code."""- from tui_gateway.server import _finalize_session-- mock_db = MagicMock()- mock_get_db.return_value = mock_db-- agent = _make_agent(session_id="sess_123")- session = _make_session(agent=agent, history=[{"role": "user", "content": "x"}])-- _finalize_session(session, end_reason="test")-- mock_db.end_session.assert_called_once_with("sess_123", "test")class TestFinalizeSessionPersistE2E:diff --git a/tests/tui_gateway/test_gateway_owned_session_reap.py b/tests/tui_gateway/test_gateway_owned_session_reap.pyindex 5d58e936b6f..d52bf334ac4 100644--- a/tests/tui_gateway/test_gateway_owned_session_reap.py+++ b/tests/tui_gateway/test_gateway_owned_session_reap.py@@ -9,11 +9,11 @@ loops. The TUI is only a viewer of those sessions."""import threading-from unittest.mock import MagicMock, patch+from unittest.mock import MagicMockimport pytest-from tui_gateway.server import _finalize_session, _is_gateway_owned_source, _teardown_session+from tui_gateway.server import _is_gateway_owned_source, _teardown_sessionclass TestIsGatewayOwnedSource:@@ -22,23 +22,13 @@ class TestIsGatewayOwnedSource:"matrix", "mattermost", "bluebubbles", "sms", "email"):assert _is_gateway_owned_source(src) is True, src- def test_case_and_whitespace_normalized(self):- assert _is_gateway_owned_source(" Telegram ") is Truedef test_tui_owned_sources_are_not(self):for src in ("tui", "cli", "webui", "desktop", "cron", "subagent","test", "acp", ""):assert _is_gateway_owned_source(src) is False, src- def test_local_and_server_endpoints_are_not(self):- # Platform enum members, but their sessions aren't owned by a remote- # chat surface — reaping them keeps /resume clean.- for src in ("local", "webhook", "api_server", "msgraph_webhook"):- assert _is_gateway_owned_source(src) is False, src- def test_arbitrary_strings_are_not(self):- assert _is_gateway_owned_source("hermesbench-task-xyz") is False- assert _is_gateway_owned_source(None) is Falsedef _make_session(session_id="sess_1"):@@ -91,29 +81,6 @@ def _read_real_row(db_path, session_id):db.close()-class TestFinalizeSkipsGatewaySessions:- @patch("tui_gateway.server._get_db")- def test_gateway_session_not_ended(self, mock_get_db):- db = MagicMock()- db.get_session.return_value = {"id": "sess_1", "source": "telegram"}- mock_get_db.return_value = db-- _finalize_session(_make_session(), end_reason="ws_orphan_reap")-- db.end_session.assert_not_called()--- @patch("tui_gateway.server._get_db")- def test_missing_row_still_ended(self, mock_get_db):- """A session with no state.db row can't be gateway-owned — keep the- pre-existing reap behavior."""- db = MagicMock()- db.get_session.return_value = None- mock_get_db.return_value = db-- _finalize_session(_make_session(), end_reason="tui_close")-- db.end_session.assert_called_once_with("sess_1", "tui_close")class TestGatewayOwnedSessionTeardown:diff --git a/tests/tui_gateway/test_goal_command.py b/tests/tui_gateway/test_goal_command.pyindex 0e096f1d7b7..fce21e5ceb6 100644--- a/tests/tui_gateway/test_goal_command.py+++ b/tests/tui_gateway/test_goal_command.py@@ -218,11 +218,6 @@ def test_successful_goal_turn_accepts_only_valid_completion_outcomes(# ── command.dispatch /goal ────────────────────────────────────────────-def test_goal_bare_shows_status_when_none_set(server, session):- sid, _, _ = session- r = _call(server, "command.dispatch", name="goal", arg="", session_id=sid)- assert r["result"]["type"] == "exec"- assert "No active goal" in r["result"]["output"]def _exhaust_budget(session_key: str, goal_text: str = "finish the benchmark"):@@ -260,9 +255,8 @@ def test_goal_resume_after_budget_exhaustion_dispatches_continuation(r = _call(server, "command.dispatch", name="goal", arg="resume", session_id=sid)result = r["result"]assert result["type"] == "send"- assert result["message"].startswith("[Continuing toward your standing goal]")+ assert result["message"].strip()assert result["display"] == "/goal resume"- assert "Goal resumed" in result["notice"]state = GoalManager(session_key).stateassert state.status == "active"@@ -273,7 +267,6 @@ def test_goal_resume_without_goal_stays_exec(server, session):sid, _, _ = sessionr = _call(server, "command.dispatch", name="goal", arg="resume", session_id=sid)assert r["result"]["type"] == "exec"- assert "No goal to resume" in r["result"]["output"]# ── slash.exec /goal routing ──────────────────────────────────────────@@ -289,13 +282,8 @@ def test_slash_exec_routes_goal_to_command_dispatch(server, session):# Should succeed by routing to command.dispatch internallyassert "result" in rassert r["result"]["type"] == "exec"- assert "No active goal" in r["result"]["output"]-def test_pending_input_commands_includes_goal(server):- """Guard: _PENDING_INPUT_COMMANDS must list 'goal' — removing it would- silently re-break the TUI."""- assert "goal" in server._PENDING_INPUT_COMMANDSdef test_iteration_limit_fallback_is_judged_and_can_continue(@@ -425,15 +413,14 @@ def test_second_consecutive_exhaustion_pauses_goal_instead_of_looping(state = GoalManager(session_key).stateassert state.status == "paused"assert state.turns_used == 0- assert "compression exhausted twice" in state.paused_reason+ assert state.paused_reasonassert server._GOAL_COMPRESSION_RECOVERY_ATTEMPTS not in sessionnotices = [p["text"]for event, _sid, p in turn_envif event == "status.update" and p.get("kind") == "goal"]- assert any("Retrying the active goal once" in text for text in notices)- assert any("Goal paused" in text for text in notices)+ assert len(notices) >= 2 # retry notice, then pause noticedef test_real_queued_prompt_preempts_goal_compression_retry(@@ -534,7 +521,7 @@ def test_new_goal_does_not_inherit_previous_goal_recovery_attempt(server):assert first_prompt is not Noneassert replacement_prompt is not Noneassert "replacement goal" in replacement_prompt- assert "Retrying the active goal once" in replacement_notice+ assert replacement_noticeassert GoalManager(session_key).state.status == "active"@@ -545,24 +532,6 @@ def _write_moa_config(home, text):cfg_path.write_text(text)-def test_moa_bare_returns_usage(server, session, hermes_home):- _write_moa_config(hermes_home, """-moa:- default_preset: default- presets:- default:- reference_models:- - provider: openai-codex- model: gpt-5.5- aggregator:- provider: openrouter- model: anthropic/claude-opus-4.8-""")- sid, _, s = session- r = _call(server, "command.dispatch", name="moa", arg="", session_id=sid)- # Bare /moa is usage-only now; switching to a preset is via the model picker.- assert "error" in r- assert "model_override" not in s@pytest.mark.parametrize("method", ["command.dispatch", "slash.exec"])diff --git a/tests/tui_gateway/test_groups_methods.py b/tests/tui_gateway/test_groups_methods.pyindex f85fcc5ed86..3111b14b3fb 100644--- a/tests/tui_gateway/test_groups_methods.py+++ b/tests/tui_gateway/test_groups_methods.py@@ -60,30 +60,6 @@ def _create_room():)["room"]-def test_capabilities_are_honest_about_the_driver_boundary(home):- methods_groups.stop_hosted_room_service(timeout=1.0)- result = _result(srv._methods["groups.capabilities"](1, {}))-- assert result["protocol_version"] == 2- assert result["driver"] is False- assert result["authority_gateway_id"] == _server_authority()- assert "authority_epoch" in result["features"]- assert "coordinator_fencing" in result["features"]- assert "monotonic_log" in result["features"]- assert "groups.state" in result["methods"]- assert "groups.send" in result["methods"]- assert "groups.send" in srv._LONG_HANDLERS- assert "groups.retry" in result["methods"]- assert "groups.approve" in result["methods"]- advertised = [- str(value).lower() for value in (*result["features"], *result["methods"])- ]- assert not any(- token in value- for token in ("attachment", "desktop", "messaging")- for value in advertised- )- assert result["room_link"]["enabled"] is Truedef test_capabilities_and_invitation_advertise_scoped_roomlink(home, monkeypatch):@@ -153,7 +129,6 @@ def test_capabilities_disable_roomlink_when_run_replay_is_not_durable(},)assert invitation["error"]["code"] == 4120- assert "durable run idempotency" in invitation["error"]["message"]def test_capabilities_open_shared_durable_run_store_without_test_injection(@@ -534,7 +509,6 @@ def test_rpc_retry_is_idempotent_and_conflict_is_visible(home):},)assert conflict["error"]["code"] == 4111- assert "different content" in conflict["error"]["message"]def test_foreign_authority_cannot_send_or_disband(home):@@ -902,7 +876,6 @@ def test_pruned_room_send_and_log_report_expired_history(home, monkeypatch):assert sent["error"]["data"] == {"reason": "room_history_expired"}assert logged["error"]["data"] == {"reason": "room_history_expired"}assert renamed["error"]["data"] == {"reason": "room_history_expired"}- assert "permanently retired" in sent["error"]["message"]recreated = srv._methods["groups.create"](7,diff --git a/tests/tui_gateway/test_groups_replication_methods.py b/tests/tui_gateway/test_groups_replication_methods.pyindex 3947f18daf2..7750071b8bb 100644--- a/tests/tui_gateway/test_groups_replication_methods.py+++ b/tests/tui_gateway/test_groups_replication_methods.py@@ -61,18 +61,6 @@ def _authority_page(tmp_path, gateway_id="install:" + "a" * 32, n=3):return rooms.read_events(db, room_id="room-1", since_seq=0, limit=100)-def test_capabilities_advertise_replication(home):- result = _result(srv._methods["groups.capabilities"](1, {}))- assert "log_replication" in result["features"]- assert "authority_takeover" in result["features"]- for name in (- "groups.replicate",- "groups.replica_state",- "groups.promote",- "groups.demote",- ):- assert name in result["methods"]- assert name in srv._LONG_HANDLERSdef test_replicate_then_state_roundtrip(home, tmp_path):diff --git a/tests/tui_gateway/test_gui_surface_toolsets.py b/tests/tui_gateway/test_gui_surface_toolsets.pyindex 512821eee6c..a851c3af6b3 100644--- a/tests/tui_gateway/test_gui_surface_toolsets.py+++ b/tests/tui_gateway/test_gui_surface_toolsets.py@@ -15,7 +15,7 @@ answer is identical on every connection topology.import pytestimport tui_gateway.server as server-from toolsets import TOOLSETS, resolve_toolset+from toolsets import TOOLSETSGUI_TOOLS = {"annotate_preview",@@ -41,14 +41,6 @@ def no_desktop_env(monkeypatch):class TestDesktopUiToolset:- def test_holds_exactly_the_gui_affordances(self):- # apply_layout registers into desktop_ui via the registry (not the- # static toolsets.py list), so force discovery first — otherwise the- # result depends on which earlier test imported tool modules- # (pre-existing ordering flake, surfaced by the #97979 test sweep).- from tools.registry import discover_builtin_tools- discover_builtin_tools()- assert set(resolve_toolset("desktop_ui")) == GUI_TOOLS | {"apply_layout"}def test_stays_off_the_core_tool_list(self):"""Core ships on every API call — a GUI-only tool must not be there."""diff --git a/tests/tui_gateway/test_hosted_room_driver_runtime.py b/tests/tui_gateway/test_hosted_room_driver_runtime.pyindex 92a35b44cb1..2bbc20d5628 100644--- a/tests/tui_gateway/test_hosted_room_driver_runtime.py+++ b/tests/tui_gateway/test_hosted_room_driver_runtime.py@@ -436,7 +436,6 @@ def test_runtime_uses_unique_process_generation(db: Path):second = _runtime(db, FakeSessionRPC())assert first.process_generation != second.process_generation- assert len(first.process_generation) == 32@pytest.mark.parametrize("value", [0, True])@@ -445,100 +444,8 @@ def test_room_concurrency_bound_must_be_a_positive_integer(db: Path, value):_runtime(db, FakeSessionRPC(), max_concurrent_rooms=value)-def test_waiting_room_does_not_block_an_independent_local_room(tmp_path: Path):- db = tmp_path / "state.db"- bindings = [- HostedRoomBinding("room-waiting", "gateway-a", 1),- HostedRoomBinding("room-healthy", "gateway-a", 1),- ]- identities = [- state.TaskIdentity("room-waiting", "task-waiting", "thread-a", "turn-a"),- state.TaskIdentity("room-healthy", "task-healthy", "thread-b", "turn-b"),- ]- profiles = ["profile-waiting", "profile-healthy"]- for binding, identity, profile in zip(bindings, identities, profiles):- hosted_rooms.create_room(- db,- room_id=binding.room_id,- name=binding.room_id,- members=[{"profile": profile, "handle": profile}],- authority_gateway_id=binding.gateway_id,- now=time.time(),- )- state.admit_task(- db,- identity,- payload={- "target_profile": profile,- "prompt": f"Run {binding.room_id}.",- "source_event_seq": 1,- },- clock=time.time,- )- rpc = SelectiveCompletionRPC(waiting_profiles={"profile-waiting"})- runtime = HostedRoomRuntime(- db_path=db,- rooms=bindings,- rpc=rpc,- turn_lock=RecordingTurnLocks(),- lease_ttl_seconds=0.4,- poll_interval_seconds=0.01,- max_concurrent_rooms=2,- )- runtime.start()- _wait_for(lambda: state.get_task(db, identities[1])["status"] == "settled")- _wait_for(lambda: state.get_task(db, identities[0])["status"] == "running")- assert state.get_task(db, identities[0])["status"] == "running"- _wait_for(lambda: len(runtime.status()["current_tasks"]) == 1)- assert len(runtime.status()["current_tasks"]) == 1- assert runtime.stop(timeout=5.0)---def test_rotated_bounded_scheduler_eventually_runs_later_room(tmp_path: Path):- db = tmp_path / "state.db"- bindings = [- HostedRoomBinding(f"room-{index}", "gateway-a", 1) for index in range(1, 4)- ]- for binding in bindings:- hosted_rooms.create_room(- db,- room_id=binding.room_id,- name=binding.room_id,- members=[{"profile": PROFILE, "handle": PROFILE}],- authority_gateway_id=binding.gateway_id,- now=time.time(),- )- identity = state.TaskIdentity(- "room-3",- "task-room-3",- "thread-room-3",- "turn-room-3",- )- state.admit_task(- db,- identity,- payload={- "target_profile": PROFILE,- "prompt": "Run the later room.",- "source_event_seq": 1,- },- clock=time.time,- )- runtime = HostedRoomRuntime(- db_path=db,- rooms=bindings,- rpc=FakeSessionRPC(),- turn_lock=RecordingTurnLocks(),- lease_ttl_seconds=0.4,- poll_interval_seconds=0.01,- max_concurrent_rooms=2,- )-- runtime.start()- _wait_for(lambda: state.get_task(db, identity)["status"] == "settled")- assert runtime.stop(timeout=5.0)def test_queued_task_routes_profile_and_credentials_without_overrides(db: Path):@@ -1056,13 +963,9 @@ def test_turn_deadline_stops_exact_attempt_and_publishes_durable_failure(db: Patassert runtime.stop(timeout=5.0)failed = state.get_task(db, identity)- assert failed["result"] == {- "error": (- "This Group Chat turn exceeded its configured time limit and was stopped."- ),- "reason_code": "turn_deadline_exceeded",- "timeout_seconds": 0.05,- }+ assert failed["result"]["reason_code"] == "turn_deadline_exceeded"+ assert failed["result"]["timeout_seconds"] == 0.05+ assert failed["result"]["error"]assert failed["cancel_id"] == "deadline:1"assert [call for call in rpc.calls if call[0] == "interrupt"]assert [task["status"] for task in published] == ["failed"]@@ -2078,7 +1981,9 @@ def test_profile_turn_lock_covers_resolve_submit_and_terminal_observation(db: Pa_wait_for(lambda: state.get_task(db, identity)["status"] == "settled")assert runtime.stop(timeout=5.0)- assert locks.events == [("lock-enter", PROFILE), ("lock-exit", PROFILE)]+ # Balanced enter/exit pairs on the task's profile only (a loaded runner may run extra cycles).+ assert locks.events and all(profile == PROFILE for _event, profile in locks.events)+ assert locks.events.count(("lock-enter", PROFILE)) == locks.events.count(("lock-exit", PROFILE))methods = [method for method, _params in rpc.calls]assert methods.index("resolve_exact") < methods.index("submit")assert methods.index("submit") < methods.index("complete")diff --git a/tests/tui_gateway/test_hosted_room_prompt_fence.py b/tests/tui_gateway/test_hosted_room_prompt_fence.pyindex 11c1ddb5194..9ad2c3ece3f 100644--- a/tests/tui_gateway/test_hosted_room_prompt_fence.py+++ b/tests/tui_gateway/test_hosted_room_prompt_fence.py@@ -48,7 +48,6 @@ def test_direct_prompt_to_hosted_group_session_is_rejected(tmp_path, monkeypatch)assert result["error"]["code"] == 4122- assert "managed by its gateway" in result["error"]["message"]def test_direct_prompt_to_non_hosted_group_reaches_normal_admission(@@ -137,7 +136,6 @@ def test_direct_prompt_to_peer_reserved_group_is_rejected_until_revoke({"session_id": "session-1", "text": "continue"},)assert rejected["error"]["code"] == 4122- assert "home host" in rejected["error"]["message"]hosted_rooms.revoke_room_grant_scope(hosted_rooms.default_db_path(),@@ -178,9 +176,6 @@ def test_direct_prompt_is_refused_when_room_authority_cannot_be_verified()assert result["error"]["code"] == 5122- assert result["error"]["message"] == (- "Could not verify this group. Try again after the gateway recovers."- )def test_contended_ownership_probe_fails_quickly_without_blocking_socket(diff --git a/tests/tui_gateway/test_hosted_room_service.py b/tests/tui_gateway/test_hosted_room_service.pyindex 38a5390703a..cec66d09e01 100644--- a/tests/tui_gateway/test_hosted_room_service.py+++ b/tests/tui_gateway/test_hosted_room_service.py@@ -706,17 +706,6 @@ def test_thread_transcript_prunes_committed_message_and_settlement_together()-def test_service_uses_low_idle_poll_with_immediate_wakeup(tmp_path: Path):- service = HostedRoomService(_server(), db_path=tmp_path / "state.db")-- assert service.runtime.poll_interval_seconds == 5.0- assert service.runtime.active_poll_interval_seconds == 0.25- assert service.runtime.turn_timeout_seconds == 1830.0- service.runtime._wake.clear()- service.wakeup()- assert service.runtime._wake.is_set()--def test_service_derives_room_deadline_from_agent_timeout(tmp_path: Path, monkeypatch):monkeypatch.setenv("HERMES_AGENT_TIMEOUT", "90")diff --git a/tests/tui_gateway/test_hud_surface_note.py b/tests/tui_gateway/test_hud_surface_note.pyindex 029664b351d..1ddcd9e1abd 100644--- a/tests/tui_gateway/test_hud_surface_note.py+++ b/tests/tui_gateway/test_hud_surface_note.py@@ -22,17 +22,6 @@ from tui_gateway import serverFULL_KIT = {"read_window_below", "computer_use", "browser_navigate"}-def _tool_def(name: str) -> dict:- return {- "type": "function",- "function": {- "name": name,- "description": name,- "parameters": {"type": "object", "properties": {}},- },- }--def _session(*, tools=FULL_KIT, **extra):return {"agent": types.SimpleNamespace(valid_tool_names=set(tools)),@@ -50,12 +39,6 @@ def _session(*, tools=FULL_KIT, **extra):class TestNoteContents:"""Every tool the note names has to be one this agent actually has."""- def test_points_at_the_window_below_and_at_working_in_it(self):- note = hud_surface_note(FULL_KIT)-- assert "read_window_below" in note- assert "computer_use" in note- assert "browser_navigate" in notedef test_no_note_at_all_without_the_tool_it_rests_on(self):assert hud_surface_note({"computer_use", "browser_navigate"}) == ""@@ -93,39 +76,6 @@ class TestTurnRouting:assert server._hud_surface_note(session) == ""- def test_note_survives_tool_search_when_mcp_tools_are_present(self):- """valid_tool_names is the post-assembly list. MCP tools used to hide- read_window_below there, so a HUD turn got no note at all."""- from tools.registry import discover_builtin_tools, registry- from tools.tool_search import ToolSearchConfig, assemble_tool_defs-- discover_builtin_tools()- mcp_name = "mcp_hud_surface_probe"- registry.register(- name=mcp_name,- handler=lambda args, **kw: "{}",- schema=_tool_def(mcp_name)["function"],- toolset="mcp-hud-surface-probe",- )-- assembled = assemble_tool_defs(- [_tool_def(name) for name in (*FULL_KIT, mcp_name)],- context_length=200_000,- config=ToolSearchConfig.from_raw({"enabled": "on"}),- )- names = {td["function"]["name"] for td in assembled.tool_defs}-- assert assembled.activated- assert mcp_name not in names- # Production computes the note from agent.valid_tool_names — the- # GRANTED set — not from the visible post-assembly schemas. Under- # #97979 the HUD kit (read_window_below, computer_use) is deferred- # behind the bridge yet still granted/callable, so the note must- # survive assembly unchanged.- assert server._hud_surface_note(_session(tools=FULL_KIT, client_surface="hud")) == (- hud_surface_note(FULL_KIT)- )-class TestPrepending:"""Notes ride the model input; the persisted prompt stays what was typed."""diff --git a/tests/tui_gateway/test_image_ref_message.py b/tests/tui_gateway/test_image_ref_message.pyindex 4a1cf95d812..231c8a4094e 100644--- a/tests/tui_gateway/test_image_ref_message.py+++ b/tests/tui_gateway/test_image_ref_message.py@@ -9,7 +9,6 @@ analyzes them in-loop with ``vision_analyze`` (the same shape as the``@folder:`` path, which was always fast)."""-import timefrom unittest.mock import patchimport pytest@@ -38,19 +37,15 @@ def test_never_calls_vision_on_submit_path(img):assert "vision_analyze" in out-def test_returns_instantly_for_many_images(tmp_path):- """No per-image network round-trips: 20 images in well under a second."""+def test_every_attached_image_is_referenced(tmp_path):paths = []for i in range(20):p = tmp_path / f"img{i}.png"p.write_bytes(b"\x89PNG\r\n\x1a\n fake")paths.append(str(p))- start = time.monotonic()out = _build_image_ref_message("caption", paths)- elapsed = time.monotonic() - start- assert elapsed < 1.0for p in paths:assert p in out@@ -60,19 +55,3 @@ def test_missing_paths_skipped(tmp_path, img):out = _build_image_ref_message("hi", [str(gone), str(img)])assert str(gone) not in outassert str(img) in out---def test_text_preserved_and_trails_refs(img):- out = _build_image_ref_message("my caption", [str(img)])- assert out.index("vision_analyze") < out.index("my caption")---def test_no_text_defaults_to_question_when_no_valid_images(tmp_path):- out = _build_image_ref_message("", [str(tmp_path / "missing.png")])- assert out == "What do you see in this image?"---def test_no_text_with_image_yields_refs_only(img):- out = _build_image_ref_message("", [str(img)])- assert str(img) in out- assert out.strip().startswith("[The user attached an image")diff --git a/tests/tui_gateway/test_inline_rpc_gil_starvation.py b/tests/tui_gateway/test_inline_rpc_gil_starvation.pyindex 183ab49a8cc..ba71d61d2aa 100644--- a/tests/tui_gateway/test_inline_rpc_gil_starvation.py+++ b/tests/tui_gateway/test_inline_rpc_gil_starvation.py@@ -14,8 +14,6 @@ The fix routes all frontend-polled RPCs through ``_LONG_HANDLERS`` sothe WS read loop is never blocked."""-import io-import jsonimport sysimport threadingimport time@@ -59,41 +57,6 @@ def server():__import__("tui_gateway.server_requests", fromlist=["x"]).reset_for_tests()-def capture(server):- """Redirect server's real stdout to a StringIO and return (server, buf)."""- buf = io.StringIO()- server._real_stdout = buf- return server, buf---# ─── RPCs that must be in _LONG_HANDLERS ────────────────────────────────--# These are polled by the Desktop frontend. Before the fix they ran inline,-# blocking the WS read loop under GIL pressure and causing false "needs setup"-# (#50005). Each one does I/O (DB query, file read, network) that can take-# seconds when the GIL is contended by concurrent agent turns.--FRONTEND_POLLED_RPCS = [- "session.active_list", # live-session rehydrate — in-memory registry- "session.list", # loads session list — SQLite query- "pet.info", # petdex poll — file/network read- "process.list", # background process status — process registry scan- "setup.runtime_check", # runtime readiness — resolve_runtime_provider() I/O- "setup.status", # provider configured check — config/credential scan-]--[email protected]("method", FRONTEND_POLLED_RPCS)-def test_frontend_polled_rpc_is_pool_routed(server, method):- """Every frontend-polled RPC must be in _LONG_HANDLERS so dispatch()- returns immediately and the WS read loop is not blocked (#50005)."""- assert method in server._LONG_HANDLERS, (- f"{method!r} is not in _LONG_HANDLERS — it will block the WS read "- f"loop under GIL pressure, causing false 'needs setup' (#50005)."- )--def test_dispatch_inline_rpc_does_not_block_under_gil_pressure(server):"""A slow inline-turned-long handler must not prevent a concurrent fasthandler from completing. This is the core invariant: dispatch() must@@ -127,15 +90,3 @@ def test_dispatch_inline_rpc_does_not_block_under_gil_pressure(server):)released.set()---def test_rpc_pool_workers_supports_concurrent_long_handlers(server):- """The RPC thread pool must have enough workers to handle concurrent- long handlers without queueing. With 6+ frontend-polled RPCs added to- _LONG_HANDLERS, the default 4 workers can be exhausted when multiple- agent turns are running. The pool must be at least 8."""- assert server._rpc_pool_workers >= 8, (- f"_rpc_pool_workers is {server._rpc_pool_workers}, expected >= 8. "- f"Frontend-polled RPCs added to _LONG_HANDLERS need more workers to "- f"avoid queueing under multi-agent load (#50005)."- )diff --git a/tests/tui_gateway/test_interim_assistant_callback.py b/tests/tui_gateway/test_interim_assistant_callback.pyindex ab02a423360..1096d28f8b8 100644--- a/tests/tui_gateway/test_interim_assistant_callback.py+++ b/tests/tui_gateway/test_interim_assistant_callback.py@@ -9,13 +9,6 @@ from __future__ import annotationsfrom unittest.mock import patch-def test_load_interim_assistant_messages_defaults_true():- from tui_gateway.server import _load_interim_assistant_messages-- with patch("tui_gateway.server._load_cfg", return_value={}):- assert _load_interim_assistant_messages() is True--def test_agent_cbs_includes_interim_callback_when_enabled():"""_agent_cbs() includes interim_assistant_callback when the config is on.@@ -48,5 +41,3 @@ def test_agent_cbs_includes_interim_callback_when_enabled():assert emitted[0][1] == "test-session"assert emitted[0][2]["text"] == "hello world"assert emitted[0][2]["already_streamed"] is True--diff --git a/tests/tui_gateway/test_iso_certify_seam.py b/tests/tui_gateway/test_iso_certify_seam.pyindex e4425ce501b..e608f4e1b90 100644--- a/tests/tui_gateway/test_iso_certify_seam.py+++ b/tests/tui_gateway/test_iso_certify_seam.py@@ -1,54 +1,16 @@-"""Tests for the AC-4 isolation certify seam + harness helpers.--The synthetic heavy-turn agent (``tui_gateway/synthetic_turn.py``) is a test-seam: dead unless ``HERMES_ISO_CERTIFY_SYNTH_TURN=1``. These tests pin (a) the-dead-when-unset contract, (b) that an armed turn holds for the requested wall-duration and streams deltas, (c) that interrupt aborts it promptly, and (d) the-harness percentile math.+"""The AC-4 synthetic heavy-turn agent (``tui_gateway/synthetic_turn.py``) is a+test seam: it must stay dead unless ``HERMES_ISO_CERTIFY_SYNTH_TURN=1``."""from __future__ import annotations-import importlib.util-import threading-import time-from pathlib import Path--import pytest-from tui_gateway.synthetic_turn import (- SyntheticHeavyAgent,maybe_build_synthetic_agent,synth_turn_armed,)-REPO_ROOT = Path(__file__).resolve().parents[2]---def _load_iso_certify():- path = REPO_ROOT / "scripts" / "iso-certify.py"- spec = importlib.util.spec_from_file_location("iso_certify", path)- assert spec and spec.loader- mod = importlib.util.module_from_spec(spec)- spec.loader.exec_module(mod)- return mod-def test_synth_seam_dead_when_env_unset(monkeypatch):monkeypatch.delenv("HERMES_ISO_CERTIFY_SYNTH_TURN", raising=False)assert synth_turn_armed() is Falseassert maybe_build_synthetic_agent("sid") is None---def test_harness_percentile_and_guard():- iso = _load_iso_certify()- assert iso.percentile([], 99) == 0.0- assert iso.percentile([5.0], 99) == 5.0- vals = [float(i) for i in range(1, 101)] # 1..100- assert 98.0 <= iso.percentile(vals, 99) <= 100.0- assert iso.percentile(vals, 50) == pytest.approx(50.5, abs=0.6)- # The empty-timeline INCONCLUSIVE floor: too few probe samples never PASSes.- assert iso.probe_thread_samples_ok([1.0, 2.0], [1.0, 2.0, 3.0]) is False- assert iso.probe_thread_samples_ok([1.0, 2.0, 3.0], [1.0, 2.0, 3.0]) is True--diff --git a/tests/tui_gateway/test_isolated_orphan_activity.py b/tests/tui_gateway/test_isolated_orphan_activity.pyindex fa130e011b5..87e413ed21e 100644--- a/tests/tui_gateway/test_isolated_orphan_activity.py+++ b/tests/tui_gateway/test_isolated_orphan_activity.py@@ -1,25 +1,11 @@"""Detached Desktop/TUI turns use child-owned activity, not process heartbeats."""-from pathlib import Path-import sysimport threadingimport timeimport pytestfrom tui_gateway import server-from tui_gateway.host_supervisor import HostSupervisor---class _Timer:- def __init__(self, delay, callback):- self.delay, self.callback = delay, callback-- def start(self):- pass-- def cancel(self):- passdef _session(sid):@@ -29,96 +15,6 @@ def _session(sid):attached_images=[], cols=80, source="desktop", inflight_turn=None)[email protected]("mode", ["fresh", "stale", "missing", "previous"])-def test_real_child_detached_turn_activity(tmp_path, monkeypatch, mode):- """Real supervisor pipes, child admission/turn thread, bridge and orphan timer.-- Only the agent/provider and environment-heavy UI side effects are stubbed in- the child. Its activity writer and snapshot contract are the production ones.- """- sid = "detached-turn"- session = _session(sid)- forwarded = []- monkeypatch.setattr(server, "_sessions", {sid: session})- monkeypatch.setattr(server, "_pending_ws_reaps", {})- monkeypatch.setattr(server, "write_json", lambda msg: forwarded.append(msg) or True)- monkeypatch.setattr(server, "_load_dashboard_process_isolation_config", lambda: {"turn_isolation": True})- monkeypatch.setattr(server, "_WS_ORPHAN_ACTIVITY_STALE_S", 30.0)- monkeypatch.setattr(server, "_WS_ORPHAN_REAP_GRACE_S", 20.0)- monkeypatch.setattr(server, "_session_has_active_delegations", lambda *args: False)- monkeypatch.setattr(server, "_session_cwd", lambda s: str(tmp_path))- home = tmp_path / "home"- home.mkdir()- supervisor = HostSupervisor(- argv=[sys.executable, str(Path(__file__).resolve()), mode, str(tmp_path)],- registry_path=tmp_path / "host.json", env={"HERMES_HOME": str(home)},- expected_hermes_home=str(home), rpc_sink=server._relay_compute_host_rpc,- heartbeat_secs=1, autostart=False)- monkeypatch.setattr(server, "_get_compute_host_supervisor", lambda *args: supervisor)- try:- response = server._submit_prompt_to_compute_host("request", sid, session, "work")- assert response["result"]["turn_isolation"] is True- deadline = time.monotonic() + 12- while not (tmp_path / "provider-started").exists() and time.monotonic() < deadline:- time.sleep(0.02)- assert (tmp_path / "provider-started").exists(), supervisor._stderr_tail- # Give the actual child-to-parent sampler a bounded opportunity to arrive.- deadline = time.monotonic() + 3- while not server._ws_orphan_turn_activity_is_fresh(session) and time.monotonic() < deadline:- time.sleep(0.02)- assert supervisor.is_running()- assert session["agent"] is None- assert server._ws_orphan_turn_activity_is_fresh(session) is (mode == "fresh")- monkeypatch.setattr(server.threading, "Timer", _Timer)- server._schedule_ws_orphan_reap(sid)- server._pending_ws_reaps[sid].callback()- assert bool(session.get("_client_gone_interrupt_requested")) is (mode != "fresh")- assert server._pending_ws_reaps[sid].delay == (- 20.0 if mode == "fresh" else server._WS_ORPHAN_INTERRUPT_REAP_POLL_S)- assert not any(m.get("method") == "compute_host.activity" for m in forwarded)- if mode != "fresh":- deadline = time.monotonic() + 5- while session["running"] and time.monotonic() < deadline:- time.sleep(0.02)- assert not session["running"], "stale child must receive and settle the real interrupt"- if mode == "fresh":- old_token = session["_compute_host_turn_id"]- old_request = next(iter(supervisor._pending_turns))- (tmp_path / "release").touch()- deadline = time.monotonic() + 5- while session["running"] and time.monotonic() < deadline:- time.sleep(0.02)- assert not session["running"]- assert "_compute_host_activity_ns" not in session- (tmp_path / "release").unlink()- (tmp_path / "provider-started").unlink()- session["running"] = True- # Same sid and caller rid, same child/agent, but NO new activity.- server._submit_prompt_to_compute_host("request", sid, session, "next")- assert session["_compute_host_turn_id"] != old_token- new_token = session["_compute_host_turn_id"]- # A delayed terminal frame cannot resolve the new caller-rid reuse.- supervisor._handle_host_frame({"type": "turn.end", "sid": sid, "request_id": old_request})- assert session["running"]- assert session["_compute_host_turn_id"] == new_token- deadline = time.monotonic() + 5- while not (tmp_path / "provider-started").exists() and time.monotonic() < deadline:- time.sleep(0.02)- assert (tmp_path / "provider-started").exists()- # Also replay a delayed sample from the previous dispatch.- server._relay_compute_host_rpc({"method": "compute_host.activity", "params": {- "session_id": sid, "turn_id": old_token, "activity_ns": time.perf_counter_ns()}})- deadline = time.monotonic() + 3- while "_compute_host_activity_ns" not in session and time.monotonic() < deadline:- time.sleep(0.02)- assert "_compute_host_activity_ns" in session- assert not server._ws_orphan_turn_activity_is_fresh(session)- server._pending_ws_reaps[sid].callback()- assert session["_client_gone_interrupt_requested"]- finally:- supervisor.shutdown()--@pytest.mark.parametrize("change", ["none", "other-session", "old-turn", "not-running", "stale", "missing"])def test_activity_relay_is_fenced_and_ages(monkeypatch, change):session = _session("session")@@ -144,64 +40,3 @@ def test_activity_relay_is_fenced_and_ages(monkeypatch, change):monkeypatch.setattr(server.time, "perf_counter_ns", lambda: params["activity_ns"] + 31_000_000_000)server._relay_compute_host_rpc({"method": "compute_host.activity", "params": params})assert not server._ws_orphan_turn_activity_is_fresh(session)---def _run_child(mode, directory):- import socket- from agent.activity_tracking import ActivityTrackingMixin- from agent.session_activity import build_activity_snapshot- from tui_gateway.compute_host import run_host-- def no_network(*args, **kwargs):- raise AssertionError("test child must not contact a provider")- socket.socket.connect = no_network-- class Agent(ActivityTrackingMixin):- def __init__(self, sid):- self.session_id = sid- self._interrupt = threading.Event()- if mode == "previous":- self._touch_activity("previous turn")-- def get_activity_summary(self):- return build_activity_snapshot(last_activity_at=getattr(self, "_last_activity_ts", None),- last_activity_description="test provider")-- def clear_interrupt(self):- self._interrupt.clear()-- def interrupt(self, **kwargs):- self._interrupt.set()-- def run_conversation(self, *args, **kwargs):- Path(directory, "provider-started").touch()- deadline = time.monotonic() + 20- while not self._interrupt.wait(0.05) and time.monotonic() < deadline:- if Path(directory, "release").exists():- break- if mode == "fresh" and args[0] != "next":- self._touch_activity("provider wait")- elif mode == "stale":- self._last_activity_ts = time.time() - 3600- return {"final_response": "done", "interrupted": self._interrupt.is_set()}-- def init(sid, key, agent, history, **kwargs):- s = _session(sid)- s.update(agent=agent, running=False, transport=None,- image_counter=0, slash_worker=None, show_reasoning=False,- tool_progress_mode="all")- server._sessions[sid] = s-- server._make_agent = lambda sid, *a, **kw: Agent(sid)- server._init_session = init- server._wire_callbacks = lambda *a: None- server._sync_agent_model_with_config = lambda *a: None- server._register_session_cwd = lambda *a: None- server._tts_stream_begin = lambda: None- server._sync_session_key_after_compress = lambda *a, **kw: None- server._get_usage = lambda *a: {}- run_host(stdout=sys.__stdout__)---if __name__ == "__main__":- _run_child(sys.argv[1], sys.argv[2])diff --git a/tests/tui_gateway/test_kanban_notify_poller.py b/tests/tui_gateway/test_kanban_notify_poller.pyindex 7600aa50f38..2a8692f6f06 100644--- a/tests/tui_gateway/test_kanban_notify_poller.py+++ b/tests/tui_gateway/test_kanban_notify_poller.py@@ -243,21 +243,6 @@ class TestFormatKanbanEventText:ev = SimpleNamespace(kind=kind, payload={})assert _format_kanban_event_text(self.SUB, self.TASK, ev, "main") is None- def test_blocked_includes_reason(self):- ev = SimpleNamespace(kind="blocked", payload={"reason": "needs creds"})- text = _format_kanban_event_text(self.SUB, self.TASK, ev, "main")- assert "t_abc123" in text- assert "blocked" in text- assert "needs creds" in text- assert "[main]" in text- assert "@worker" in text-- def test_completed_prefers_payload_summary(self):- ev = SimpleNamespace(kind="completed", payload={"summary": "first line\nsecond"})- text = _format_kanban_event_text(self.SUB, self.TASK, ev, "")- assert "done" in text- assert "first line" in text- assert "second" not in textdef test_timed_out_with_bad_payload_does_not_raise(self):ev = SimpleNamespace(kind="timed_out", payload={"limit_seconds": "not-a-number"})diff --git a/tests/tui_gateway/test_lazy_session_regressions.py b/tests/tui_gateway/test_lazy_session_regressions.pyindex 3ffbe551910..fdf8eaee1a9 100644--- a/tests/tui_gateway/test_lazy_session_regressions.py+++ b/tests/tui_gateway/test_lazy_session_regressions.py@@ -107,81 +107,6 @@ class TestFinalizeSessionUsesAgentSessionId:# Bug #20001: _sync_session_key_after_compress post-run_conversation# ===========================================================================-class TestSyncSessionKeyAfterAutoCompress:- """When auto-compression fires inside run_conversation(), the post-turn- code in _run_prompt_submit must call _sync_session_key_after_compress- to update session_key for downstream consumers (title, goals, etc.)."""-- def test_session_key_synced_after_run_conversation_with_compression(self, monkeypatch):- """Simulate: run_conversation() internally compresses and rotates- agent.session_id. After it returns, session['session_key'] must match."""- from tui_gateway import server-- class _CompressingAgent:- """Agent that simulates compression-driven session_id rotation."""- def __init__(self):- self.session_id = "pre-compress-key"- self._cached_system_prompt = ""-- def run_conversation(self, prompt, conversation_history=None, stream_callback=None, **_kwargs):- # Simulate what _compress_context does: rotate session_id- self.session_id = "post-compress-key"- return {- "final_response": "done",- "messages": [- {"role": "user", "content": prompt},- {"role": "assistant", "content": "done"},- ],- }-- agent = _CompressingAgent()- session = _tui_session(agent=agent, session_key="pre-compress-key")-- # Track if _sync_session_key_after_compress was called- sync_calls = []- original_sync = server._sync_session_key_after_compress-- def _tracking_sync(sid, sess, **kwargs):- sync_calls.append((sid, sess.get("session_key")))- # Just update the key directly (skip approval routing etc.)- new_id = getattr(sess.get("agent"), "session_id", None) or ""- if new_id and new_id != sess.get("session_key"):- sess["session_key"] = new_id-- monkeypatch.setattr(server, "_sync_session_key_after_compress", _tracking_sync)- monkeypatch.setattr(server, "_emit", lambda *a, **kw: None)- monkeypatch.setattr(server, "make_stream_renderer", lambda cols: None)- monkeypatch.setattr(server, "render_message", lambda raw, cols: None)-- # Use _ImmediateThread pattern to run synchronously- class _ImmediateThread:- def __init__(self, target=None, daemon=None, **kw):- self._target = target- def start(self):- self._target()-- server._sessions["test-sid"] = session- monkeypatch.setattr(server.threading, "Thread", _ImmediateThread)-- try:- server.handle_request({- "id": "1",- "method": "prompt.submit",- "params": {"session_id": "test-sid", "text": "hello"},- })-- # Sync should have been called- assert len(sync_calls) > 0, (- "_sync_session_key_after_compress must be called after run_conversation "- "to pick up compression-driven session_id rotation"- )-- # session_key should now match agent.session_id- assert session["session_key"] == "post-compress-key", (- "session_key must be updated to match agent.session_id after compression"- )- finally:- server._sessions.pop("test-sid", None)# ===========================================================================@@ -297,7 +222,7 @@ class TestGatewaySurfacesNullResponse:# Plain outcome plus the way forward; the raw provider text stays in the log.assert "500 Internal Server Error" not in response- assert "/retry" in response and "/new" in response+ assert responsedef test_silent_drop_after_stop_surfaces_hint(self):@@ -322,8 +247,6 @@ class TestGatewaySurfacesNullResponse:)assert result, "Silent-drop turn must surface a user-facing hint"- lowered = result.lower()- assert "send it again" in lowered or "try again" in lowered# ===========================================================================diff --git a/tests/tui_gateway/test_loop_command.py b/tests/tui_gateway/test_loop_command.pyindex ea4730687ac..ae7b25cd357 100644--- a/tests/tui_gateway/test_loop_command.py+++ b/tests/tui_gateway/test_loop_command.py@@ -72,11 +72,6 @@ def _call(server, method, **params):# ── command.dispatch /loop ────────────────────────────────────────────-def test_loop_bare_shows_status_when_none_set(server, session):- sid, _, _ = session- r = _call(server, "command.dispatch", name="loop", arg="", session_id=sid)- assert r["result"]["type"] == "exec"- assert "No loop set" in r["result"]["output"]def test_loop_set_persists(server, session):@@ -84,7 +79,6 @@ def test_loop_set_persists(server, session):r = _call(server, "command.dispatch", name="loop", arg="5m check the deploy", session_id=sid)result = r["result"]assert result["type"] == "exec"- assert "Loop set" in result["output"]from hermes_cli.loops import LoopManager@@ -95,10 +89,6 @@ def test_loop_set_persists(server, session):assert mgr.state.interval_seconds == 300.0-def test_loop_proactive_alias_resolves(server, session):- sid, _, _ = session- r = _call(server, "command.dispatch", name="proactive", arg="5m ping", session_id=sid)- assert "Loop set" in r["result"]["output"]def test_loop_pause_resume_stop(server, session):@@ -147,7 +137,6 @@ def test_tui_tick_fires_when_idle_and_due(server, session):server._maybe_fire_tui_loop_tick(sid, s)assert "poll the build" in fired.get("text", "")- assert "[/loop wakeup #1" in fired["text"]# Session claimed for the wakeup turn.assert s["running"] is Truediff --git a/tests/tui_gateway/test_make_agent_provider.py b/tests/tui_gateway/test_make_agent_provider.pyindex bcbe25711ff..37a5defc0c2 100644--- a/tests/tui_gateway/test_make_agent_provider.py+++ b/tests/tui_gateway/test_make_agent_provider.py@@ -6,58 +6,9 @@ provider/base_url/api_key empty in AIAgent, causing HTTP 404."""import os-from unittest.mock import MagicMock, patch+from unittest.mock import patch-def test_make_agent_passes_resolved_provider():- """_make_agent forwards provider/base_url/api_key/api_mode from- resolve_runtime_provider to AIAgent."""-- fake_runtime = {- "provider": "anthropic",- "base_url": "https://api.anthropic.com",- "api_key": "sk-test-key",- "api_mode": "anthropic_messages",- "command": None,- "args": None,- "credential_pool": None,- }-- fake_cfg = {- "model": {"default": "claude-opus-4-6", "provider": "anthropic"},- "agent": {"system_prompt": "test"},- }-- with (- patch("tui_gateway.server._load_cfg", return_value=fake_cfg),- patch("tui_gateway.server._get_db", return_value=MagicMock()),- patch("tui_gateway.server._load_tool_progress_mode", return_value="compact"),- patch("tui_gateway.server._load_reasoning_config", return_value=None),- patch("tui_gateway.server._load_service_tier", return_value=None),- patch("tui_gateway.server._load_enabled_toolsets", return_value=None),- patch(- "hermes_cli.runtime_provider.resolve_runtime_provider",- return_value=fake_runtime,- ) as mock_resolve,- patch("run_agent.AIAgent") as mock_agent,- ):-- from tui_gateway.server import _make_agent-- _make_agent("sid-1", "key-1")-- # target_model comes from _resolve_startup_runtime() which reads- # _load_cfg(). Due to module-level caching in tui_gateway.server,- # the patched config may not take effect when the module was already- # imported by an earlier test. Assert the stable part of the call.- mock_resolve.assert_called_once()- assert mock_resolve.call_args.kwargs.get("requested") is None-- call_kwargs = mock_agent.call_args- assert call_kwargs.kwargs["provider"] == "anthropic"- assert call_kwargs.kwargs["base_url"] == "https://api.anthropic.com"- assert call_kwargs.kwargs["api_key"] == "sk-test-key"- assert call_kwargs.kwargs["api_mode"] == "anthropic_messages"def test_probe_config_health_flags_null_sections():diff --git a/tests/tui_gateway/test_mcp_late_refresh_thread_owner.py b/tests/tui_gateway/test_mcp_late_refresh_thread_owner.pyindex 79aac06d103..2c98ec0d613 100644--- a/tests/tui_gateway/test_mcp_late_refresh_thread_owner.py+++ b/tests/tui_gateway/test_mcp_late_refresh_thread_owner.py@@ -69,10 +69,6 @@ def test_entry_in_flight_sees_startup_thread(clean_discovery_globals):assert entry.mcp_discovery_in_flight() is False-def test_no_mcp_threads_not_in_flight(clean_discovery_globals):- """No discovery anywhere → not in flight, join reports done immediately."""- assert entry.mcp_discovery_in_flight() is False- assert entry.join_mcp_discovery(timeout=0.1) is Truedef test_startup_module_exposes_in_flight_helpers(clean_discovery_globals):diff --git a/tests/tui_gateway/test_mcp_oauth_client_callback.py b/tests/tui_gateway/test_mcp_oauth_client_callback.pyindex ae45e1ead35..57ef8b968eb 100644--- a/tests/tui_gateway/test_mcp_oauth_client_callback.py+++ b/tests/tui_gateway/test_mcp_oauth_client_callback.py@@ -12,7 +12,6 @@ Covers the three seams added for remote Desktop backends:rejected, replay rejected, unknown session rejected)."""-import threadingimport pytest@@ -140,7 +139,6 @@ def test_start_flow_client_redirect_skips_gateway_listener(monkeypatch):monkeypatch.setenv("SSH_CLIENT", "192.0.2.1 12345 22")attempt = mcp_oauth.start("cardy")assert attempt.flow.redirect_uri.startswith("http://127.0.0.1:")- assert "copy the full URL" in attempt.detailassert attempt.flow.flow_id in mcp_oauth_sessions._sessionsdeliver_callback_flow(attempt.flow.flow_id, "cardy", code="authcode", state="teststate123"diff --git a/tests/tui_gateway/test_model_switch_marker_role.py b/tests/tui_gateway/test_model_switch_marker_role.pyindex 9513efc20fd..23dcaeaf3a8 100644--- a/tests/tui_gateway/test_model_switch_marker_role.py+++ b/tests/tui_gateway/test_model_switch_marker_role.py@@ -9,9 +9,6 @@ sanitize/merge pass already coalesces consecutive user messages.from __future__ import annotations-import threading-from types import SimpleNamespace-from unittest.mock import MagicMockfrom tui_gateway.server import _append_model_switch_marker@@ -31,9 +28,6 @@ class TestAppendModelSwitchMarkerRole:)- def test_no_marker_for_none_session(self) -> None:- """None session should be a no-op."""- _append_model_switch_marker(None, model="gpt-4o", provider="openai")class TestModelSwitchMarkerDedup:@@ -57,14 +51,6 @@ class TestModelSwitchMarkerDedup:# The surviving marker is the last history entry.assert session["history"][-1] is markers[0]- def test_five_switches_leave_one_marker(self) -> None:- # Mirrors the issue's screenshot: 5 consecutive MoA preset switches.- session: dict = {"session_key": "s", "history": []}- for name in ("质量-非高峰", "省钱-非高峰", "代码编程-非高峰", "日常对话-非高峰", "智能-高峰"):- _append_model_switch_marker(session, model=name, provider="moa")- markers = self._markers(session)- assert len(markers) == 1- assert "智能-高峰" in markers[0]["content"]def test_dedup_preserves_real_conversation_turns(self) -> None:session: dict = {diff --git a/tests/tui_gateway/test_model_switch_reasoning_flag.py b/tests/tui_gateway/test_model_switch_reasoning_flag.pyindex 38706a02b44..f1fcfb27166 100644--- a/tests/tui_gateway/test_model_switch_reasoning_flag.py+++ b/tests/tui_gateway/test_model_switch_reasoning_flag.py@@ -60,5 +60,5 @@ def test_reasoning_flag_with_global_writes_config_and_drops_the_pin(_quiet_switcassert _quiet_switch["agent.reasoning_effort"] == "none"assert "create_reasoning_override" not in session- with pytest.raises(ValueError, match="--reasoning takes"):+ with pytest.raises(ValueError):server._apply_model_switch("sid", {"agent": _Agent()}, "new/model --reasoning turbo")diff --git a/tests/tui_gateway/test_personality_clobbers_system_prompt.py b/tests/tui_gateway/test_personality_clobbers_system_prompt.pyindex 36a99c1167d..086aed8495d 100644--- a/tests/tui_gateway/test_personality_clobbers_system_prompt.py+++ b/tests/tui_gateway/test_personality_clobbers_system_prompt.py@@ -103,25 +103,6 @@ def _run(home: str, session_id: str = ""):return resp-def test_personality_selection_preserves_manual_system_prompt(tmp_path, monkeypatch):- """Selecting a personality must NOT overwrite the manual agent.system_prompt."""- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- # Force the server module to pick up the temp home for config reads/writes.- monkeypatch.setattr(server, "_hermes_home", Path(tmp_path))- monkeypatch.setattr(server, "_cfg_path", None)- monkeypatch.setattr(server, "_cfg_cache", None)- _seed_config(str(tmp_path))-- resp = _run(str(tmp_path))-- assert resp["result"]["value"] == "personality_1", resp- # THE BUG: the manual system_prompt was overwritten by the personality.- saved = _read_saved_system_prompt(str(tmp_path))- assert saved == MANUAL_PROMPT, (- "agent.system_prompt was clobbered by the personality selection.\n"- f" expected (manual): {MANUAL_PROMPT!r}\n"- f" got (personality): {saved!r}"- )def test_switching_personality_leaves_no_stale_text(tmp_path, monkeypatch):diff --git a/tests/tui_gateway/test_pet_generate_rpc.py b/tests/tui_gateway/test_pet_generate_rpc.pydeleted file mode 100644index 77ec81eb11d..00000000000--- a/tests/tui_gateway/test_pet_generate_rpc.py+++ /dev/null@@ -1,64 +0,0 @@-"""Gateway RPC tests for pet generation (pet.generate / pet.hatch).--Image generation is mocked, so these assert the RPC contract + staging behavior-(draft tokens, data-URI previews, expiry, activation) without any API calls.-"""--from __future__ import annotations--import pytest--pytest.importorskip("PIL")-from PIL import Image # noqa: E402--from tui_gateway import server # noqa: E402---def _png(path):- Image.new("RGBA", (64, 64), (200, 80, 80, 255)).save(path)---def test_pet_generate_requires_prompt():- resp = server._methods["pet.generate"]("r1", {"prompt": " "})- assert "error" in resp---def _fake_drafts_factory(tmp_path):- def fake_drafts(prompt, *, n=4, style="auto", reference_images=None, provider=None, on_draft=None, is_cancelled=None):- paths = []- for i in range(n):- p = tmp_path / f"d{i}.png"- _png(p)- paths.append(p)- if on_draft is not None:- on_draft(i, p)- return paths-- return fake_drafts---def _fake_hatch_factory(captured):- """A hatch that registers a real local pet (so the preview payload populates)."""- import agent.pet.generate as gen- from agent.pet import store-- def fake_hatch(*, base_image, slug, display_name="", description="", concept="", style="auto", on_progress=None, provider=None, is_cancelled=None):- captured["base_image"] = str(base_image)- captured["slug"] = slug- pet = store.register_local_pet(- Image.new("RGBA", (192, 208), (10, 20, 30, 255)),- slug=slug,- display_name=display_name,- description=description,- )- return gen.HatchResult(- slug=pet.slug,- display_name=display_name or pet.display_name,- spritesheet=pet.spritesheet,- states=["idle", "wave"],- validation={"ok": True, "warnings": ["state 'jump' has no frames"]},- )-- return fake_hatch--diff --git a/tests/tui_gateway/test_ping_probe.py b/tests/tui_gateway/test_ping_probe.pyindex 514d42036e6..1870e13745f 100644--- a/tests/tui_gateway/test_ping_probe.py+++ b/tests/tui_gateway/test_ping_probe.py@@ -22,10 +22,3 @@ def test_ping_registered_and_answers_pong():assert res == {"pong": True}-def test_ping_ignores_params_and_returns_ok_envelope():- # The probe must be parameter-agnostic: the client sends {} but a stray- # future caller must not be able to make it fail.- envelope = srv._methods["ping"](7, {"anything": "value"})- assert envelope["jsonrpc"] == "2.0"- assert envelope["id"] == 7- assert envelope["result"] == {"pong": True}diff --git a/tests/tui_gateway/test_plugins_manage_install.py b/tests/tui_gateway/test_plugins_manage_install.pyindex 784ac5c3430..6471d6e11f4 100644--- a/tests/tui_gateway/test_plugins_manage_install.py+++ b/tests/tui_gateway/test_plugins_manage_install.py@@ -1,50 +1,10 @@"""Gateway plugins.manage install action."""-from types import SimpleNamespacefrom unittest.mock import patchfrom tui_gateway import server-def test_plugins_manage_install_success():- # The real ``dashboard_install_plugin`` ok payload, key for key. Under HERMES_TEST_ISOLATION the- # dispatcher validates the result against ``PluginsManageResult`` (extra=forbid), so a key the- # installer emits but the contract lacks fails here instead of only in the desktop's errors.log.- payload = {- "ok": True,- "plugin_name": "hello-world",- "warnings": [],- "python_dependencies": [],- "missing_env": [],- "after_install_path": None,- "enabled": True,- }- with patch(- "hermes_cli.plugins_cmd.dashboard_install_plugin",- return_value=payload,- ) as mock_install:- resp = server.handle_request(- {- "id": "1",- "method": "plugins.manage",- "params": {- "action": "install",- "repo": "owner/hello-world",- "force": True,- "enable": False,- },- }- )-- assert "result" in resp- assert resp["result"]["plugin_name"] == "hello-world"- mock_install.assert_called_once_with(- "owner/hello-world",- force=True,- enable=False,- catalog_name=None,- ref=None,- )def test_plugins_manage_install_missing_identifier():@@ -57,7 +17,6 @@ def test_plugins_manage_install_missing_identifier():)assert "error" in resp- assert "identifier" in resp["error"]["message"]def test_plugins_manage_install_failure():@@ -80,33 +39,6 @@ def test_plugins_manage_install_failure():assert "Git clone failed" in resp["error"]["message"]-def test_plugins_manage_install_catalog_name_only():- """A catalog pick needs no identifier — the backend resolves repo + pin."""- payload = {"ok": True, "plugin_name": "weather-plugin", "enabled": False}- with patch(- "hermes_cli.plugins_cmd.dashboard_install_plugin",- return_value=payload,- ) as mock_install:- resp = server.handle_request(- {- "id": "1",- "method": "plugins.manage",- "params": {- "action": "install",- "catalog_name": "weather-plugin",- "enable": False,- },- }- )-- assert "result" in resp- mock_install.assert_called_once_with(- "",- force=False,- enable=False,- catalog_name="weather-plugin",- ref=None,- )def test_plugins_manage_update_requires_catalog_sidecar(tmp_path, monkeypatch):@@ -126,7 +58,6 @@ def test_plugins_manage_update_requires_catalog_sidecar(tmp_path, monkeypatch):)assert "error" in resp- assert "not a catalog install" in resp["error"]["message"]def test_plugins_manage_list_reports_desktop_half(tmp_path):@@ -153,40 +84,3 @@ def test_plugins_manage_list_reports_desktop_half(tmp_path):assert by_name["snap"]["servers"] == []-def test_plugins_manage_list_reports_declared_server_snapshot(tmp_path):- plugin_dir = tmp_path / "example-plugin"- plugin_dir.mkdir()- package = SimpleNamespace(- manifest={- "extensions": {- "com.nousresearch.hermes": {- "servers": {"example-server": {}}- }- }- }- )- current = SimpleNamespace(state="missing_app", availability=object())- liveness = SimpleNamespace(- status=lambda _name: current,- describe=lambda _decl, _availability, _state: "Example App is not installed. Install Example App, then try again.",- )- rows = [("example-plugin", "1.0", "Example", "user", plugin_dir, "example-plugin")]- import_module = server._tools_mod-- with patch("hermes_cli.plugins_cmd._discover_all_plugins", return_value=rows), \- patch("hermes_cli.plugins_cmd._get_enabled_set", return_value=set()), \- patch("hermes_cli.plugins_cmd._get_disabled_set", return_value=set()), \- patch("hermes_cli.plugins_cmd._is_portable_plugin_dir", return_value=True), \- patch("hermes_cli.agent_plugins.load_agent_plugin", return_value=package), \- patch("hermes_platform.declaration.lookup", return_value=object()), \- patch("tools.mcp_tool_scope._resolve_server_key", return_value="example-plugin__example-server"), \- patch("hermes_cli.plugins_cmd_catalog.catalog_pins", return_value={}), \- patch("tui_gateway.server._tools_mod", wraps=import_module) as modules:- modules.side_effect = lambda name: liveness if name == "tools.mcp_liveness" else import_module(name)- resp = server.handle_request({"id": "1", "method": "plugins.manage", "params": {"action": "list"}})-- assert resp["result"]["plugins"][0]["servers"] == [{- "name": "example-server",- "state": "missing_app",- "sentence": "Example App is not installed. Install Example App, then try again.",- }]diff --git a/tests/tui_gateway/test_plugins_manage_install_ref.py b/tests/tui_gateway/test_plugins_manage_install_ref.pydeleted file mode 100644index 043d07d2ba8..00000000000--- a/tests/tui_gateway/test_plugins_manage_install_ref.py+++ /dev/null@@ -1,24 +0,0 @@-"""Desktop/TUI ``plugins.manage`` honours a ``ref`` pin exactly like ``hermes plugins install --ref``."""-from unittest.mock import patch--from tui_gateway import methods_tools, server---def test_plugins_manage_install_threads_ref_to_headless_install():- sha = "a" * 40- with patch("hermes_cli.plugins_cmd.dashboard_install_plugin", return_value={"ok": True}) as install:- server.handle_request({"id": "1", "method": "plugins.manage",- "params": {"action": "install", "identifier": "org/private-plugin", "ref": sha}})- assert install.call_args.kwargs["ref"] == sha---def test_plugins_manage_list_reports_ref_pin(monkeypatch, tmp_path):- sha = "b" * 40- pc = methods_tools._tools_mod("hermes_cli.plugins_cmd")- monkeypatch.setattr(pc, "_discover_all_plugins", lambda: [("team-plugin", "1.0", "", "git", tmp_path, "team-plugin")])- monkeypatch.setattr(pc, "_read_install_metadata", lambda: {"team-plugin": {"pinned": True, "revision": sha, "source": "x"}})- monkeypatch.setattr(pc, "_get_enabled_set", set)- monkeypatch.setattr(pc, "_get_disabled_set", set)- monkeypatch.setattr(methods_tools._tools_mod("hermes_cli.plugins_cmd_catalog"), "catalog_pins", dict)- (row,) = methods_tools._plugin_rows()- assert row["pinned_sha"] == shadiff --git a/tests/tui_gateway/test_plugins_manage_remove.py b/tests/tui_gateway/test_plugins_manage_remove.pyindex 562edb4ffdc..112a7a142d5 100644--- a/tests/tui_gateway/test_plugins_manage_remove.py+++ b/tests/tui_gateway/test_plugins_manage_remove.py@@ -41,5 +41,5 @@ def test_remove_refuses_missing_name_and_unknown_plugin(plugins_home):assert resp["error"]["code"] == 4019resp = _remove("../not-a-plugin")- assert "error" in resp and "not found" in resp["error"]["message"]+ assert "error" in respassert (plugins_home / "plugins" / "demo-plugin").exists()diff --git a/tests/tui_gateway/test_profiles_list_session_field_cache.py b/tests/tui_gateway/test_profiles_list_session_field_cache.pyindex bb96ace363d..e80ee0f7237 100644--- a/tests/tui_gateway/test_profiles_list_session_field_cache.py+++ b/tests/tui_gateway/test_profiles_list_session_field_cache.py@@ -84,24 +84,3 @@ def test_a_profile_without_a_store_is_not_memoised_and_picks_one_up(home):assert _row("bare")["last_session"]["title"] == "now it exists"-def test_an_unchanged_store_is_read_once_across_repeated_polls(home, monkeypatch):- """The saving itself: the 5s poll stops reopening a store that has not moved."""- bob = home / "profiles" / "bob"- _seed(bob, "20260920_000001_a", "steady")-- opens: list = []- real = SessionDB-- def _counting(*args, **kwargs):- opens.append(kwargs.get("db_path"))- return real(*args, **kwargs)-- monkeypatch.setattr("hermes_state.SessionDB", _counting)-- _rows()- after_first = len(opens)- _rows()- _rows()-- assert after_first >= 1, "the first poll must actually read the store"- assert len(opens) == after_first, "an unchanged store was reopened by a later poll"diff --git a/tests/tui_gateway/test_profiles_list_ui_meta_cache.py b/tests/tui_gateway/test_profiles_list_ui_meta_cache.pyindex e7a90565cd4..966a362e244 100644--- a/tests/tui_gateway/test_profiles_list_ui_meta_cache.py+++ b/tests/tui_gateway/test_profiles_list_ui_meta_cache.py@@ -70,26 +70,5 @@ def test_an_avatar_added_without_touching_profile_yaml_is_still_seen(home):assert _row()["has_avatar"] is True-def test_an_unchanged_profile_yaml_is_parsed_once_across_repeated_polls(home, monkeypatch):- """The saving itself. Counted at the server-published name: the module's bodies are rebound."""- parsed: list = []- real = srv._read_profile_yaml- def _counting(profile_dir):- parsed.append(str(profile_dir))- return real(profile_dir)- monkeypatch.setattr(srv, "_read_profile_yaml", _counting)-- for _ in range(3):- _row()-- bob = str(home / "profiles" / "bob")- assert parsed.count(bob) == 1, f"profile.yaml re-parsed: {parsed}"---def test_the_wire_key_order_is_unchanged(home):- """``ui_meta_revisions`` precedes ``ui_meta``, and ``has_avatar`` follows both."""- keys = [k for k in _row() if k.startswith("ui_meta") or k == "has_avatar"]-- assert keys == ["ui_meta_revisions", "ui_meta", "has_avatar"]diff --git a/tests/tui_gateway/test_profiles_list_worker_session.py b/tests/tui_gateway/test_profiles_list_worker_session.pyindex 2dba02edaf6..edb76259e63 100644--- a/tests/tui_gateway/test_profiles_list_worker_session.py+++ b/tests/tui_gateway/test_profiles_list_worker_session.py@@ -92,11 +92,3 @@ def test_worker_session_tool_source_counts(home):assert row["last_session"] is None-def test_include_sessions_false_omits_worker_session(home):- db = _db(home)- _add_session(db, "work1", source="kanban", title="Task", ts=1000, text="task body")- db.close()-- row = _row(_profiles({"include_sessions": False}), "default")- assert "worker_session" not in row- assert "last_session" not in rowdiff --git a/tests/tui_gateway/test_projects_rpc.py b/tests/tui_gateway/test_projects_rpc.pyindex da82a686b20..b603cbe30eb 100644--- a/tests/tui_gateway/test_projects_rpc.py+++ b/tests/tui_gateway/test_projects_rpc.py@@ -47,25 +47,8 @@ def _fast_git_probe(monkeypatch):git_probe.invalidate()-def test_methods_registered():- for m in (- "projects.list",- "projects.create",- "projects.get",- "projects.update",- "projects.add_folder",- "projects.remove_folder",- "projects.set_primary",- "projects.archive",- "projects.set_active",- "projects.for_cwd",- ):- assert m in server._methods---def test_for_cwd_is_a_long_handler():- # git-probe handler must run off the dispatch thread.- assert "projects.for_cwd" in server._LONG_HANDLERS++def test_repo_root_cache_does_not_freeze_a_not_yet_repo(monkeypatch):@@ -88,125 +71,14 @@ def test_repo_root_cache_does_not_freeze_a_not_yet_repo(monkeypatch):assert git_probe.repo_root(cwd) == cwd # now cached-def test_negative_results_are_ttl_cached_then_re_probed(monkeypatch):- # A non-repo cwd is re-derived on every session in a project-tree build, so a- # "not a repo" answer must be cached briefly to avoid re-spawning git dozens- # of times — but only until the TTL elapses, so a folder that later becomes a- # repo is still picked up.- from tui_gateway import git_probe-- git_probe.invalidate()- calls = {"n": 0}-- def probe(_cwd, *_a):- calls["n"] += 1- return "" # never a repo-- monkeypatch.setattr(git_probe, "run_git", probe)- monkeypatch.setattr(git_probe, "_NEG_TTL", 1000) # effectively no expiry here-- cwd = "/not/a/repo"- assert git_probe.repo_root(cwd) == ""- for _ in range(10):- assert git_probe.repo_root(cwd) == ""- assert calls["n"] == 1 # cached: probed once, not 11 times-- # Once the TTL lapses, the next lookup re-probes (a `git init` may have run).- monkeypatch.setattr(git_probe, "_NEG_TTL", 0)- git_probe._cache._neg[cwd] = 0.0 # force-expire the cached negative- assert git_probe.repo_root(cwd) == ""- assert calls["n"] == 2---def test_warm_roots_probes_in_parallel_and_fills_the_cache(monkeypatch):- # Cold first paint must not serialize one git subprocess per cwd.- import threading- import time-- from tui_gateway import git_probe-- git_probe.invalidate()- lock = threading.Lock()- live = {"now": 0, "peak": 0, "calls": 0}-- def slow(cwd, *_a):- with lock:- live["now"] += 1- live["calls"] += 1- live["peak"] = max(live["peak"], live["now"])- time.sleep(0.02)- with lock:- live["now"] -= 1- return cwd # show-toplevel → cwd is its own root-- monkeypatch.setattr(git_probe, "run_git", slow)- cwds = [f"/repo{i}" for i in range(8)]- git_probe.warm_roots(cwds, max_workers=8)-- assert live["peak"] > 1 # ran concurrently, not serialized- # Cache is warm: resolving again triggers no further probes.- before = live["calls"]- assert git_probe.repo_root("/repo0") == "/repo0"- assert live["calls"] == before---def test_missing_directory_costs_no_subprocess(monkeypatch):- # Deleted worktrees dominate a long session history's cwds, and `git -C` on- # one can only fail — so it must never reach the fork.- from tui_gateway import git_probe-- def boom(*_a, **_kw):- raise AssertionError("spawned git for a directory that does not exist")-- monkeypatch.setattr(git_probe, "bounded_git_probe", boom)- assert git_probe.run_git("/gone/worktree", "rev-parse", "--show-toplevel") == ""-def test_non_repo_cwd_is_not_probed_for_a_common_dir(monkeypatch, tmp_path):- # `warm_roots` only reaches `common_repo_root` for cwds that ARE repos, so a- # common-dir probe here is one the warm can't absorb: it runs serially on- # the discovery pass, once per non-repo cwd.- from tui_gateway import git_probe-- git_probe.invalidate()- asked = []-- def probe(cwd, *args):- asked.append(args[-1])- return "" # not a repo, whatever we ask- monkeypatch.setattr(git_probe, "run_git", probe)- assert git_probe.common_repo_root(str(tmp_path)) == ""- assert asked == ["--show-toplevel"]-def test_tree_build_warms_every_path_it_will_resolve(monkeypatch, tmp_path):- # build_tree resolves declared project folders and discovered repo roots as- # well as session cwds. Anything left out of the warm is probed one- # directory at a time while the sidebar shows a skeleton.- from tui_gateway import git_probe-- repo = tmp_path / "repo"- (repo / ".git").mkdir(parents=True)- _call("projects.create", {"name": "Repo", "folders": [str(repo)]})-- warmed: list[str] = []- real_warm = git_probe.warm_roots-- def recording_warm(cwds, **kw):- paths = list(cwds)- warmed.extend(paths)- return real_warm(paths, **kw)-- monkeypatch.setattr(git_probe, "warm_roots", recording_warm)-- server._build_project_tree(- server._get_db(), preview_limit=3, hydrate=False, session_limit=5, include_discovered=True- )- assert str(repo) in warmeddef test_create_list_roundtrip(tmp_path):@@ -286,14 +158,8 @@ def test_delete_removes_project(tmp_path):payload = _call("projects.delete", {"id": pid})assert all(p["id"] != pid for p in payload["projects"])- assert "projects.delete" in server._methods-def test_discover_repos_is_registered_long_handler():- assert "projects.discover_repos" in server._methods- assert "projects.discover_repos" in server._LONG_HANDLERS- assert "projects.record_repos" in server._methods- assert "projects.record_repos" in server._LONG_HANDLERSdef test_record_repos_persists_and_shows_zero_session_repo(tmp_path):diff --git a/tests/tui_gateway/test_prompt_accept_logging.py b/tests/tui_gateway/test_prompt_accept_logging.pyindex 719466b2a87..855fd9a567d 100644--- a/tests/tui_gateway/test_prompt_accept_logging.py+++ b/tests/tui_gateway/test_prompt_accept_logging.py@@ -104,80 +104,15 @@ def test_accepted_and_finished_records_on_success(turn_env, caplog):assert len(finished) == 1msg = accepted[0].getMessage()- # The full id triple a rotation-mute trace needs.- assert "ui_session=ui-sid" in msg- assert "session_key=gw-session-key" in msg- assert "agent_session_id=agent-sid-1" in msg# Prompt content is never logged — only its length.assert "hunter2" not in msgassert "QDRANT_API_KEY" not in msg- assert f"chars={len(SECRETISH_PROMPT)}" in msgfin = finished[0].getMessage()- assert "ui_session=ui-sid" in fin- assert "status=complete" in finassert "hunter2" not in fin-def test_finished_record_reflects_mid_turn_rotation(turn_env, caplog):- """Compression rotating agent.session_id mid-turn must be visible as an- accepted/finished pair with different agent ids — that pair IS the- rotation trace #86647 asks for."""- agent = types.SimpleNamespace(session_id="parent-sid", clear_interrupt=lambda: None)- def _rotate_and_finish(*a, **k):- agent.session_id = "continuation-sid" # what _compress_context does- return {"final_response": "done"}- agent.run_conversation = _rotate_and_finish- session = _session(agent=agent, running=True)-- with caplog.at_level(logging.INFO, logger="tui_gateway.server"):- server._run_prompt_submit("rid", "ui-sid", session, "go")-- accepted = _records(caplog, "tui prompt accepted")[0].getMessage()- finished = _records(caplog, "tui turn finished")[0].getMessage()- assert "agent_session_id=parent-sid" in accepted- assert "agent_session_id=continuation-sid" in finished---def test_finished_record_fires_on_exception_path(turn_env, caplog):- def _boom(*a, **k):- raise RuntimeError("connection reset mid-stream")-- agent = types.SimpleNamespace(- session_id="agent-sid-1",- run_conversation=_boom,- clear_interrupt=lambda: None,- )- session = _session(agent=agent, running=True)-- with caplog.at_level(logging.INFO, logger="tui_gateway.server"):- server._run_prompt_submit("rid", "ui-sid", session, "go")- finished = _records(caplog, "tui turn finished")- assert len(finished) == 1- msg = finished[0].getMessage()- assert "status=error" in msg- assert "error_retained=True" in msg---def test_finished_record_fires_on_returned_error(turn_env, caplog):- agent = types.SimpleNamespace(- session_id="agent-sid-1",- run_conversation=lambda *a, **k: {- "final_response": "",- "error": "provider 402: billing wall",- "failed": True,- },- clear_interrupt=lambda: None,- )- session = _session(agent=agent, running=True)-- with caplog.at_level(logging.INFO, logger="tui_gateway.server"):- server._run_prompt_submit("rid", "ui-sid", session, "go")-- finished = _records(caplog, "tui turn finished")- assert len(finished) == 1- assert "status=error" in finished[0].getMessage()diff --git a/tests/tui_gateway/test_protocol.py b/tests/tui_gateway/test_protocol.pyindex d64edd29dc7..74fd985c4d2 100644--- a/tests/tui_gateway/test_protocol.py+++ b/tests/tui_gateway/test_protocol.py@@ -67,36 +67,6 @@ def server():mod._live_transports.clear()-def test_shared_fixture_cleanup_uses_full_session_teardown(server, monkeypatch):- """The cross-file autouse cleanup must close every retained resource."""- from tests import conftest-- closed = {"worker": 0, "agent": 0, "lease": 0}-- class _Closable:- def __init__(self, key):- self.key = key-- def close(self):- closed[self.key] += 1-- class _Lease:- def release(self):- closed["lease"] += 1-- monkeypatch.setattr(server, "_get_db", lambda: None)- server._sessions["leaked"] = {- "session_key": "leaked",- "agent": _Closable("agent"),- "slash_worker": _Closable("worker"),- "active_session_lease": _Lease(),- "history": [],- }-- conftest._teardown_tui_server_sessions(server)-- assert server._sessions == {}- assert closed == {"worker": 1, "agent": 1, "lease": 1}@pytest.fixture()@@ -115,16 +85,8 @@ def test_unknown_method(server):assert resp["error"]["code"] == -32601-def test_ok_envelope(server):- assert server._ok("r1", {"x": 1}) == {- "jsonrpc": "2.0", "id": "r1", "result": {"x": 1},- }-def test_err_envelope(server):- assert server._err("r2", 4001, "nope") == {- "jsonrpc": "2.0", "id": "r2", "error": {"code": 4001, "message": "nope"},- }@pytest.mark.parametrize("kind", ["legacy", "hard-only", "dynamic-getattr"])@@ -177,10 +139,6 @@ def test_session_interrupt_uses_explicit_stop_compatibility(server, monkeypatch,# ── write_json ────────────────────────────────────────────────-def test_write_json(capture):- server, buf = capture- assert server.write_json({"test": True})- assert json.loads(buf.getvalue()) == {"test": True}def test_live_session_payload_replays_pending_approval(server, monkeypatch):@@ -247,23 +205,6 @@ def test_live_session_payload_replays_open_requests(server):assert "open_requests" not in other-def test_disable_flush_env_var_actually_wires_to_module_constant(monkeypatch):- """End-to-end: setting `HERMES_TUI_GATEWAY_NO_FLUSH=1` and importing- `tui_gateway.transport` fresh actually flips `_DISABLE_FLUSH` true.-- Reloads only the transport module — server.py is untouched so its- atexit hooks/worker pool stay intact."""- import importlib-- monkeypatch.setenv("HERMES_TUI_GATEWAY_NO_FLUSH", "1")- transport_mod = importlib.reload(importlib.import_module("tui_gateway.transport"))-- try:- assert transport_mod._DISABLE_FLUSH is True- finally:- # Restore the env-disabled state so other tests see the default.- monkeypatch.delenv("HERMES_TUI_GATEWAY_NO_FLUSH", raising=False)- importlib.reload(transport_mod)# ── _emit ────────────────────────────────────────────────────────────@@ -287,8 +228,11 @@ def _frames(buf):return [json.loads(line) for line in buf.getvalue().splitlines()]-def _wait_open(server_requests, buf=None, timeout=2.0):- """The open request once its frame has been written (registration precedes the write)."""+def _wait_open(server_requests, buf=None, timeout=10.0):+ """The open request once its frame has been written (registration precedes the write).++ Generous deadline: the first send() in a process lazily imports the ws/contracts/replay modules,+ which can take seconds on a loaded CI box when this is the first server request of the run."""deadline = time.monotonic() + timeoutwhile time.monotonic() < deadline:with server_requests._lock:@@ -701,9 +645,6 @@ def test_approval_respond_4001_when_nothing_resolves(server, monkeypatch):# ── Session lookup ───────────────────────────────────────────────────-def test_sess_missing(server):- _, err = server._sess({"session_id": "nope"}, "r1")- assert err["error"]["code"] == 4001# ── session.resume payload ────────────────────────────────────────────@@ -793,8 +734,6 @@ def test_session_resume_rejects_runaway_transcript_before_history_load()assert response["error"]["code"] == 4130- assert "limit 20000" in response["error"]["message"]- assert "hermes sessions export" in response["error"]["message"]def test_session_resume_deferred_and_omitted_paths_guard_the_tip_only(server, monkeypatch):@@ -947,12 +886,10 @@ def test_session_resume_guard_failure_fails_open(server, monkeypatch):})- # The guard must not block: no 4130, and any downstream failure must not- # be the guard's own "resume safety check failed" error. Reopen being- # attempted proves execution moved past the guard.+ # The guard must not block: no 4130. Reopen being attempted proves+ # execution moved past the guard.err = response.get("error") or {}assert err.get("code") != 4130- assert "resume safety check failed" not in str(err.get("message", ""))assert reopened == ["transient-guard-session"]@@ -1267,7 +1204,6 @@ def test_slash_exec_rejects_skill_commands(server):# Should return an error so the TUI's .catch() fires command.dispatchassert "error" in respassert resp["error"]["code"] == 4018- assert "skill command" in resp["error"]["message"]def test_slash_exec_scopes_skill_lookup_to_session_profile(server, tmp_path):@@ -1320,7 +1256,6 @@ def test_slash_exec_scopes_skill_lookup_to_session_profile(server, tmp_path):# resolves is by scoping the lookup to the session's profile_home.assert "error" in respassert resp["error"]["code"] == 4018- assert "skill command" in resp["error"]["message"]def test_command_dispatch_scopes_skill_lookup_to_session_profile(server, tmp_path):@@ -1416,31 +1351,6 @@ def test_command_dispatch_queue_sends_message(server):assert result["message"] == "tell me about quantum computing"-def test_skills_manage_search_uses_tools_hub_sources(server):- result = type("Result", (), {- "description": "Build better terminal demos",- "name": "showroom",- })()- auth = MagicMock(return_value="auth")- router = MagicMock(return_value=["source"])- search = MagicMock(return_value=[result])- fake_search = types.SimpleNamespace(create_source_router=router, unified_search=search)- fake_github = types.SimpleNamespace(GitHubAuth=auth)-- with patch.dict(sys.modules, {"tools.skills_hub_search": fake_search, "tools.skills_hub_github": fake_github}):- resp = server.handle_request({- "id": "skills-search",- "method": "skills.manage",- "params": {"action": "search", "query": "showroom"},- })-- assert "error" not in resp- assert resp["result"] == {- "results": [{"description": "Build better terminal demos", "name": "showroom"}]- }- auth.assert_called_once_with()- router.assert_called_once_with("auth")- search.assert_called_once_with("showroom", ["source"], source_filter="all", limit=20)# ── dispatch(): pool routing for long handlers (#12546) ──────────────@@ -1455,36 +1365,8 @@ def test_dispatch_runs_short_handlers_inline(server):assert resp == {"jsonrpc": "2.0", "id": "r1", "result": {"pong": True}}[email protected]("completion_method", ["complete.path", "complete.slash"])-def test_completion_handlers_are_pool_routed(completion_method, server):- """complete.path/complete.slash must run on the pool, never the reader thread.- Regression for #21123: completion ran inline, so a slow git ls-files /- skill-scan blocked prompt.submit and froze the TUI for the 120s RPC timeout.- """- assert completion_method in server._LONG_HANDLERS--- "voice_or_wake_method",- ["voice.toggle", "voice.record", "voice.tts", "wake.start", "wake.status"],-)-def test_voice_and_wake_handlers_are_pool_routed(voice_or_wake_method, server):- """Voice and wake RPCs must run on the pool, never the WS reader thread.-- Regression: voice.toggle (status) triggers check_voice_requirements() →- STT provider auto-detect → a SYNCHRONOUS faster-whisper lazy install (uv/pip- subprocess, up to a 300s timeout). Inline on the WS reader loop it blocked- prompt.submit / session.list frames queued behind it — the desktop showed- sent messages that never reached the agent. Same bug class as #21123 /- #50005: anything that can stall for seconds must stay off the reader thread.-- wake.start and wake.status share the same STT lazy-install path via- check_wake_word_requirements() → _stt_ready() → _get_provider(), and- wake.start additionally calls lazy_deps.ensure() for wake-word engine deps.- The desktop polls wake.status on every gateway-ready.- """- assert voice_or_wake_method in server._LONG_HANDLERS+def test_skin_live_switch_end_to_end(server, tmp_path, monkeypatch):diff --git a/tests/tui_gateway/test_reaper_flush_profile_scope.py b/tests/tui_gateway/test_reaper_flush_profile_scope.pyindex 14afd853ae6..26e2c7f6980 100644--- a/tests/tui_gateway/test_reaper_flush_profile_scope.py+++ b/tests/tui_gateway/test_reaper_flush_profile_scope.py@@ -69,16 +69,3 @@ def test_exit_flush_never_waits_on_an_external_secret_source(homes, monkeypatch)assert tui_server._flush_sessions_before_exit(budget_s=1.0) == 1-def test_exit_flush_warns_when_it_loses_a_transcript(homes, monkeypatch, caplog):- """Both callers discard the return value, so an overrun is invisible without this line."""- _launch, served = homes-- class _Stuck(_Agent):- def _persist_session(self, _messages):- time.sleep(2.0)-- _install_session(monkeypatch, {"agent": _Stuck([]), "profile_home": str(served)})-- with caplog.at_level("WARNING"):- assert tui_server._flush_sessions_before_exit(budget_s=0.2) == 0- assert any("Exit flush persisted 0 of 1" in r.getMessage() for r in caplog.records), caplog.textdiff --git a/tests/tui_gateway/test_render.py b/tests/tui_gateway/test_render.pydeleted file mode 100644index 1d86f46c27c..00000000000--- a/tests/tui_gateway/test_render.py+++ /dev/null@@ -1,31 +0,0 @@-"""Tests for tui_gateway.render — rendering bridge fallback behavior."""--from unittest.mock import MagicMock, patch--from tui_gateway.render import make_stream_renderer, render_diff, render_message---def _stub_rich(mock_mod):- return patch.dict("sys.modules", {"agent.rich_output": mock_mod})---def _no_rich():- return patch.dict("sys.modules", {"agent.rich_output": None})---# ── render_message ───────────────────────────────────────────────────---def test_render_message_none_without_module():- with _no_rich():- assert render_message("hello") is None---# ── render_diff / make_stream_renderer ───────────────────────────────---def test_stream_renderer_none_without_module():- with _no_rich():- assert make_stream_renderer() is None--diff --git a/tests/tui_gateway/test_review_summary_callback.py b/tests/tui_gateway/test_review_summary_callback.pyindex d9fe7aa68ab..e123df94b3b 100644--- a/tests/tui_gateway/test_review_summary_callback.py+++ b/tests/tui_gateway/test_review_summary_callback.py@@ -99,26 +99,6 @@ def test_init_session_attaches_background_review_callback(server, monkeypatch):}-def test_review_summary_callback_survives_agent_without_attribute(server, monkeypatch):- """If the agent is a bare object that doesn't allow attribute- assignment (e.g. some stubbed test double), _init_session must not- raise — session startup stays robust."""- monkeypatch.setattr(server, "_SlashWorker", lambda *a, **kw: object())- monkeypatch.setattr(server, "_wire_callbacks", lambda sid: None)- monkeypatch.setattr(server, "_notify_session_boundary", lambda *a, **kw: None)- monkeypatch.setattr(server, "_session_info", lambda agent, session=None: {"model": "m"})- monkeypatch.setattr(server, "_load_show_reasoning", lambda: False)- monkeypatch.setattr(server, "_load_tool_progress_mode", lambda: "all")- monkeypatch.setattr(server, "_emit", lambda *a, **kw: None)-- class LockedAgent:- __slots__ = ("model",)-- def __init__(self):- self.model = "fake/model"-- # LockedAgent's __slots__ blocks background_review_callback assignment.- server._init_session("sid-x", "key-x", LockedAgent(), [], cols=80)# If we got here, _init_session swallowed the AttributeError gracefully.diff --git a/tests/tui_gateway/test_rollback_container_refusal.py b/tests/tui_gateway/test_rollback_container_refusal.pyindex cf25213eb90..096b5a7258b 100644--- a/tests/tui_gateway/test_rollback_container_refusal.py+++ b/tests/tui_gateway/test_rollback_container_refusal.py@@ -34,8 +34,7 @@ def test_rollback_diff_refuses_container_backed_session():finally:server._sessions.pop("sid", None)- assert "result" not in resp- assert "terminal.backend=docker" in resp["error"]["message"]+ assert "result" not in resp and resp["error"]assert seen["task_id"] == "container-session"diff --git a/tests/tui_gateway/test_serve_exit_flush.py b/tests/tui_gateway/test_serve_exit_flush.pyindex 6b86e482b2b..de69e545977 100644--- a/tests/tui_gateway/test_serve_exit_flush.py+++ b/tests/tui_gateway/test_serve_exit_flush.py@@ -186,15 +186,3 @@ def test_periodic_flush_skips_running_sessions(registered_session, monkeypatch):assert agent.flush_calls == []-def test_idle_reaper_scan_piggybacks_incremental_flush(monkeypatch):- """The existing reaper tick drives the flush — no new timer subsystem."""- called = {"flush": 0}- monkeypatch.setattr(- server,- "_flush_dirty_sessions",- lambda now=None: called.__setitem__("flush", called["flush"] + 1) or 0,- )- monkeypatch.setattr(server, "_enforce_session_cap", lambda: None)- monkeypatch.setattr(server, "_reclaim_orphaned_leases", lambda: None)- server._reap_idle_sessions()- assert called["flush"] == 1diff --git a/tests/tui_gateway/test_session_control.py b/tests/tui_gateway/test_session_control.pyindex a022fca1508..27ae37c6c8f 100644--- a/tests/tui_gateway/test_session_control.py+++ b/tests/tui_gateway/test_session_control.py@@ -159,7 +159,6 @@ def _save_heartbeat(key, **overrides):class TestStructuredRead:def test_methods_are_registered_and_empty_snapshot_is_stable(self, server, session):sid, _, _ = session- assert {"session.control.read", "session.control"} <= set(server._methods)first = _control(server, sid)second = _control(server, sid)assert first == second@@ -220,8 +219,7 @@ class TestStructuredRead:sid, key, _ = sessionsetup(key)before = _control(server, sid)- assert isinstance(before["revision"], str)- assert len(before["revision"]) == 64+ assert isinstance(before["revision"], str) and before["revision"]assert before == _control(server, sid)if kind == "goal":@@ -274,15 +272,15 @@ class TestManagerOnlyMutations:_forbid_dispatch(server, monkeypatch)added = _call(server, "session.control", session_id=sid, action="subgoal.add", args={"text": "Second criterion"})- assert added["result"]["dispatch"]["output"] == "✓ Added subgoal 2: Second criterion"+ assert "error" not in addedassert load_goal(key).subgoals == ["First criterion", "Second criterion"]removed = _call(server, "session.control", session_id=sid, action="subgoal.remove", args={"index": 1})- assert removed["result"]["dispatch"]["output"] == "✓ Removed subgoal 1: First criterion"+ assert "error" not in removedassert load_goal(key).subgoals == ["Second criterion"]cleared = _call(server, "session.control", session_id=sid, action="subgoal.clear")- assert cleared["result"]["dispatch"]["output"] == "✓ Cleared 1 subgoal."+ assert "error" not in clearedassert load_goal(key).subgoals == []def test_subgoal_requires_a_goal_and_valid_arguments_without_dispatch(self, server, session, monkeypatch):@@ -310,27 +308,24 @@ class TestManagerOnlyMutations:GoalManager(key).wait_for_seconds(60, reason="backoff")response = _call(server, "session.control", session_id=sid, action="goal.unwait")- assert response["result"]["dispatch"]["output"] == "▶ Wait barrier cleared — goal loop resumes."+ assert "error" not in responseassert GoalManager(key).state.waiting_until == 0.0def test_heartbeat_pause_resume_clear_and_no_heartbeat_messages_do_not_dispatch(self, server, session, monkeypatch):sid, key, _ = session_forbid_dispatch(server, monkeypatch)- assert _call(server, "session.control", session_id=sid, action="heartbeat.pause")["result"]["dispatch"]["output"] == "No heartbeat set."- assert _call(server, "session.control", session_id=sid, action="heartbeat.resume")["result"]["dispatch"]["output"] == "No heartbeat to resume."- assert _call(server, "session.control", session_id=sid, action="heartbeat.clear")["result"]["dispatch"]["output"] == "No heartbeat set."+ for action in ("heartbeat.pause", "heartbeat.resume", "heartbeat.clear"):+ empty = _call(server, "session.control", session_id=sid, action=action)+ assert "error" not in empty and empty["result"]["control"]["heartbeat"] is None_save_heartbeat(key, status="active", last_fired_at=1.0)paused = _call(server, "session.control", session_id=sid, action="heartbeat.pause")- assert paused["result"]["dispatch"]["output"] == "⏸ Heartbeat paused: Check the deployment"assert paused["result"]["control"]["heartbeat"]["status"] == "paused"resumed = _call(server, "session.control", session_id=sid, action="heartbeat.resume")- assert resumed["result"]["dispatch"]["output"] == "▶ Heartbeat resumed (every 10m): Check the deployment"assert resumed["result"]["control"]["heartbeat"]["last_fired_at"] > 1.0cleared = _call(server, "session.control", session_id=sid, action="heartbeat.clear")- assert cleared["result"]["dispatch"]["output"] == "✓ Heartbeat cleared."assert cleared["result"]["control"]["heartbeat"] is Nonediff --git a/tests/tui_gateway/test_session_db_ownership_teardown.py b/tests/tui_gateway/test_session_db_ownership_teardown.pyindex 9d708cb70bc..73284499282 100644--- a/tests/tui_gateway/test_session_db_ownership_teardown.py+++ b/tests/tui_gateway/test_session_db_ownership_teardown.py@@ -241,17 +241,6 @@ def test_transfer_is_refused_for_the_shared_launch_handle(monkeypatch):assert agent._owns_session_db is False-def test_get_db_returns_the_cached_instance(monkeypatch):- """The identity defense (``db is _get_db()``) only works while _get_db- hands out ONE process-wide instance. Pin the caching semantics: once a- handle exists, repeated calls return the same object rather than- constructing per-call wrappers (review finding on #91631)."""- sentinel = types.SimpleNamespace(closed=0)- monkeypatch.setattr(server, "_db", sentinel)- monkeypatch.setattr(server, "_db_error", None)-- assert server._get_db() is sentinel- assert server._get_db() is server._get_db()# ---------------------------------------------------------------------------diff --git a/tests/tui_gateway/test_session_hidden_rpc.py b/tests/tui_gateway/test_session_hidden_rpc.pyindex 25a35293e95..c23b38a7871 100644--- a/tests/tui_gateway/test_session_hidden_rpc.py+++ b/tests/tui_gateway/test_session_hidden_rpc.py@@ -59,14 +59,6 @@ def test_set_hidden_unknown_id_still_errors(db):assert envelope.get("error"), envelope-def test_set_hidden_stored_id_does_not_log_a_rejection(db, caplog):- """The stored-id tier is this method's design, not a stale-runtime-id rejection: a fulfilled hide must- not emit the "session-scoped RPC rejected … not in memory" warning that diagnoses vanished messages."""- _seed(db, "stored-chat")- with caplog.at_level("WARNING", logger=srv.logger.name):- envelope = _call("session.set_hidden", {"session_id": "stored-chat", "hidden": True})- assert "error" not in envelope, envelope- assert not [r for r in caplog.records if "session-scoped RPC rejected" in r.getMessage()]def test_session_list_include_hidden(db):diff --git a/tests/tui_gateway/test_session_platform_resolution.py b/tests/tui_gateway/test_session_platform_resolution.pyindex 76e35330887..215bc643188 100644--- a/tests/tui_gateway/test_session_platform_resolution.py+++ b/tests/tui_gateway/test_session_platform_resolution.py@@ -50,17 +50,7 @@ class TestResolveSessionPlatform:assert _srv._resolve_session_platform() == "desktop"- @pytest.mark.parametrize("val", ["1", "true", "yes", "on", "TRUE", "Yes", "ON"])- def test_truthy_variants_recognized(self, clean_env, val):- clean_env.setenv("HERMES_DESKTOP", val)- _srv = _reload_resolver()- assert _srv._resolve_session_platform() == "desktop"- @pytest.mark.parametrize("val", ["0", "false", "", "no", "off", "False"])- def test_falsy_variants_fall_back_to_tui(self, clean_env, val):- clean_env.setenv("HERMES_DESKTOP", val)- _srv = _reload_resolver()- assert _srv._resolve_session_platform() == "tui"def test_embedded_terminal_overrides_desktop_when_both_set(self, clean_env):"""The terminal-pane qualifier must short-circuit the desktop-backenddiff --git a/tests/tui_gateway/test_session_usage_account_lines.py b/tests/tui_gateway/test_session_usage_account_lines.pyindex e651dfafeae..50290a2a261 100644--- a/tests/tui_gateway/test_session_usage_account_lines.py+++ b/tests/tui_gateway/test_session_usage_account_lines.py@@ -47,5 +47,4 @@ def test_session_usage_rpc_ships_account_lines_for_the_live_route():assert result["total"] == 30 and "credits_lines" not in result# Fetched against the session's own route, not a default endpoint.assert seen == [("openai-codex", "https://chatgpt.example/backend-api", "tok")]- assert "Provider: openai-codex (Plus)" in result["account_lines"]- assert any(line.startswith("Weekly") and "12%" in line for line in result["account_lines"])+ assert result["account_lines"]diff --git a/tests/tui_gateway/test_slash_fuzzy.py b/tests/tui_gateway/test_slash_fuzzy.pyindex 648602f1ca6..9cfe023c95d 100644--- a/tests/tui_gateway/test_slash_fuzzy.py+++ b/tests/tui_gateway/test_slash_fuzzy.py@@ -12,7 +12,6 @@ from tui_gateway.slash_fuzzy import (fuzzy_rank_slash_items,normalize_slash_search_query,score_slash_completion_item,- tokenize_search_text,)@@ -26,19 +25,8 @@ def test_normalize_slash_search_query():assert normalize_slash_search_query("plain") == "plain"-def test_tokenize_search_text_includes_full_value_and_words():- assert tokenize_search_text("Commit & Push") == ["commit & push", "commit", "push"]-def test_score_tiers_name_before_description():- item = _item("/recaps ", "Turn session recaps on/off")- assert score_slash_completion_item(item, "recaps") == 0- assert score_slash_completion_item(item, "rec") == 1- assert score_slash_completion_item(item, "caps") == 2- assert score_slash_completion_item(item, "session") == 3- assert score_slash_completion_item(item, "sess") == 4- assert score_slash_completion_item(item, "essio") == 5- assert math.isinf(score_slash_completion_item(item, "zzz"))def test_name_match_beats_description_match():diff --git a/tests/tui_gateway/test_slash_worker_profile_home.py b/tests/tui_gateway/test_slash_worker_profile_home.pydeleted file mode 100644index c1459bc5bf1..00000000000--- a/tests/tui_gateway/test_slash_worker_profile_home.py+++ /dev/null@@ -1,38 +0,0 @@-"""Tests for TUI gateway slash_worker profile_home propagation (#40677)."""--from pathlib import Path-from unittest.mock import MagicMock, patch---def test_slash_worker_accepts_profile_home():- """_SlashWorker.__init__ accepts profile_home parameter."""- # hermes_state evaluates get_hermes_home() / "state.db" at import time, so- # the mock must return a Path (a bare str raises TypeError under per-file- # subprocess isolation).- with patch.dict("sys.modules", {- "hermes_constants": MagicMock(- get_hermes_home=MagicMock(return_value=Path("/tmp/hermes_test")),- ),- }):- with patch("subprocess.Popen") as mock_popen:- mock_popen.return_value.stdout = MagicMock()- mock_popen.return_value.stderr = MagicMock()-- from tui_gateway.server import _SlashWorker-- # Test initialization with profile_home- worker = _SlashWorker(- session_key="test_key",- model="test-model",- profile_home="/home/luke/.hermes/profiles/work"- )-- # Verify Popen was called- assert mock_popen.called-- # Check that HERMES_HOME was set in the environment- call_kwargs = mock_popen.call_args[1]- assert "env" in call_kwargs- assert call_kwargs["env"]["HERMES_HOME"] == "/home/luke/.hermes/profiles/work"--diff --git a/tests/tui_gateway/test_slash_worker_sys_path.py b/tests/tui_gateway/test_slash_worker_sys_path.pyindex 01cfa559014..798a7d3a9fe 100644--- a/tests/tui_gateway/test_slash_worker_sys_path.py+++ b/tests/tui_gateway/test_slash_worker_sys_path.py@@ -11,7 +11,6 @@ helper) but missed this child, so the crash still reproduced. slash_worker.pymust run the guard before its first non-stdlib import."""-import astimport osimport subprocessimport sys@@ -49,44 +48,5 @@ def test_slash_worker_imports_from_cwd_with_colliding_utils(tmp_path):)-def test_sys_path_guard_runs_before_cli_import():- """The guard must execute before ``import cli`` — reordering it below the- import would re-introduce the shadowing crash. Assert via AST that the- ``hermes_bootstrap.harden_import_path()`` call precedes ``import cli``."""- src = (PROJECT_ROOT / "tui_gateway" / "slash_worker.py").read_text()- tree = ast.parse(src)- harden_call_line = None- cli_import_line = None- for node in ast.walk(tree):- if (- isinstance(node, ast.Call)- and isinstance(node.func, ast.Attribute)- and node.func.attr == "harden_import_path"- ):- if harden_call_line is None:- harden_call_line = node.lineno- if isinstance(node, ast.Import) and any(a.name == "cli" for a in node.names):- if cli_import_line is None:- cli_import_line = node.lineno- assert harden_call_line is not None, (- "slash_worker.py must call hermes_bootstrap.harden_import_path()"- )- assert cli_import_line is not None, "slash_worker.py must 'import cli'"- assert harden_call_line < cli_import_line, (- "harden_import_path() must run before 'import cli' (issue #51286)"- )---def test_guard_delegates_to_shared_helper_not_inline():- """slash_worker should delegate to the shared guard, not re-implement the- old inline ``{"", "."}`` sys.path filter that #51693 replaced."""- src = (PROJECT_ROOT / "tui_gateway" / "slash_worker.py").read_text()- assert '{"", "."}' not in src and "{'', '.'}" not in src, (- "slash_worker.py should delegate to hermes_bootstrap.harden_import_path, "- "not re-implement the guard inline"- )- assert "hermes_bootstrap.harden_import_path()" in src, (- "slash_worker.py must call the shared hermes_bootstrap.harden_import_path guard"- )diff --git a/tests/tui_gateway/test_slash_worker_watchdog.py b/tests/tui_gateway/test_slash_worker_watchdog.pyindex eb5c54e2558..3ed73be03cc 100644--- a/tests/tui_gateway/test_slash_worker_watchdog.py+++ b/tests/tui_gateway/test_slash_worker_watchdog.py@@ -1,4 +1,3 @@-import inspectfrom tui_gateway import slash_worker@@ -13,11 +12,3 @@ def test_is_orphaned_false_when_direct_parent_is_unchanged():assert slash_worker._is_orphaned(original_ppid, getppid=lambda: original_ppid) is False-def test_parent_death_watchdog_contract_has_no_create_time_plumbing():- assert list(inspect.signature(slash_worker._is_orphaned).parameters) == [- "original_ppid",- "getppid",- ]- assert list(inspect.signature(slash_worker._start_parent_death_watchdog).parameters) == [- "original_ppid",- ]diff --git a/tests/tui_gateway/test_spawn_tree_records.py b/tests/tui_gateway/test_spawn_tree_records.pyindex 11630009355..44b5320aaf0 100644--- a/tests/tui_gateway/test_spawn_tree_records.py+++ b/tests/tui_gateway/test_spawn_tree_records.py@@ -32,4 +32,3 @@ def test_spawn_tree_load_rejects_non_dict_snapshot(tmp_path, monkeypatch):envelope = srv._methods["spawn_tree.load"](1, {"path": str(bad)})assert "error" in envelope- assert "not a JSON object" in envelope["error"]["message"]diff --git a/tests/tui_gateway/test_startup_orphan_sweep.py b/tests/tui_gateway/test_startup_orphan_sweep.pyindex 90190a065ee..49abc1070e3 100644--- a/tests/tui_gateway/test_startup_orphan_sweep.py+++ b/tests/tui_gateway/test_startup_orphan_sweep.py@@ -221,59 +221,7 @@ class TestScheduleStartupOrphanSweep:class TestEntryAndWsWiring:- def test_main_schedules_sweep(self, monkeypatch):- scheduled = {"n": 0}- def _schedule():- scheduled["n"] += 1-- monkeypatch.setattr(server, "_schedule_startup_orphan_sweep", _schedule)- monkeypatch.setattr(entry, "_install_sidecar_publisher", lambda: None)- monkeypatch.setattr(entry, "ensure_mcp_discovery_started", lambda: None)- monkeypatch.setattr(entry, "resolve_skin", lambda: "default")- monkeypatch.setattr(entry.server, "_ensure_skin_watcher", lambda: None)- monkeypatch.setattr(entry, "_log_exit", lambda reason: None)- monkeypatch.setattr(entry, "handle_spurious_eof", lambda *a: False)- monkeypatch.setattr(entry, "write_json", lambda _payload: True)- monkeypatch.setattr(entry.sys, "stdin", io.StringIO(""))-- # Prewarm is imported lazily inside main(); keep it inert.- import hermes_cli.model_switch as ms-- monkeypatch.setattr(model_switch_providers, "prewarm_picker_cache_async", lambda: None)-- entry.main()- assert scheduled["n"] == 1-- def test_handle_ws_schedules_sweep(self, monkeypatch):- import asyncio-- from tui_gateway import ws as ws_mod-- scheduled = {"n": 0}- monkeypatch.setattr(- server, "_schedule_startup_orphan_sweep", lambda: scheduled.__setitem__("n", scheduled["n"] + 1)- )- monkeypatch.setattr(server, "resolve_skin", lambda: "default")- monkeypatch.setattr(server, "_ensure_skin_watcher", lambda: None)- monkeypatch.setattr(server, "register_live_transport", lambda *_a, **_k: None)- monkeypatch.setattr(server, "_WS_ORPHAN_REAP_GRACE_S", 0)-- class FakeWS:- async def accept(self):- pass-- async def send_text(self, line):- pass-- async def receive_text(self):- raise ws_mod._WebSocketDisconnect()-- async def close(self):- pass-- asyncio.run(ws_mod.handle_ws(FakeWS()))- assert scheduled["n"] == 1def test_schedule_failure_does_not_break_main(self, monkeypatch):def _boom():@@ -288,7 +236,6 @@ class TestEntryAndWsWiring:monkeypatch.setattr(entry, "handle_spurious_eof", lambda *a: False)monkeypatch.setattr(entry, "write_json", lambda _payload: True)monkeypatch.setattr(entry.sys, "stdin", io.StringIO(""))- import hermes_cli.model_switch as msmonkeypatch.setattr(model_switch_providers, "prewarm_picker_cache_async", lambda: None)diff --git a/tests/tui_gateway/test_subprocess_encoding.py b/tests/tui_gateway/test_subprocess_encoding.pydeleted file mode 100644index a1dd0bbc1a5..00000000000--- a/tests/tui_gateway/test_subprocess_encoding.py+++ /dev/null@@ -1,132 +0,0 @@-"""Regression tests for UTF-8 encoding hardening in tui_gateway/server.py (#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. When a child-process emitted bytes invalid in that locale, an unhandled UnicodeDecodeError-crashed the reader thread / gateway thread.--#53137 added encoding="utf-8", errors="replace" to every text-mode subprocess-call in tui_gateway/server.py. These tests assert that the kwargs survive so-the crash class cannot silently regress.--# Test pattern adapted from @devorun's PR #52700 (salvage convention).-"""--from __future__ import annotations--import subprocess-from unittest.mock import MagicMock, patch--import pytest--import tui_gateway.server as server---# ── helpers ──────────────────────────────────────────────────────────────--def _make_completed_process() -> MagicMock:- """A CompletedProcess-like mock with str stdout/stderr (text=True contract)."""- cp = MagicMock()- cp.stdout = ""- cp.stderr = ""- cp.returncode = 0- return cp---# ── _SlashWorker.Popen path ──────────────────────────────────────────────--def test_slash_worker_popen_uses_utf8_replace():- """The slash-worker subprocess.Popen must pass encoding="utf-8" and- errors="replace" so invalid bytes in child stdout/stderr don't raise- UnicodeDecodeError inside the drain threads (#53137).- """- with patch.dict("sys.modules", {- "hermes_constants": MagicMock(- get_hermes_home=MagicMock(return_value="/tmp/hermes_test")- ),- }):- with patch("subprocess.Popen") as mock_popen:- mock_popen.return_value.stdout = MagicMock()- mock_popen.return_value.stderr = MagicMock()-- from tui_gateway.server import _SlashWorker-- _SlashWorker(- session_key="test_key",- model="test-model",- )-- assert mock_popen.called, "Popen was not invoked"- kwargs = mock_popen.call_args[1]- assert kwargs.get("encoding") == "utf-8", (- f"slash-worker Popen must set encoding='utf-8' (got {kwargs.get('encoding')!r})"- )- assert kwargs.get("errors") == "replace", (- f"slash-worker Popen must set errors='replace' (got {kwargs.get('errors')!r})"- )---# ── cli.exec handler ─────────────────────────────────────────────────────--def test_cli_exec_uses_utf8_replace():- """The cli.exec RPC handler runs `python -m hermes_cli.main` via- subprocess.run; it must pass encoding="utf-8" and errors="replace"- (#53137)."""- handler = server._methods["cli.exec"]- with patch("subprocess.run", return_value=_make_completed_process()) as mock_run:- # Non-interactive argv that passes _cli_exec_blocked.- resp = handler(1, {"argv": ["--version"]})- assert mock_run.called, "subprocess.run was not invoked"- kwargs = mock_run.call_args[1]- assert kwargs.get("encoding") == "utf-8", (- f"cli.exec subprocess.run must set encoding='utf-8' (got {kwargs.get('encoding')!r})"- )- assert kwargs.get("errors") == "replace", (- f"cli.exec subprocess.run must set errors='replace' (got {kwargs.get('errors')!r})"- )---# ── shell.exec handler ───────────────────────────────────────────────────--def test_shell_exec_uses_utf8_replace():- """The shell.exec RPC handler runs an arbitrary shell command via- subprocess.run; it must pass encoding="utf-8" and errors="replace"- (#53137)."""- handler = server._methods["shell.exec"]- with patch("subprocess.run", return_value=_make_completed_process()) as mock_run:- # A harmless, non-dangerous command that passes the approval gate.- with patch("tools.approval_detection.detect_hardline_command", return_value=(False, "")), \- patch("tools.approval_detection.detect_dangerous_command", return_value=(False, None, "")):- resp = handler(1, {"command": "echo hello"})- assert mock_run.called, "subprocess.run was not invoked"- kwargs = mock_run.call_args[1]- assert kwargs.get("encoding") == "utf-8", (- f"shell.exec subprocess.run must set encoding='utf-8' (got {kwargs.get('encoding')!r})"- )- assert kwargs.get("errors") == "replace", (- f"shell.exec subprocess.run must set errors='replace' (got {kwargs.get('errors')!r})"- )---# ── quick-command exec path (via command.dispatch) ───────────────────────--def test_quick_command_exec_uses_utf8_replace():- """A quick_command of type 'exec' is dispatched via command.dispatch;- the underlying subprocess.run must pass encoding="utf-8" and- errors="replace" (#53137)."""- handler = server._methods["command.dispatch"]- fake_cp = _make_completed_process()- with patch("subprocess.run", return_value=fake_cp) as mock_run, \- patch("tui_gateway.server._load_cfg", return_value={- "quick_commands": {"runcmd": {"type": "exec", "command": "echo hi"}}- }), \- patch("tools.environments.local._sanitize_subprocess_env", return_value={"PATH": "/usr/bin"}):- resp = handler(1, {"name": "runcmd", "arg": "", "session_id": ""})- assert mock_run.called, "subprocess.run was not invoked for quick-command exec"- kwargs = mock_run.call_args[1]- assert kwargs.get("encoding") == "utf-8", (- f"quick-command exec subprocess.run must set encoding='utf-8' (got {kwargs.get('encoding')!r})"- )- assert kwargs.get("errors") == "replace", (- f"quick-command exec subprocess.run must set errors='replace' (got {kwargs.get('errors')!r})"- )diff --git a/tests/tui_gateway/test_tour_bridge_fail_fast.py b/tests/tui_gateway/test_tour_bridge_fail_fast.pyindex 290c5e0ca47..e7c96d1bcad 100644--- a/tests/tui_gateway/test_tour_bridge_fail_fast.py+++ b/tests/tui_gateway/test_tour_bridge_fail_fast.py@@ -56,12 +56,6 @@ def test_a_client_that_answers_gets_the_full_deadline_back(session, bridge):assert bridge.calls[1]["timeout"] == server._TOUR_TIMEOUT_S-def test_unanswered_probe_explains_the_real_problem(session, bridge):- result = json.loads(server._tour_request("s1", {"action": "targets"}))-- assert result["success"] is False- assert "desktop" in result["error"].lower()- assert "update" in result["error"].lower()def test_later_actions_short_circuit_instead_of_stalling_again(session, bridge):diff --git a/tests/tui_gateway/test_tui_entry_mcp_owner.py b/tests/tui_gateway/test_tui_entry_mcp_owner.pyindex c1d19d743d8..5db2330da84 100644--- a/tests/tui_gateway/test_tui_entry_mcp_owner.py+++ b/tests/tui_gateway/test_tui_entry_mcp_owner.py@@ -15,10 +15,6 @@ from hermes_constants import hermes_home_keyfrom tui_gateway import entry-def test_tui_uses_shared_portable_mcp_gate(monkeypatch):- monkeypatch.setattr(mcp_startup, "_has_configured_mcp_servers", lambda: True)-- assert entry._has_configured_mcp_servers() is Truedef test_wait_falls_through_to_shared_owner(monkeypatch):@@ -52,14 +48,6 @@ def test_wait_noop_when_no_owner_has_a_thread(monkeypatch):assert time.monotonic() - start < 0.5-def test_wait_still_joins_entry_local_thread(monkeypatch):- thread = threading.Thread(target=lambda: time.sleep(0.05), daemon=True)- thread.start()- monkeypatch.setattr(entry, "_mcp_discovery_thread", thread)-- entry.wait_for_mcp_discovery(timeout=2.0)-- assert not thread.is_alive()def test_wait_reinvokes_shared_spawn_when_discovery_enabled(monkeypatch):diff --git a/tests/tui_gateway/test_tui_gateway_queue_on_busy.py b/tests/tui_gateway/test_tui_gateway_queue_on_busy.pyindex 9959daadd74..d0206c7b718 100644--- a/tests/tui_gateway/test_tui_gateway_queue_on_busy.py+++ b/tests/tui_gateway/test_tui_gateway_queue_on_busy.py@@ -10,7 +10,6 @@ path retained as a compatibility fallback."""import threading-import timeimport typesimport tools.async_delegation as ad@@ -33,10 +32,6 @@ def _session(agent=None, **extra):# ── _enqueue_prompt ────────────────────────────────────────────────────────-def test_enqueue_pins_text_and_transport():- session = _session()- server._enqueue_prompt(session, "hello", "ws-1")- assert session["queued_prompt"] == {"text": "hello", "transport": "ws-1"}def test_enqueue_preserves_order_after_an_image_turn():diff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.pyindex a061a2f0edd..5cc7c044d0a 100644--- a/tests/tui_gateway/test_tui_gateway_server.py+++ b/tests/tui_gateway/test_tui_gateway_server.py@@ -129,7 +129,7 @@ def test_session_slot_is_claimed_on_first_turn_not_on_create(monkeypatch, tmp_paassert len(active_session_registry_snapshot()) == 1blocked = server._ensure_active_session_slot(other, server._sessions[other])- assert "active session limit (1/1)" in blocked+ assert blocked # refusal reason returned; exact wording not pinnedclosed = server._methods["session.close"]("r3", {"session_id": sid})assert closed["result"]["closed"] is True@@ -214,15 +214,6 @@ def test_handoff_fail_marks_only_inflight_rows(monkeypatch):server._sessions.pop(sid, None)-def test_dashboard_process_isolation_config_defaults_without_default_merge(monkeypatch):- """tui_gateway.server::_load_cfg is raw YAML, so defaults live at read site."""- monkeypatch.setattr(server, "_load_cfg", lambda: {})-- assert server._load_dashboard_process_isolation_config() == {- "turn_isolation": False,- "compute_host_heartbeat_secs": 15,- "compute_host_respawn_max": 3,- }def test_dashboard_process_isolation_config_coerces_raw_values():@@ -248,13 +239,6 @@ def test_dashboard_process_isolation_config_coerces_raw_values():}-def test_default_config_seeds_dashboard_process_isolation_keys():- from hermes_cli.config import DEFAULT_CONFIG-- dashboard = DEFAULT_CONFIG["dashboard"]- assert dashboard["turn_isolation"] is False- assert dashboard["compute_host_heartbeat_secs"] == 15- assert dashboard["compute_host_respawn_max"] == 3def test_prompt_submit_dispatches_to_compute_host_when_turn_isolation_enabled(monkeypatch):@@ -363,22 +347,16 @@ def test_prompt_submit_unknown_session_logs_warning(caplog):})- assert resp == {- "jsonrpc": "2.0",- "id": "r1",- "error": {"code": 4001, "message": "session not found"},- }+ assert resp["id"] == "r1"+ assert resp["error"]["code"] == 4001+ # The runtime id and method name must be in the warning so a client looping+ # on a stale runtime id is attributable from logs (exact wording not pinned).assert any(- "session-scoped RPC rejected" in rec.message and "gone-sid" in rec.message+ rec.levelno >= logging.WARNING+ and "gone-sid" in rec.getMessage()+ and "prompt.submit" in rec.getMessage()for rec in caplog.records)- # The method name must be in the line. Without it this warning cannot- # identify WHICH client call is looping on a stale runtime id — the gap- # that made a 5s `process.list` poll storm (18,614 rejections against one- # id) unattributable from the logs alone.- assert any(- "method=prompt.submit" in rec.message for rec in caplog.records- )def test_prompt_submit_fails_open_inline_when_compute_host_dispatch_breaks(monkeypatch):@@ -1195,7 +1173,7 @@ def test_write_json_unserializable_payload_becomes_error_frame(monkeypatch, caplframe = json.loads("".join(out.parts))assert frame["id"] == "profiles" and frame["error"]["code"] == -32603assert "datetime" in frame["error"]["message"]- assert "frame serialization failed" in caplog.text+ assert any(rec.levelno >= logging.ERROR for rec in caplog.records)def test_write_json_drops_detached_ws_frames(monkeypatch):@@ -1467,56 +1445,6 @@ def test_usage_ticker_unbounded_join_waits_out_blocked_emit(monkeypatch):assert order == ["session.usage", "message.complete"]-def test_run_prompt_submit_joins_ticker_without_timeout(monkeypatch):- """_run_prompt_submit must join the ticker with NO timeout. A timed join- can expire while a tick sits in a stalled transport write (up to- _WS_WRITE_TIMEOUT_S = 10s) and abandon it to land after message.complete;- the wait is bounded by that same write anyway — message.complete's own- emit would stall on the same transport."""- joins: list = []- real_ticker = server._start_usage_ticker-- class _JoinSpy:- def __init__(self, thread):- self._thread = thread-- def join(self, timeout=None):- joins.append(timeout)- return self._thread.join(timeout)-- def __getattr__(self, name):- return getattr(self._thread, name)-- def _spying_ticker(sid, agent, interval=1.0):- stop, thread = real_ticker(sid, agent, interval=interval)- return stop, _JoinSpy(thread)-- monkeypatch.setattr(server, "_start_usage_ticker", _spying_ticker)- monkeypatch.setattr(server.threading, "Thread", _ImmediateThread)- monkeypatch.setattr(server, "_emit", lambda event_type, sid, payload=None: None)- monkeypatch.setattr(server, "make_stream_renderer", lambda cols: None)- monkeypatch.setattr(server, "render_message", lambda raw, cols: None)- monkeypatch.setattr(server, "_get_db", lambda: None)-- class _Agent:- def run_conversation(- self, prompt, conversation_history=None, stream_callback=None- ):- return {"final_response": "done", "messages": [], "completed": True}-- server._sessions["sid"] = _session(agent=_Agent())- try:- server.handle_request(- {- "id": "1",- "method": "prompt.submit",- "params": {"session_id": "sid", "text": "hello"},- }- )- finally:- server._sessions.pop("sid", None)-- assert joins == [None], f"expected one unbounded join, got {joins}"def test_tui_verbose_tool_details_fail_closed_when_redaction_fails(monkeypatch):@@ -1539,7 +1467,6 @@ def test_tui_verbose_tool_details_are_capped_before_emit(monkeypatch):capped = server._cap_tui_verbose_text("one\ntwo\nthree\nfour")- assert capped.startswith("[showing verbose tail; omitted ")assert capped.endswith("three\nfour")assert "one" not in capped@@ -1549,13 +1476,10 @@ def test_tui_verbose_default_cap_stays_small(monkeypatch):# rendered into a persisted, expanded-by-default trail block for the whole# session. Raising this cap back toward the old 16KB re-introduces the Ink# render-tree blowup that silently OOM-killed the TUI. Keep it small.- assert server._TUI_VERBOSE_TEXT_MAX_CHARS <= 2_000-huge = "x" * 40_000capped = server._cap_tui_verbose_text(huge)assert len(capped) < 2_000- assert capped.startswith("[showing verbose tail; omitted ")def test_tui_verbose_tool_events_omit_details_when_redaction_fails(monkeypatch):@@ -1666,43 +1590,17 @@ def test_tui_non_interactive_tool_lifecycle_stays_hidden_when_tool_progress_off(def test_dispatch_rejects_non_object_request():resp = server.dispatch([])- assert resp == {- "jsonrpc": "2.0",- "id": None,- "error": {"code": -32600, "message": "invalid request: expected an object"},- }+ assert resp["id"] is None+ assert resp["error"]["code"] == -32600def test_dispatch_rejects_non_object_params():resp = server.dispatch({"id": "1", "method": "session.create", "params": []})- assert resp == {- "jsonrpc": "2.0",- "id": "1",- "error": {"code": -32602, "message": "invalid params: expected an object"},- }-+ assert resp["id"] == "1"+ assert resp["error"]["code"] == -32602-def test_system_battery_returns_reading(monkeypatch):- monkeypatch.setitem(- sys.modules,- "agent.battery",- types.SimpleNamespace(- read_battery=lambda: types.SimpleNamespace(- available=True, percent=77, plugged=False- ),- battery_category=lambda _s: "good",- ),- )- resp = server.dispatch({"id": "b1", "method": "system.battery", "params": {}})-- assert resp["result"] == {- "available": True,- "percent": 77,- "plugged": False,- "category": "good",- }def test_system_battery_fails_open(monkeypatch):@@ -1786,44 +1684,6 @@ def test_voice_toggle_returns_configured_record_key(monkeypatch):assert status_resp["result"]["record_key"] == "ctrl+o"-def test_voice_toggle_on_carries_stop_hint(monkeypatch):- """voice.toggle action=on returns the spoken-stop hint for clients to- render — sourced from voice.stop_phrases so a custom phrase shows- correctly, and empty when the feature is disabled (stop_phrases: [])."""- monkeypatch.setattr(server, "_load_cfg", lambda: {"voice": {}})- monkeypatch.setitem(- sys.modules,- "tools.voice_mode",- types.SimpleNamespace(check_voice_requirements=lambda: {"available": True, "details": ""}),- )- monkeypatch.setitem(- sys.modules,- "tools.voice_mode_transcript",- types.SimpleNamespace(voice_stop_hint=lambda: 'Say "halt" to end the voice chat.'),- )- monkeypatch.setenv("HERMES_VOICE", "0")-- on_resp = _dispatch_sync(- {"id": "voice-on", "method": "voice.toggle", "params": {"action": "on"}}- )- assert on_resp["result"]["stop_hint"] == 'Say "halt" to end the voice chat.'-- # Disabled stop phrases → empty hint, clients show nothing.- monkeypatch.setitem(- sys.modules,- "tools.voice_mode_transcript",- types.SimpleNamespace(voice_stop_hint=lambda: ""),- )- on_resp = _dispatch_sync(- {"id": "voice-on2", "method": "voice.toggle", "params": {"action": "on"}}- )- assert on_resp["result"]["stop_hint"] == ""-- # off carries no hint text (mode is ending).- off_resp = _dispatch_sync(- {"id": "voice-off", "method": "voice.toggle", "params": {"action": "off"}}- )- assert off_resp["result"]["stop_hint"] == ""def test_voice_toggle_handles_non_dict_voice_cfg(monkeypatch):@@ -2025,26 +1885,6 @@ def test_prompt_submit_typed_stop_passes_through_when_voice_off(monkeypatch):assert resp.get("result") != {"voice_stopped": True}-def test_prompt_submit_longer_text_not_consumed_in_voice_mode(monkeypatch):- """"stop the build" while voice is on must reach the agent path."""- monkeypatch.setitem(- sys.modules,- "tools.voice_mode",- types.SimpleNamespace(- is_voice_stop_phrase=lambda t: t.strip().lower().strip(".!?") == "stop"- ),- )- monkeypatch.setenv("HERMES_VOICE", "1")-- resp = server.dispatch(- {- "id": "typed-long",- "method": "prompt.submit",- "params": {"session_id": "missing-sid", "text": "stop the build"},- }- )-- assert resp.get("result") != {"voice_stopped": True}def test_wake_owner_is_sticky_and_routes_detection_to_first_transport(monkeypatch):@@ -2312,61 +2152,6 @@ def test_wake_toggle_persists_enabled_flag_only_on_explicit_gesture(monkeypatch)server._wake_owner_surface = ""-def test_wake_status_reports_configured_input_device_and_windows_silence_hint(monkeypatch):- from tools import wake_word-- config = {- "enabled": True,- "phrase": "hey hermes",- "provider": "openwakeword",- "surface": "gui",- "input_device": "Microphone Array",- }- device = {- "selector": "Microphone Array",- "name": "Microphone Array",- "hostapi": "Windows WASAPI",- "default_samplerate": 48000.0,- }- transport = types.SimpleNamespace(_closed=False)-- monkeypatch.setattr(wake_word, "load_wake_word_config", lambda: config)- monkeypatch.setattr(- wake_word,- "check_wake_word_requirements",- lambda cfg: {- "available": True,- "hint": "",- "phrase": "hey hermes",- "provider": "openwakeword",- },- )- monkeypatch.setattr(wake_word, "get_input_device_status", lambda cfg: device)- monkeypatch.setattr(wake_word, "owns_listener", lambda owner: owner is transport)- monkeypatch.setattr(wake_word, "is_listening", lambda: True)- monkeypatch.setattr(wake_word, "audio_is_silent", lambda: True)- monkeypatch.setattr(- wake_word,- "silent_audio_hint",- lambda details: f"silent input: {details['name']} ({details['hostapi']})",- )-- server._wake_owner_transport = transport- server._wake_owner_surface = "gui"- try:- response = _dispatch_sync(- {"id": "wake-status", "method": "wake.status", "params": {}},- transport=transport,- )- assert response["result"]["configured_surface"] == "gui"- assert response["result"]["input_device"] == device- assert response["result"]["audio_silent"] is True- assert response["result"]["hint"] == (- "silent input: Microphone Array (Windows WASAPI)"- )- finally:- server._wake_owner_transport = None- server._wake_owner_surface = ""def test_voice_record_start_forwards_max_recording_seconds(monkeypatch):@@ -2612,9 +2397,7 @@ def test_load_enabled_toolsets_rejects_disabled_mcp_env(monkeypatch, capsys):assert "kanban" not in resultassert set(result) - {"memory", "project"} <= _RECENTLY_SHIPPED_TOOLSETSerr = capsys.readouterr().err- assert "ignoring disabled MCP servers" in errassert "mcp-off" in err- assert "using configured CLI toolsets" in errdef test_load_enabled_toolsets_falls_back_when_tui_env_invalid(monkeypatch, capsys):@@ -2638,7 +2421,7 @@ def test_load_enabled_toolsets_falls_back_when_tui_env_invalid(monkeypatch, capsassert {"memory", "project"} <= set(result)assert "kanban" not in resultassert set(result) - {"memory", "project"} <= _RECENTLY_SHIPPED_TOOLSETS- assert "using configured CLI toolsets" in capsys.readouterr().err+ assert capsys.readouterr().err.strip() # a fallback warning is printeddef test_load_enabled_toolsets_warns_when_config_fallback_fails(monkeypatch, capsys):@@ -2656,7 +2439,7 @@ def test_load_enabled_toolsets_warns_when_config_fallback_fails(monkeypatch, cap)assert server._load_enabled_toolsets() is None- assert "could not be loaded" in capsys.readouterr().err+ assert capsys.readouterr().err.strip() # a warning is printeddef test_load_enabled_toolsets_honors_builtin_env_if_config_fails(monkeypatch):@@ -2677,13 +2460,6 @@ def test_load_enabled_toolsets_all_env_means_all(monkeypatch):assert server._load_enabled_toolsets() is None-def test_load_enabled_toolsets_all_env_warns_about_ignored_extra_entries(- monkeypatch, capsys-):- monkeypatch.setenv("HERMES_TUI_TOOLSETS", "all,nope")-- assert server._load_enabled_toolsets() is None- assert "ignoring additional entries: nope" in capsys.readouterr().errdef test_load_enabled_toolsets_reports_disabled_mcp_separately(monkeypatch, capsys):@@ -2704,8 +2480,7 @@ def test_load_enabled_toolsets_reports_disabled_mcp_separately(monkeypatch, capsassert server._load_enabled_toolsets() == ["web"]err = capsys.readouterr().err- assert "ignoring unknown HERMES_TUI_TOOLSETS entries: nope" in err- assert "ignoring disabled MCP servers" in err+ assert "nope" in errassert "mcp-off" in err@@ -2880,16 +2655,6 @@ def test_tool_start_ships_full_args(monkeypatch):assert "args" not in events[1][2]-def test_tool_ctx_sends_an_arg_preview_not_a_phrased_label():- # Clients phrase their own verb around this string: the TUI renders- # `Terminal("<ctx>")` and the desktop prepends "Running"/"Ran". Sending a- # pre-phrased label made both stutter ("Ran Running sleep 70 + 2 commands")- # and stood in for the real command in the desktop's `$` transcript.- assert server._tool_ctx("terminal", {"command": 'sleep 70; echo "a"; echo "b"'}) == (- "sleep 70 + 2 commands"- )- assert server._tool_ctx("read_file", {"path": "/tmp/demo/package.json"}) == "package.json"- assert server._tool_ctx("web_search", {"query": "weather in NYC"}) == "weather in NYC"def test_history_to_messages_keeps_reasoning_only_assistant_turn():@@ -3317,48 +3082,8 @@ def test_session_resume_uses_parent_lineage_for_display(monkeypatch, omit_messagassert resp["result"]["messages"] == expectedassert resp["result"]["message_count"] == (1 if omit_messages else 2)assert resp["result"]["messages_omitted"] is omit_messages- expected_calls = [(target, False, True)] if omit_messages else [- (target, False, False),- (target, True, False),- ]- assert captured["history_calls"] == expected_calls--def test_live_visible_history_prefers_db_display_with_candidate():- """A warm/live session must serve the persisted DISPLAY lineage, not the- collapsed in-memory model history.- Regression for #65919's cross-session fallout: verification candidates- (finish_reason=verification_required) are persisted but collapsed out of the- model working history by repair_message_sequence. Building the live-reuse- payload from ``display_history_prefix + history`` therefore dropped the- substantive answer, while the eager session.resume path still showed it —- the two payloads for the same session disagreed. This asserts the live path- now matches the eager/REST display projection by construction.- """- # In-memory model history: the candidate has been collapsed away.- in_memory = [- {"role": "user", "content": "do the thing"},- {"role": "assistant", "content": "terse verified reply"},- ]- # Persisted display lineage: the candidate (substantive answer) survives.- display_with_candidate = [- {"role": "user", "content": "do the thing"},- {"role": "assistant", "content": "long substantive answer",- "finish_reason": "verification_required"},- {"role": "assistant", "content": "terse verified reply"},- ]-- class DB:- def get_messages_as_conversation(- self, key, include_ancestors=False, repair_alternation=False, **_kwargs- ):- assert key == "s1"- assert include_ancestors is True- return list(display_with_candidate)-- result = server._live_visible_history({"session_key": "s1"}, DB(), in_memory)- assert result == display_with_candidatedef test_live_visible_history_falls_back_without_db_or_key():@@ -3953,7 +3678,6 @@ def test_session_resume_passes_stored_runtime_to_agent(monkeypatch):{"id": "1", "method": "session.resume", "params": {"session_id": "stored-session", "eager_build": True}})- assert resp["result"]["info"] == {"model": "gpt-5.4", "provider": "openai-codex"}assert captured["model_override"] == {"model": "gpt-5.4","provider": "openai-codex",@@ -4486,12 +4210,6 @@ def test_config_sync_ignores_env_seed_without_config_model(monkeypatch):server._sync_agent_model_with_config("sid", session)-def test_config_model_target_never_reads_env(monkeypatch):- monkeypatch.setenv("HERMES_MODEL", "seed/model")- monkeypatch.setenv("HERMES_INFERENCE_MODEL", "seed/model")- monkeypatch.setattr(server, "_load_cfg", lambda: {"model": {"provider": "nous"}})-- assert server._config_model_target() == ("", "nous")def test_apply_model_switch_persist_override_false_never_persists(monkeypatch):@@ -4556,25 +4274,6 @@ def test_startup_runtime_does_not_treat_inference_provider_as_explicit(monkeypatassert server._resolve_startup_runtime() == ("nous/hermes-test", None)-def test_startup_runtime_detects_provider_for_model_env(monkeypatch):- monkeypatch.setenv("HERMES_MODEL", "sonnet")- monkeypatch.delenv("HERMES_TUI_PROVIDER", raising=False)- monkeypatch.delenv("HERMES_INFERENCE_PROVIDER", raising=False)- monkeypatch.setattr(server, "_load_cfg", lambda: {"model": {"provider": "auto"}})-- def fake_detect(model, current_provider):- assert model == "sonnet"- assert current_provider == "auto"- return "anthropic", "anthropic/claude-sonnet-4.6"-- monkeypatch.setattr(- "hermes_cli.models.detect_static_provider_for_model", fake_detect- )-- assert server._resolve_startup_runtime() == (- "anthropic/claude-sonnet-4.6",- "anthropic",- )def test_load_fallback_model_merges_chain_providers_first(monkeypatch):@@ -4770,29 +4469,18 @@ def test_compute_host_turn_frame_carries_the_session_login(monkeypatch):assert frame["auth_user_id"] == "basic:alice"-def test_attaching_a_different_login_keeps_the_creator_and_warns_once(monkeypatch, caplog):+def test_attaching_a_different_login_keeps_the_creator_and_warns_once(monkeypatch):"""Ownership is not enforced. The record keeps the creator's login, and the attach is logged once with bothids rather than on every prompt the second client sends."""creator, other = _LoginSocket("alice"), _LoginSocket("bob")record = _login_session(monkeypatch, "sid-shared", "shared-key", creator)- with caplog.at_level(logging.WARNING, logger="tui_gateway.server"):- assert server._attach_session_transport(record, other)- assert server._attach_session_transport(record, other)+ assert server._attach_session_transport(record, other)+ assert server._attach_session_transport(record, other)- warnings = [rec.getMessage() for rec in caplog.records if "basic:bob" in rec.getMessage()]- assert len(warnings) == 1- assert "basic:alice" in warnings[0] and "shared-key" in warnings[0]assert server._session_auth_user_id(record) == "basic:alice"-def test_attaching_the_same_login_again_does_not_warn(monkeypatch, caplog):- record = _login_session(monkeypatch, "sid-same", "same-key", _LoginSocket("alice"))-- with caplog.at_level(logging.WARNING, logger="tui_gateway.server"):- assert server._attach_session_transport(record, _LoginSocket("alice"))-- assert not [rec for rec in caplog.records if "logged in as" in rec.getMessage()]def test_background_agent_kwargs_preserves_full_fallback_chain(monkeypatch):@@ -5157,7 +4845,6 @@ def test_session_resume_does_not_rebind_after_client_gone_interrupt_claim(monkeyassert response is not Noneassert response["error"]["code"] == 4009- assert response["error"]["message"] == "session disconnect interrupt settling"assert session["transport"] is server._detached_ws_transportfinally:server._sessions.pop("live-sid", None)@@ -5287,34 +4974,6 @@ def test_ws_disconnect_running_sidecar_still_closes_without_orphan_timer(monkeypserver._sessions.pop("sidecar-sid", None)-def test_ws_orphan_reap_closes_worker_when_session_stays_detached(monkeypatch):- """A detached WS session past its grace window has its slash_worker closed.-- Regression for #38591 fallout: every dashboard refresh spawned a fresh- session + _SlashWorker but never reaped the previous one, leaking one- python subprocess per refresh.- """- closed = {"worker": False}-- class _FakeWorker:- def close(self):- closed["worker"] = True-- server._sessions["orphan-sid"] = _session(- transport=server._detached_ws_transport,- slash_worker=_FakeWorker(),- running=False,- )- # Run the reap body synchronously (no real timer/grace) to assert behaviour.- monkeypatch.setattr(server, "_WS_ORPHAN_REAP_GRACE_S", 0.01)- try:- # Directly invoke the orphaned-check + teardown the timer would run.- assert server._ws_session_is_orphaned(server._sessions["orphan-sid"]) is True- session = server._sessions.pop("orphan-sid")- server._teardown_session(session)- assert closed["worker"] is True- finally:- server._sessions.pop("orphan-sid", None)def test_ws_orphan_reap_releases_resume_lock_before_slow_teardown(monkeypatch):@@ -5333,7 +4992,7 @@ def test_ws_orphan_reap_releases_resume_lock_before_slow_teardown(monkeypatch):def _slow_teardown(_session, *, end_reason="tui_close"):assert end_reason == "ws_orphan_reap"teardown_started.set()- assert release_teardown.wait(timeout=2.0)+ assert release_teardown.wait(timeout=10.0)monkeypatch.setattr(server, "_WS_ORPHAN_REAP_GRACE_S", 0.01)monkeypatch.setattr(server.threading, "Timer", _Timer)@@ -5348,15 +5007,15 @@ def test_ws_orphan_reap_releases_resume_lock_before_slow_teardown(monkeypatch):thread.start()acquired = Falsetry:- assert teardown_started.wait(timeout=1.0)+ assert teardown_started.wait(timeout=10.0)assert "slow-orphan" not in server._sessions- acquired = server._session_resume_lock.acquire(timeout=0.2)+ acquired = server._session_resume_lock.acquire(timeout=2.0)assert acquired, "orphan teardown kept the global resume lock held"finally:if acquired:server._session_resume_lock.release()release_teardown.set()- thread.join(timeout=2.0)+ thread.join(timeout=10.0)server._sessions.pop("slow-orphan", None)assert not thread.is_alive()@@ -5859,12 +5518,6 @@ def test_superseded_runtime_finalized_without_reclaimed_broadcast(monkeypatch):server._pending_ws_reaps.pop("new-sid", None)-def test_superseded_by_resume_is_recoverable_end_reason():- from hermes_state_common import _RECOVERABLE_END_REASONS-- assert "superseded_by_resume" in _RECOVERABLE_END_REASONS- # And quiet: it must NOT trigger the session.reclaimed broadcast.- assert "superseded_by_resume" not in server._RECLAIM_END_REASONSdef test_lazy_unpersisted_resume_rebinds_transport_and_cancels_reap(monkeypatch):@@ -6561,7 +6214,6 @@ def test_prompt_submit_refuses_boolean_ordinal(monkeypatch):)assert resp.get("error") is not Noneassert resp["error"]["code"] == 4004- assert "must be an integer" in resp["error"]["message"]assert server._sessions["bool-trunc-sid"]["history"] == historyfinally:server._sessions.pop("bool-trunc-sid", None)@@ -6601,7 +6253,6 @@ def test_prompt_submit_refuses_confirm_truncate_without_target(monkeypatch):)assert resp.get("error") is not Noneassert resp["error"]["code"] == 4004- assert "confirm_truncate requires" in resp["error"]["message"]assert server._sessions["bare-confirm-sid"]["history"] == historyfinally:server._sessions.pop("bare-confirm-sid", None)@@ -6819,7 +6470,6 @@ def test_prompt_submit_refuses_ordinal_and_message_id_mismatch(monkeypatch):)assert resp.get("error") is not Noneassert resp["error"]["code"] == 4030- assert "does not match" in resp["error"]["message"]finally:server._sessions.pop("mismatch-trunc-sid", None)@@ -7053,7 +6703,6 @@ def test_prompt_submit_refuses_ordinal_and_row_id_mismatch(monkeypatch):)assert resp.get("error") is not Noneassert resp["error"]["code"] == 4030- assert "does not match" in resp["error"]["message"]finally:server._sessions.pop("row-mismatch-sid", None)@@ -7080,7 +6729,6 @@ def test_prompt_submit_refuses_boolean_row_id(monkeypatch):)assert resp.get("error") is not Noneassert resp["error"]["code"] == 4004- assert "must be an integer" in resp["error"]["message"]finally:server._sessions.pop("bool-row-sid", None)@@ -7106,7 +6754,6 @@ def test_prompt_submit_row_id_not_found(monkeypatch):)assert resp.get("error") is not Noneassert resp["error"]["code"] == 4018- assert "no longer in session history" in resp["error"]["message"]finally:server._sessions.pop("missing-row-sid", None)@@ -7357,7 +7004,7 @@ def test_notification_poller_live_loop_requeues_foreign_completion_for_owner()assert len(delivered["a"]) == 1- assert "proc-live-handoff completed normally" in delivered["a"][0]+ assert "proc-live-handoff" in delivered["a"][0]assert delivered["b"] == []assert isolated_queue.empty()finally:@@ -8745,8 +8392,6 @@ def test_pet_info_known_revision_elides_spritesheet(monkeypatch):assert resp["result"]["spritesheetBase64"] == "A" * 1024-def test_desktop_contract_includes_approval_mode_rpc():- assert server.DESKTOP_BACKEND_CONTRACT >= 3def test_config_set_approval_mode_rejects_unknown_value():@@ -8905,7 +8550,6 @@ def test_config_set_fast_rejects_unsupported_model(monkeypatch):})assert resp["error"]["code"] == 4002- assert "not available" in resp["error"]["message"]assert agent.service_tier is Noneassert agent.request_overrides == {}assert writes == []@@ -8935,7 +8579,6 @@ def test_config_set_fast_rejects_missing_model(monkeypatch):})assert resp["error"]["code"] == 4002- assert "without a selected model" in resp["error"]["message"]assert agent.service_tier is Noneassert agent.request_overrides == {}assert writes == []@@ -9212,12 +8855,6 @@ def test_enable_gateway_prompts_sets_gateway_env(monkeypatch):assert server.os.environ["HERMES_INTERACTIVE"] == "1"-def test_setup_status_reports_provider_config(monkeypatch):- monkeypatch.setattr("hermes_cli.main._has_any_provider_configured", lambda **_kw: False)-- resp = server.handle_request({"id": "1", "method": "setup.status", "params": {}})-- assert resp["result"]["provider_configured"] is Falsedef test_setup_status_answers_from_the_bootstrap_record_once_it_exists(monkeypatch):@@ -9255,21 +8892,18 @@ def test_invalid_params_and_unknown_method_name_the_version_skew_fix():resp = server.handle_request({"id": "1", "method": "no.such.method", "params": {}})assert resp["error"]["code"] == -32601assert resp["error"]["message"].startswith("unknown method: no.such.method")- assert "hermes update" in resp["error"]["message"]resp = server.handle_request({"id": "2", "method": "session.status", "params": {"session_id": "x", "turn_author": "y"}})assert resp["error"]["code"] == 4000assert resp["error"]["message"].startswith("invalid params for session.status: turn_author")- assert "hermes update" in resp["error"]["message"]def test_probe_credentials_emits_exact_empty_key_warning():agent = types.SimpleNamespace(api_key="", provider="openrouter")- assert server._probe_credentials(agent) == (- "No API key configured for provider 'openrouter'. First message will fail."- )+ warning = server._probe_credentials(agent)+ assert warning and "openrouter" in warningdef test_probe_credentials_allows_keyless_custom_runtime():@@ -9292,13 +8926,12 @@ def test_setup_runtime_check_rejects_empty_runtime_key(monkeypatch):resp = server.handle_request({"id": "1", "method": "setup.runtime_check", "params": {}})- assert resp["result"] == {- "ok": False,- "provider": "openrouter",- "model": "openrouter/test-model",- "source": "env/config",- "error": "No usable credentials found for openrouter.",- }+ result = resp["result"]+ assert result["ok"] is False+ assert (result["provider"], result["model"], result["source"]) == (+ "openrouter", "openrouter/test-model", "env/config"+ )+ assert result["error"]def test_setup_runtime_check_allows_no_key_custom_runtime(monkeypatch):@@ -9509,24 +9142,8 @@ def test_setup_readiness_unknown_profile_never_answers_for_launch_profile(monkeyresp = server.handle_request({"id": "1", "method": method, "params": {"profile": "ghost"}})assert resp["result"]["ok"] is Falseassert resp["result"]["profile"] == "ghost"- assert "does not exist" in resp["result"]["error"]-def test_complete_slash_drops_removed_provider_alias():- # `/provider` was folded into a single `/model` command, so autocomplete- # must no longer offer the dead alias...- resp = server.handle_request(- {"id": "1", "method": "complete.slash", "params": {"text": "/pro"}}- )-- assert not any(item["text"] == "provider" for item in resp["result"]["items"])-- # ...while `/model` stays the canonical command.- resp_model = server.handle_request(- {"id": "2", "method": "complete.slash", "params": {"text": "/mod"}}- )-- assert any(item["text"] == "model" for item in resp_model["result"]["items"])def test_complete_slash_returns_plain_string_fields():@@ -9549,21 +9166,9 @@ def test_complete_slash_returns_plain_string_fields():assert isinstance(item["meta"], str), item-def test_complete_slash_includes_tui_details_command():- resp = server.handle_request(- {"id": "1", "method": "complete.slash", "params": {"text": "/det"}}- )- assert any(item["text"] == "/details" for item in resp["result"]["items"])-def test_complete_slash_includes_tui_mouse_command():- resp = server.handle_request(- {"id": "1", "method": "complete.slash", "params": {"text": "/mou"}}- )-- assert any(item["text"] == "/mouse" for item in resp["result"]["items"])-def test_complete_slash_details_args():resp_root = server.handle_request(@@ -9586,13 +9191,6 @@ def test_complete_slash_details_args():assert any(item["text"] == "expanded" for item in resp_mode["result"]["items"])-def test_complete_slash_reasoning_includes_current_efforts_and_global_scope():- resp = server.handle_request(- {"id": "1", "method": "complete.slash", "params": {"text": "/reasoning "}}- )-- values = {item["text"] for item in resp["result"]["items"]}- assert {"max", "ultra", "--global"} <= values_SLASH_FILLER_COUNT = 60@@ -9883,26 +9481,6 @@ def test_config_set_model_waits_for_lazy_agent_before_switch(monkeypatch):finally:server._sessions.pop("sid", None)-def test_config_set_model_uses_live_switch_path(monkeypatch):- server._sessions["sid"] = _session()- seen = {}-- def _fake_apply(sid, session, raw, **_kwargs):- seen["args"] = (sid, session["session_key"], raw)- return {"value": "new/model", "warning": "catalog unreachable"}-- monkeypatch.setattr(server, "_apply_model_switch", _fake_apply)- resp = server.handle_request(- {- "id": "1",- "method": "config.set",- "params": {"session_id": "sid", "key": "model", "value": "new/model"},- }- )-- assert resp["result"]["value"] == "new/model"- assert resp["result"]["warning"] == "catalog unreachable"- assert seen["args"] == ("sid", "session-key", "new/model")def test_config_set_model_requires_confirmation_for_expensive_model(monkeypatch):@@ -9952,7 +9530,6 @@ def test_config_set_model_requires_confirmation_for_expensive_model(monkeypatch))assert resp["result"]["confirm_required"] is True- assert "did you mean to select openai/gpt-5.5?" in resp["result"]["confirm_message"]assert agent.switched is Falseconfirmed = server.handle_request(@@ -10700,7 +10277,6 @@ def test_config_set_model_once_requires_live_session(monkeypatch):)assert resp["error"]["code"] == 5001- assert "/model --once requires a live session" in resp["error"]["message"]def test_config_set_model_sessionless_rejected(monkeypatch):@@ -10856,7 +10432,6 @@ def test_config_set_personality_rejects_unknown_name(monkeypatch):)assert "error" in resp- assert "Unknown personality" in resp["error"]["message"]def test_config_set_personality_preserves_history_and_returns_info(monkeypatch):@@ -11189,9 +10764,6 @@ def test_session_compress_reports_aborted_summary_without_success(monkeypatch):assert result["status"] == "aborted"assert result["removed"] == 0assert result["summary"]["aborted"] is True- assert result["summary"]["headline"] == (- "Compression aborted: 6 messages preserved"- )assert "no API key was found" in result["summary"]["note"]assert "Compressed:" not in result["summary"]["headline"]finally:@@ -11360,10 +10932,10 @@ def test_slash_exec_r7_read_commands_use_metadata_mirror_flag_on(monkeypatch):monkeypatch.setattr(server, "_load_cfg", lambda: {"dashboard": {"turn_isolation": True}})cases = {- "usage": "Total tokens: 140",+ "usage": "140","history": "live question from state db","prompt": "host system prompt",- "status": "Tokens: 140",+ "status": "140","context": "Context usage: 80 / 1,000 tokens","tools": "terminal","help": "/status",@@ -11677,7 +11249,6 @@ def test_file_attach_errors_when_unresolvable_and_no_bytes(monkeypatch, tmp_path)assert "error" in resp- assert "no data_url" in resp["error"]["message"]finally:server._sessions.pop("sid", None)@@ -11811,17 +11382,6 @@ def test_commands_catalog_survives_an_unreadable_usage_sidecar(monkeypatch):)-def test_commands_catalog_includes_tui_mouse_command():- resp = server.handle_request(- {"id": "1", "method": "commands.catalog", "params": {}}- )-- pairs = dict(resp["result"]["pairs"])- tui_cat = next(c for c in resp["result"]["categories"] if c["name"] == "TUI")- tui_pairs = dict(tui_cat["pairs"])-- assert "/mouse" in pairs- assert "/mouse" in tui_pairsdef test_commands_catalog_has_no_duplicate_or_alias_colliding_names():@@ -11859,7 +11419,6 @@ def test_commands_catalog_filters_gateway_only_commands_and_keeps_status_visibleassert "/status" in pairsassert canon["/status"] == "/status"assert "/approvals" in pairs- assert resp["result"]["sub"]["/approvals"] == ["manual", "smart", "off"]assert "/topic" not in pairsassert "/approve" not in pairs@@ -11881,9 +11440,6 @@ def test_commands_catalog_includes_desktop_meta_without_skills():)commands = resp["result"]["commands"]- assert commands["/review"] == {"argument_mode": "text", "desktop": None}- assert commands["/clear"]["desktop"] == "terminal"- assert commands["/model"]["desktop"] == "hidden"assert commands["/compact"]["argument_mode"] == commands["/compress"]["argument_mode"]for skill in resp["result"]["skills"]:@@ -11968,12 +11524,8 @@ def test_session_status_reads_live_gateway_agent(monkeypatch):server._sessions.pop("sid", None)out = resp["result"]["output"]- assert "Hermes TUI Status" in out- assert "Session ID: session-key" in out- assert "Title: Live TUI" in out- assert "Model: live-model (live-provider)" in out- assert "Tokens: 1,234" in out- assert "Agent Running: Yes" in out+ for value in ("session-key", "Live TUI", "live-model", "live-provider", "1,234"):+ assert value in outdef test_session_status_reads_live_compute_host_metadata(monkeypatch):@@ -12035,9 +11587,7 @@ def test_skills_reload_runs_in_gateway_process(monkeypatch):resp = server.handle_request({"id": "1", "method": "skills.reload", "params": {}})- assert called["result"]["total"] == 42assert "new-skill" in resp["result"]["output"]- assert "42 skill(s) available" in resp["result"]["output"]def test_snapshot_restore_is_blocked_from_tui_worker():@@ -12096,51 +11646,10 @@ def test_command_dispatch_exec_nonzero_surfaces_error(monkeypatch):assert "failed" in resp["error"]["message"]-def test_plugins_list_surfaces_loader_error(monkeypatch):- with patch("hermes_cli.plugins.get_plugin_manager", side_effect=Exception("boom")):- resp = server.handle_request(- {"id": "1", "method": "plugins.list", "params": {}}- )-- assert "error" in resp- assert "boom" in resp["error"]["message"]---def test_complete_slash_surfaces_completer_error(monkeypatch):- with patch(- "hermes_cli.commands_completion.SlashCommandCompleter",- side_effect=Exception("no completer"),- ):- resp = server.handle_request(- {"id": "1", "method": "complete.slash", "params": {"text": "/mo"}}- )-- assert "error" in resp- assert "no completer" in resp["error"]["message"]--def test_input_detect_drop_attaches_image(monkeypatch):- fake_cli = types.ModuleType("cli")- fake_cli._detect_file_drop = lambda raw: {- "path": Path("/tmp/cat.png"),- "is_image": True,- "remainder": "",- }- server._sessions["sid"] = _session()- monkeypatch.setitem(sys.modules, "cli", fake_cli)- resp = server.handle_request(- {- "id": "1",- "method": "input.detect_drop",- "params": {"session_id": "sid", "text": "/tmp/cat.png"},- }- )- assert resp["result"]["matched"] is True- assert resp["result"]["is_image"] is True- assert resp["result"]["text"] == "[User attached image: cat.png]"def test_input_detect_drop_path_with_spaces(tmp_path):@@ -12747,20 +12256,6 @@ def test_session_redirect_rejects_when_idle_without_agent(monkeypatch):assert session.get("queued_prompt") is None-def test_session_info_includes_mcp_servers(monkeypatch):- fake_status = [- {"name": "github", "transport": "http", "tools": 12, "connected": True},- {"name": "filesystem", "transport": "stdio", "tools": 4, "connected": True},- {"name": "broken", "transport": "stdio", "tools": 0, "connected": False},- ]- fake_mod = types.ModuleType("tools.mcp_tool_discovery")- fake_mod.get_mcp_status = lambda: fake_status- monkeypatch.setitem(sys.modules, "tools.mcp_tool_discovery", fake_mod)-- info = server._session_info(types.SimpleNamespace(tools=[], model="", provider="openai-codex"))-- assert info["provider"] == "openai-codex"- assert info["mcp_servers"] == fake_statusdef test_session_info_includes_session_title(monkeypatch):@@ -12843,7 +12338,6 @@ def test_session_undo_rejects_while_running():)assert resp.get("error"), "session.undo should reject while running"assert resp["error"]["code"] == 4009- assert "session busy" in resp["error"]["message"]# History must be unchangedassert len(server._sessions["sid"]["history"]) == 2finally:@@ -13430,7 +12924,6 @@ def test_prompt_submit_truncation_signals_busy_instead_of_queueing(monkeypatch):)assert resp.get("error", {}).get("code") == 4009- assert "session busy" in resp["error"]["message"]# The edit must not have been silently accepted as a queued follow-up.assert server._sessions["sid"].get("queued_prompt") is Noneassert server._sessions["sid"]["running"] is True@@ -13514,7 +13007,6 @@ def test_prompt_submit_refuses_turn_when_truncate_persist_fails(monkeypatch):)assert "error" in respassert resp["error"]["code"] == 5008- assert "truncat" in resp["error"]["message"].lower() or "persist" in resp["error"]["message"].lower()# Memory left intact — same list contents as before the refused cut.assert sess["history"] == original_historyassert sess["history_version"] == 0@@ -13768,7 +13260,6 @@ def test_prompt_submit_truncate_oor_includes_structured_user_turn_count(monkeypa)err = resp.get("error") or {}assert err.get("code") == 4018- assert "no longer in session history" in (err.get("message") or "")data = err.get("data") or {}assert data.get("user_turn_count") == 1assert data.get("ordinal") == 0@@ -14210,7 +13701,7 @@ def test_session_not_running_before_agent_ready_emits_error_event(monkeypatch):error_events = [e for e in emitted if e and len(e) >= 2 and e[0] == "error" and e[1] == "sid"]assert len(error_events) == 1, f"expected one error event, got: {emitted}"msg = error_events[0][2].get("message", "")- assert "no longer running" in msg.lower(), f"unexpected message: {msg}"+ assert msg.strip(), f"empty error message: {emitted}"finally:server._sessions.pop("sid", None)@@ -14530,13 +14021,14 @@ def test_agent_build_wait_cap_config_override(monkeypatch):assert server._agent_build_wait_cap() == 90.0monkeypatch.setattr(server, "_load_cfg", lambda: {"agent": {}})- assert server._agent_build_wait_cap() == 600.0+ default_cap = server._agent_build_wait_cap()+ assert default_cap > 0 and default_cap != 90.0monkeypatch.setattr(server, "_load_cfg", lambda: {"agent": {"build_wait_timeout": 0}})- assert server._agent_build_wait_cap() == 600.0+ assert server._agent_build_wait_cap() == default_capmonkeypatch.setattr(server, "_load_cfg", lambda: {"agent": {"build_wait_timeout": "nonsense"}})- assert server._agent_build_wait_cap() == 600.0+ assert server._agent_build_wait_cap() == default_capdef test_wait_agent_for_prompt_expires_at_cap(monkeypatch):@@ -14655,30 +14147,6 @@ def test_apply_pending_model_switch_runs_queued_pick(monkeypatch):assert calls == ["anthropic/claude-sonnet-4.6"]-def test_config_set_model_allowed_when_idle(monkeypatch):- """Regression guard: idle sessions can still switch models."""- seen = {"called": False}-- def _fake_apply(sid, session, raw, **_kwargs):- seen["called"] = True- return {"value": "newmodel", "warning": ""}-- monkeypatch.setattr(server, "_apply_model_switch", _fake_apply)-- server._sessions["sid"] = _session(running=False)- try:- resp = server.handle_request(- {- "id": "1",- "method": "config.set",- "params": {"session_id": "sid", "key": "model", "value": "newmodel"},- }- )- assert resp.get("result")- assert resp["result"]["value"] == "newmodel"- assert seen["called"]- finally:- server._sessions.pop("sid", None)def test_mirror_slash_side_effects_rejects_mutating_commands_while_running(monkeypatch):@@ -14779,9 +14247,7 @@ def test_mirror_slash_compress_does_not_prelock_history(monkeypatch):assert seen["compress"]assert seen["sync"]assert ("session.info", "sid", {"model": "x"}) in emitted- assert "Compressed:" in warning- assert "6 → 1 messages" in warning- assert "tokens" in warning+ assert warning # before/after summary returned (#46686)_PARTIAL_FAKE_HISTORY = [@@ -15290,7 +14756,6 @@ def test_prompt_submit_fails_loudly_when_store_unavailable(monkeypatch):assert resp["error"]["code"] == 5072msg = resp["error"]["message"]- assert "not saved" in msg and "hermes doctor --fix" in msgassert "utf-8 decode failure" not in msg # raw cause rides `data.details`, never the leadassert resp["error"]["data"]["code"] == "storage_unavailable"assert "utf-8 decode failure" in resp["error"]["data"]["details"]@@ -15410,9 +14875,6 @@ def test_session_list_returns_clean_error_when_state_db_is_unavailable(monkeypatresp = server.handle_request({"id": "1", "method": "session.list", "params": {}})assert "error" in resp- # Plain cause + repair command; the machine-readable code lets a GUI attach "Run doctor".- assert "Session storage is unavailable" in resp["error"]["message"]- assert "hermes doctor --fix" in resp["error"]["message"]assert resp["error"]["data"]["code"] == "storage_unavailable"assert resp["error"]["data"]["details"] == "locking protocol"@@ -15449,7 +14911,6 @@ def test_session_delete_returns_db_unavailable_when_no_db(monkeypatch):assert "error" in respassert resp["error"]["code"] == 5036- assert "Session storage is unavailable" in resp["error"]["message"]assert resp["error"]["data"]["code"] == "storage_locked"@@ -15477,7 +14938,6 @@ def test_session_delete_refuses_active_session(monkeypatch):assert "error" in respassert resp["error"]["code"] == 4023- assert "active session" in resp["error"]["message"]assert called == [], "delete_session must not be called for active sessions"@@ -15504,7 +14964,6 @@ def test_session_delete_fails_closed_when_active_snapshot_raises(monkeypatch):assert "error" in respassert resp["error"]["code"] == 5036- assert "enumerate active sessions" in resp["error"]["message"]def test_session_delete_returns_4007_when_missing(monkeypatch):@@ -15916,10 +15375,6 @@ def test_session_history_uses_session_profile_db(monkeypatch, tmp_path):assert seen.get("launch") is None# Count comes from profile-backed conversation (1 msg), not bare mem list alone.assert resp["result"]["count"] == 1- texts = []- for m in resp["result"]["messages"]:- texts.append(str(m))- assert any("from-profile" in t for t in texts) or resp["result"]["count"] == 1finally:server._sessions.pop("sid", None)@@ -16440,7 +15895,7 @@ def test_session_create_seed_disk_full_keeps_row_for_retry(monkeypatch):assert "result" in resp# The failure surfaced at WARNING (observable), not buried at debug.warnings = [r for r in records if r.levelno >= _logging.WARNING]- assert any("seeded-branch persistence failed" in r.getMessage() for r in warnings)+ assert warningsserver._sessions.pop(resp["result"]["stored_session_id"], None)@@ -16716,44 +16171,6 @@ def test_session_branch_uses_persisted_display_history_after_compaction(monkeypaserver._sessions.pop(key, None)-def test_pending_title_finalizer_uses_session_profile_db(monkeypatch, tmp_path):- """Post-turn pending_title must land in the session profile store."""- profile_home = tmp_path / "profiles" / "mlperf"- profile_home.mkdir(parents=True)- seen: dict = {}-- class LaunchDB:- def set_session_title(self, _key, _title):- seen["launch"] = True- return True-- class ProfileDB:- def __init__(self, db_path=None):- seen["db_path"] = db_path-- def set_session_title(self, key, title):- seen["set"] = (key, title)- return True-- def close(self):- seen["closed"] = True-- monkeypatch.setattr(server, "_get_db", lambda: LaunchDB())- monkeypatch.setattr("hermes_state_registry.acquire", ProfileDB)- session = {- "session_key": "ml-sess",- "pending_title": "deferred-title",- "profile_home": str(profile_home),- "history": [],- }- # Exercise the same close pattern as the post-turn finalizer.- with server._session_db(session) as db:- assert db is not None- assert db.set_session_title(session["session_key"], session["pending_title"])- session["pending_title"] = None- assert seen.get("set") == ("ml-sess", "deferred-title")- assert seen.get("launch") is None- assert session["pending_title"] is None# --------------------------------------------------------------------------@@ -16792,7 +16209,7 @@ def test_model_options_does_not_overwrite_curated_models(monkeypatch):with patch("hermes_cli.model_switch.list_authenticated_providers",return_value=curated_providers,- ) as listing:+ ):# If provider_model_ids gets called at all, the handler is still# overwriting curated with live — that's the regression we're# guarding against.@@ -16810,10 +16227,6 @@ def test_model_options_does_not_overwrite_curated_models(monkeypatch):assert nous["total_models"] == 30# Handler must not consult the live catalog — curated is the truth.live_fetch.assert_not_called()- # list_authenticated_providers is the single source.- assert listing.call_count == 1- assert listing.call_args.kwargs["probe_custom_providers"] is False- assert listing.call_args.kwargs["probe_current_custom_provider"] is Truedef test_model_options_propagates_list_exception(monkeypatch):@@ -16834,50 +16247,6 @@ def test_model_options_propagates_list_exception(monkeypatch):assert "catalog blew up" in resp["error"]["message"]-def test_model_options_hides_unconfigured_providers_by_default(monkeypatch):- from hermes_cli.inventory import ConfigContext-- calls = []-- monkeypatch.setattr(server, "_resolve_model", lambda: "")- monkeypatch.setattr(- "hermes_cli.inventory.load_picker_context",- lambda: ConfigContext(- current_provider="",- current_model="",- current_base_url="",- user_providers={},- custom_providers=[],- ),- )-- def _fake_build_models_payload(_ctx, **kwargs):- calls.append(kwargs)- return {"providers": [], "model": "", "provider": ""}-- monkeypatch.setattr(- "hermes_cli.inventory.build_models_payload",- _fake_build_models_payload,- )-- resp = server._methods["model.options"](99, {"session_id": ""})- assert "result" in resp, resp- assert calls[-1]["explicit_only"] is False- assert calls[-1]["include_unconfigured"] is False-- resp = server._methods["model.options"](- 100,- {"session_id": "", "explicit_only": True},- )- assert "result" in resp, resp- assert calls[-1]["explicit_only"] is True-- resp = server._methods["model.options"](- 101,- {"session_id": "", "include_unconfigured": True},- )- assert "result" in resp, resp- assert calls[-1]["include_unconfigured"] is Truedef test_model_options_preserves_canonical_custom_row_after_agent_init(monkeypatch):@@ -16943,11 +16312,6 @@ def test_model_options_preserves_canonical_custom_row_after_agent_init(monkeypatassert [row["slug"] for row in resp["result"]["providers"]] == ["custom:local-ollama"]- canonical.assert_called_once_with(- base_url="http://127.0.0.1:11434/v1",- config_provider="custom:local-ollama",- model="qwen3.6:35b-65k",- )def test_model_save_key_uses_credential_lifecycle_and_picker_context(monkeypatch):@@ -16999,12 +16363,6 @@ def test_model_save_key_uses_credential_lifecycle_and_picker_context(monkeypatchassert "result" in resp, respassert resp["result"]["provider"] == {**provider, "authenticated": True}save_credential.assert_called_once_with(env_var, fake_key)- picker_context.assert_called_once_with(agent)- build_payload.assert_called_once_with(- picker_ctx,- picker_hints=True,- max_models=50,- )def test_model_save_key_reconciles_the_launch_profiles_stale_setup_record(monkeypatch):@@ -17046,21 +16404,6 @@ def test_model_save_key_reconciles_the_launch_profiles_stale_setup_record(monkey# ----------------------------------------------------------------------------def test_model_options_refresh_allows_custom_provider_probes(monkeypatch):- monkeypatch.setattr(- server,- "_load_cfg",- lambda: {"providers": {}, "custom_providers": []},- )- with patch(- "hermes_cli.model_switch.list_authenticated_providers",- return_value=[],- ) as listing:- resp = server._methods["model.options"](78, {"session_id": "", "refresh": True})-- assert "result" in resp, resp- assert listing.call_args.kwargs["probe_custom_providers"] is True- assert listing.call_args.kwargs["probe_current_custom_provider"] is Falseclass _ImmediateThread:@@ -17175,11 +16518,7 @@ def test_prompt_submit_surfaces_backend_error_as_visible_text(monkeypatch):payload = complete_events[-1][2]assert payload.get("status") == "error"text = payload.get("text", "")- # Plain title first, the raw provider body demoted to a Details line, and a next step —- # never the bare "Error: <body>" as if it were the assistant's reply.- assert not text.startswith("Error:")- assert "Details: HTTP 400: invalid model id 'kimi-k2.6'" in text- assert "/retry" in text or "/model" in text+ assert "invalid model id 'kimi-k2.6'" in textassert payload.get("error") == "HTTP 400: invalid model id 'kimi-k2.6'"@@ -17751,23 +17090,6 @@ def test_browser_manage_status_falls_back_to_config_cdp_url(monkeypatch):assert resp["result"] == {"connected": True, "url": "http://lan:9222"}-def test_browser_manage_status_does_not_call_get_cdp_override(monkeypatch):- """Regression guard for Copilot's "status must not block" review:- status must NOT route through `_get_cdp_override`, which performs a- `/json/version` HTTP probe with a multi-second timeout."""- monkeypatch.setenv("BROWSER_CDP_URL", "http://127.0.0.1:9222")-- fake = types.SimpleNamespace(- _get_cdp_override=lambda: pytest.fail( # noqa: PT015 — fail loudly if called- "_get_cdp_override must not run on /browser status (network I/O)"- )- )- with patch.dict(sys.modules, {"tools.browser_tool_lifecycle": fake}):- resp = server.handle_request(- {"id": "1", "method": "browser.manage", "params": {"action": "status"}}- )-- assert resp["result"]["connected"] is Truedef test_browser_manage_connect_sets_env_and_cleans_twice(monkeypatch):@@ -17797,9 +17119,6 @@ def test_browser_manage_connect_sets_env_and_cleans_twice(monkeypatch):assert resp["result"]["connected"] is Trueassert resp["result"]["url"] == "http://127.0.0.1:9222"- assert resp["result"]["messages"] == [- "Chromium-family browser is already listening at http://127.0.0.1:9222"- ]assert os.environ.get("BROWSER_CDP_URL") == "http://127.0.0.1:9222"# First cleanup runs against the OLD env (none here), second against the NEW.assert cleanup_calls == ["", "http://127.0.0.1:9222"]@@ -17819,9 +17138,6 @@ def test_browser_manage_connect_defaults_to_loopback(monkeypatch):assert resp["result"]["connected"] is Trueassert resp["result"]["url"] == "http://127.0.0.1:9222"- assert resp["result"]["messages"] == [- "Chromium-family browser is already listening at http://127.0.0.1:9222"- ]assert urls[0] == "http://127.0.0.1:9222/json/version"@@ -17869,17 +17185,7 @@ def test_browser_manage_connect_default_local_reports_launch_hint(monkeypatch):assert resp["result"]["connected"] is Falseassert resp["result"]["url"] == "http://127.0.0.1:9222"- assert (- resp["result"]["messages"][0]- == "Chromium-family browser isn't running with remote debugging — attempting to launch..."- )- assert any(- "No supported Chromium-family browser executable was found" in line- for line in resp["result"]["messages"]- )- assert any(- "--remote-debugging-port=9222" in line for line in resp["result"]["messages"]- )+ assert resp["result"]["messages"]assert "BROWSER_CDP_URL" not in os.environprogress = [p["message"] for evt, p in emitted if evt == "browser.progress"]assert progress == resp["result"]["messages"]@@ -17960,7 +17266,6 @@ def test_browser_manage_connect_rejects_non_string_url(monkeypatch):)assert resp["error"]["code"] == 4015- assert "must be a string" in resp["error"]["message"]assert "BROWSER_CDP_URL" not in os.environ@@ -18011,10 +17316,6 @@ def test_browser_manage_connect_default_local_retries_after_launch(monkeypatch):assert resp["result"]["connected"] is Trueassert resp["result"]["url"] == "http://127.0.0.1:9222"- assert resp["result"]["messages"] == [- "Chromium-family browser isn't running with remote debugging — attempting to launch...",- "Chromium-family browser launched and listening on port 9222",- ]assert os.environ["BROWSER_CDP_URL"] == "http://127.0.0.1:9222"@@ -18103,7 +17404,6 @@ def test_browser_manage_connect_squatted_port_launches_on_alternate(monkeypatch)assert resp["result"]["connected"] is Trueassert resp["result"]["url"] == "http://127.0.0.1:9223"assert os.environ["BROWSER_CDP_URL"] == "http://127.0.0.1:9223"- assert any("occupied by another application" in m for m in resp["result"]["messages"])def test_browser_manage_connect_rejects_unreachable_endpoint(monkeypatch):@@ -18264,7 +17564,6 @@ def test_browser_manage_connect_rejects_invalid_port(monkeypatch):)assert resp["error"]["code"] == 4015- assert "invalid port" in resp["error"]["message"]assert "BROWSER_CDP_URL" not in os.environ@@ -18279,7 +17578,6 @@ def test_browser_manage_connect_rejects_missing_host(monkeypatch):)assert resp["error"]["code"] == 4015- assert "missing host" in resp["error"]["message"]assert "BROWSER_CDP_URL" not in os.environ@@ -18375,14 +17673,6 @@ def test_browser_manage_disconnect_drops_env_and_cleans(monkeypatch):# ── config.get indicator normalization ───────────────────────────────-def test_config_get_indicator_returns_known_value_verbatim(monkeypatch):- monkeypatch.setattr(- server, "_load_cfg", lambda: {"display": {"tui_status_indicator": "emoji"}}- )- resp = server.handle_request(- {"id": "1", "method": "config.get", "params": {"key": "indicator"}}- )- assert resp["result"] == {"value": "emoji"}def test_config_get_indicator_normalizes_casing_and_whitespace(monkeypatch):@@ -18412,12 +17702,6 @@ def test_config_get_indicator_falls_back_to_default_for_unknown(monkeypatch):assert resp["result"] == {"value": "kaomoji"}-def test_config_get_indicator_falls_back_when_unset(monkeypatch):- monkeypatch.setattr(server, "_load_cfg", lambda: {"display": {}})- resp = server.handle_request(- {"id": "1", "method": "config.get", "params": {"key": "indicator"}}- )- assert resp["result"] == {"value": "kaomoji"}# ── config.set indicator validation ──────────────────────────────────@@ -18441,61 +17725,13 @@ def test_config_set_indicator_accepts_known_value(monkeypatch):assert written == {"display.tui_status_indicator": "emoji"}-def test_config_set_indicator_falsy_non_string_surfaces_in_error(monkeypatch):- """`0` / `False` / `[]` are not valid styles, but the error message- must still tell the user what they sent — `value or ""` would have- erased them to a blank string."""- monkeypatch.setattr(server, "_write_config_key", lambda *a, **k: None)-- for bad in (0, False, []):- resp = server.handle_request(- {- "id": "1",- "method": "config.set",- "params": {"key": "indicator", "value": bad},- }- )- assert "error" in resp- msg = resp["error"]["message"]- assert "unknown indicator" in msg- # The exact repr varies; `0`/`False` stringify with content,- # `[]` becomes an empty list — what matters is the diagnostic- # is no longer just `unknown indicator: ` with nothing after.- assert msg.split("; ")[0] != "unknown indicator: ''"-def test_config_set_indicator_none_keeps_blank_repr(monkeypatch):- """`None` is the genuine 'no value' case — empty raw is acceptable."""- monkeypatch.setattr(server, "_write_config_key", lambda *a, **k: None)- resp = server.handle_request(- {- "id": "1",- "method": "config.set",- "params": {"key": "indicator", "value": None},- }- )- assert "error" in resp- assert "unknown indicator: ''" in resp["error"]["message"]# ── reload.env ───────────────────────────────────────────────────────-def test_reload_env_rpc_calls_hermes_cli_reload_env(monkeypatch):- """reload.env mirrors classic CLI's `/reload` — re-reads ~/.hermes/.env- into the gateway process and reports the count of vars updated."""- calls = {"n": 0}-- def _fake_reload():- calls["n"] += 1- return 7-- fake = types.SimpleNamespace(reload_env=_fake_reload)- with patch.dict(sys.modules, {"hermes_cli.config": fake}):- resp = server.handle_request({"id": "1", "method": "reload.env", "params": {}})-- assert resp["result"] == {"updated": 7}- assert calls["n"] == 1def test_reload_env_rpc_surfaces_errors(monkeypatch):@@ -18547,22 +17783,6 @@ def test_make_agent_reads_nested_max_turns(monkeypatch):assert mock_agent.call_args.kwargs["max_iterations"] == 200-def test_make_agent_waits_for_shared_mcp_discovery(monkeypatch):- _setup_make_agent_mocks(monkeypatch, {})- waited = []-- from hermes_cli import mcp_startup-- monkeypatch.setattr(- mcp_startup,- "wait_for_mcp_discovery",- lambda timeout=0.75: waited.append(timeout),- )-- with patch("run_agent.AIAgent"):- server._make_agent("sid1", "key1")-- assert waited == [0.75]def test_make_agent_nested_max_turns_takes_priority(monkeypatch):@@ -18576,13 +17796,6 @@ def test_make_agent_nested_max_turns_takes_priority(monkeypatch):assert mock_agent.call_args.kwargs["max_iterations"] == 400-def test_make_agent_defaults_to_500(monkeypatch):- _setup_make_agent_mocks(monkeypatch, {})-- with patch("run_agent.AIAgent") as mock_agent:- server._make_agent("sid1", "key1")-- assert mock_agent.call_args.kwargs["max_iterations"] == 500def test_make_agent_uses_session_runtime_overrides(monkeypatch):@@ -18671,12 +17884,6 @@ def test_background_agent_kwargs_falls_back_to_root_max_turns(monkeypatch):assert kwargs["max_iterations"] == 50-def test_background_agent_kwargs_defaults_to_25(monkeypatch):- monkeypatch.setattr(server, "_load_cfg", lambda: {})-- kwargs = server._background_agent_kwargs(_FakeAgentForBackground(), "task_1")-- assert kwargs["max_iterations"] == 25def test_background_agent_kwargs_handles_null_agent_config(monkeypatch):@@ -18687,21 +17894,6 @@ def test_background_agent_kwargs_handles_null_agent_config(monkeypatch):assert kwargs["max_iterations"] == 40-def test_config_show_displays_nested_max_turns(monkeypatch):- monkeypatch.setattr(- server,- "_load_cfg",- lambda: {"agent": {"max_turns": 120}, "enabled_toolsets": [], "verbose": False},- )- monkeypatch.setattr(server, "_resolve_model", lambda: "test-model")-- resp = server.handle_request({"id": "1", "method": "config.show", "params": {}})- sections = resp["result"]["sections"]- agent_rows = next(- section["rows"] for section in sections if section["title"] == "Agent"- )-- assert ["Max Turns", "120"] in agent_rowsdef test_notification_poller_delivers_completion(monkeypatch):@@ -18769,7 +17961,7 @@ def test_notification_poller_delivers_completion(monkeypatch):# Should have triggered an agent turnassert len(turns) == 1- assert "[IMPORTANT: Background process proc_poller_test completed normally" in turns[0]+ assert "proc_poller_test" in turns[0]finally:server._sessions.pop("sid_poll", None)while not process_registry.completion_queue.empty():@@ -19496,20 +18688,6 @@ def test_slash_exec_concurrent_first_use_spawns_single_worker(monkeypatch):server._sessions.pop("race-spawn", None)-def test_session_close_rpc_claims_then_tears_down(monkeypatch):- seen = []- claimed = {"session_key": "k"}- monkeypatch.setattr(server, "_pop_session_by_id", lambda sid: seen.append(sid) or claimed)- monkeypatch.setattr(- server,- "_teardown_popped_session",- lambda session, *, end_reason: seen.append((session, end_reason)) or True,- )- resp = server.handle_request(- {"id": "1", "method": "session.close", "params": {"session_id": "s9"}}- )- assert resp["result"] == {"closed": True}- assert seen == ["s9", (claimed, "tui_close")]def test_close_sessions_for_transport_closes_flagged_repoints_rest(monkeypatch):@@ -19746,7 +18924,7 @@ def test_periodic_trim_runs_once_every_session_is_quiescent(monkeypatch):server._sessions.update(sessions)try:server._reap_idle_sessions()- assert calls == ["idle reaper periodic trim"], sessions+ assert len(calls) == 1, sessionsfinally:server._sessions.clear()@@ -19762,7 +18940,7 @@ def test_turn_completion_trim_skips_while_another_session_is_running(monkeypatchserver._sessions["own"] = owntry:server._finish_turn("own", own, server._TurnRun(agent=None, one_turn_restore=None, terminal_callback=None, receipt_committed=True))- assert calls == ["tui turn completion"]+ assert len(calls) == 1calls.clear()server._sessions["other"] = _idle_evictable_session(now) | {"running": True}@@ -19781,7 +18959,7 @@ def test_reap_idle_sessions_logs_trim_failure(monkeypatch, caplog):try:with caplog.at_level("DEBUG", logger="tui_gateway.server"):server._reap_idle_sessions()- assert "idle reaper memory trim failed: RuntimeError: boom" in caplog.text+ assert "boom" in caplog.textfinally:server._sessions.clear()@@ -20258,17 +19436,6 @@ def test_subscription_change_requires_tier_or_cancel():assert res["error"] == "invalid_request"-def test_subscription_resume(monkeypatch):- import hermes_cli.nous_billing as nb-- monkeypatch.setattr(- nb,- "delete_subscription_pending_change",- lambda: {"rail": "stripe", "cancelAtPeriodEnd": False, "message": "Resumed."},- )- res = _sub_rpc("subscription.resume", {})- assert res["ok"] is True- assert res["message"] == "Resumed."def test_subscription_upgrade_echoes_status_and_idempotency(monkeypatch):@@ -20373,11 +19540,6 @@ def test_get_usage_includes_active_subagents(monkeypatch):assert usage["active_subagents"] == 4-def test_get_usage_active_subagents_zero(monkeypatch):- import tools.async_delegation as ad_mod- monkeypatch.setattr(ad_mod, "active_count", lambda: 0)- usage = server._get_usage(_BareAgent())- assert usage["active_subagents"] == 0def test_get_usage_safe_when_active_count_raises(monkeypatch):@@ -20443,27 +19605,6 @@ class TestResolveRuntimeWithFallback:assert resolution.selected_model == "deepseek-v4-pro"assert resolution.used_fallback is True- def test_quota_auth_error_is_logged_as_rate_limited_not_auth_failed(self, monkeypatch, caplog):- """#117482 sibling surface: a 429/quota AuthError on the primary reads as quota in the- gateway's fallback log, never as an auth failure."""- import logging-- from hermes_cli.auth import CODEX_RATE_LIMITED_CODE, AuthError-- def fake_resolve(**kwargs):- if kwargs.get("requested") == "openai-codex":- raise AuthError("quota exhausted (429)", provider="openai-codex",- code=CODEX_RATE_LIMITED_CODE, relogin_required=False)- return {"provider": "deepseek", "api_key": "fb-tok"}-- monkeypatch.setattr("hermes_cli.runtime_provider.resolve_runtime_provider", fake_resolve)- monkeypatch.setattr(server, "_load_fallback_model",- lambda: [{"provider": "deepseek", "model": "deepseek-v4-pro"}])- with caplog.at_level(logging.WARNING, logger=server.__name__):- resolution = server._resolve_runtime_with_fallback({"requested": "openai-codex"})- assert resolution.used_fallback is True- assert "Primary rate-limited (429)" in caplog.text- assert "auth failed" not in caplog.textdef test_auth_error_skips_provider_only_fallback(self, monkeypatch):"""Auth fallback requires one complete provider/model pair."""@@ -21142,16 +20283,6 @@ def test_build_persist_message_with_image_refs_appends_existing_paths(monkeypatcassert result == f"what is in this photo?\n@image:{img}"-def test_build_persist_message_keeps_the_caption_on_the_first_line(tmp_path):- """Session previews are the first 60 characters of the first user message,- so a leading directive would title the session with a truncated file path- in the sidebar, switcher, and command palette."""- img = tmp_path / "cat.png"- img.write_bytes(b"png")-- result = server._build_persist_message_with_image_refs("what is in this photo?", [str(img)])-- assert result.split("\n", 1)[0] == "what is in this photo?"def test_build_persist_message_with_image_refs_skips_missing_paths(monkeypatch, tmp_path):@@ -21305,85 +20436,6 @@ def test_prompt_submit_passes_persist_user_message_to_agent(monkeypatch):server._sessions.pop("sid", None)-def test_prompt_submit_releases_old_history_before_heap_trim(monkeypatch, tmp_path):- """The trim boundary must not retain the just-pruned history snapshots."""- import contextlib- observed = {}- cleanup_order = []-- class _Agent:- def run_conversation(- self, prompt, conversation_history=None, stream_callback=None- ):- return {- "final_response": "reply",- "messages": [{"role": "assistant", "content": "reply"}],- }-- class _ImmediateThread:- def __init__(self, target=None, daemon=None, **_thread_options):- self._target = target-- def start(self):- assert self._target is not None- self._target()-- def _inspect_trim_frame(**_kwargs):- import inspect-- cleanup_order.append("trim")- frame = inspect.currentframe()- assert frame is not None and frame.f_back is not None- caller_locals = frame.f_back.f_locals- # Loud, not vacuous: if the production locals are ever renamed, fail- # the test instead of silently reading None and "passing".- assert "history" in caller_locals and "run_kwargs" in caller_locals, (- "expected locals not found in _run_prompt_submit's finally frame — "- "renamed? update this test"- )- observed["history"] = caller_locals.get("history")- observed["run_kwargs"] = caller_locals.get("run_kwargs")-- 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"] = [- {"role": "tool", "tool_call_id": "old", "content": "x" * 20_000}- ]- 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: cleanup_order.append("reset_home"),- )- # This test observes the worker's history-release scope, not the- # separate notification-policy and post-turn scopes (covered elsewhere).- monkeypatch.setattr(server, "_session_profile_runtime_scope",- lambda _session: contextlib.nullcontext())- monkeypatch.setattr("hermes_cli.mem_trim.trim_memory", _inspect_trim_frame)-- 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 not observed["history"]- assert not observed["run_kwargs"]- assert cleanup_order == ["trim", "reset_home"]- finally:- server._sessions.pop("sid_trim", None)def test_fallback_session_info_reports_session_cwd_not_launch_dir(monkeypatch):@@ -21890,16 +20942,6 @@ def test_prompt_submit_truncation_archives_instead_of_deleting(monkeypatch):server._sessions.pop("archive-trunc-sid", None)-def test_insert_message_rows_sets_row_id_on_fresh_dicts(tmp_path):- """#82959: _insert_message_rows must assign _row_id on freshly inserted message dicts."""- from hermes_state import SessionDB- db = SessionDB(db_path=tmp_path / "state.db")- db.create_session("fresh-msg-row-id-sid", "cli")- msg = {"role": "user", "content": "fresh turn without pre-existing _row_id"}- with db._lock:- db._insert_message_rows(db._conn, "fresh-msg-row-id-sid", [msg])- assert "_row_id" in msg, "New message dict did not receive _row_id"- assert isinstance(msg["_row_id"], int) and msg["_row_id"] > 0def test_prompt_submit_unmatched_row_id_refuses_even_with_ordinal(monkeypatch):diff --git a/tests/tui_gateway/test_tui_gateway_ws.py b/tests/tui_gateway/test_tui_gateway_ws.pyindex 42d3159695a..9301b1fda2a 100644--- a/tests/tui_gateway/test_tui_gateway_ws.py+++ b/tests/tui_gateway/test_tui_gateway_ws.py@@ -3,9 +3,7 @@ import concurrent.futuresimport datetimeimport jsonimport threading-import time-from hermes_cli import mcp_startupfrom tui_gateway import serverfrom tui_gateway import ws as ws_mod@@ -123,35 +121,6 @@ def test_ws_disconnect_releases_wake_word_owner(monkeypatch):-def test_ws_starts_mcp_discovery_before_ready(monkeypatch):- import tui_gateway.entry as entry-- calls = []- events = []-- monkeypatch.setattr(server, "_WS_ORPHAN_REAP_GRACE_S", 0)- monkeypatch.setattr(entry, "ensure_mcp_discovery_started", lambda: calls.append("mcp"))-- class FakeWS:- async def accept(self):- events.append("accept")-- async def send_text(self, line):- if '"gateway.ready"' in line:- events.append(f"ready_after_{len(calls)}")-- async def receive_text(self):- raise ws_mod._WebSocketDisconnect()-- async def close(self):- pass-- asyncio.run(ws_mod.handle_ws(FakeWS()))-- # Discovery moved to profile-aware agent construction. WebSocket transport- # should not start MCP discovery before a profile has been bound.- assert calls == []- assert events == ["accept", "ready_after_0"]def test_ws_ready_advertises_heartbeat_and_ping_is_inline(monkeypatch):diff --git a/tests/tui_gateway/test_turn_finished_failure_cause.py b/tests/tui_gateway/test_turn_finished_failure_cause.pyindex dcc47ee978c..de8da4bde84 100644--- a/tests/tui_gateway/test_turn_finished_failure_cause.py+++ b/tests/tui_gateway/test_turn_finished_failure_cause.py@@ -159,17 +159,6 @@ class TestTheReportedRecordNowNamesItsCause:assert "failure_reason=RuntimeError" in msgassert "connection reset mid-stream" in msg- def test_successful_turn_stays_exactly_as_it_was(self, turn_env, caplog):- """No cost to the common case: a clean turn gains no new fields."""- session = _session(agent=_agent_returning({"final_response": "done"}))-- with caplog.at_level(logging.INFO, logger="tui_gateway.server"):- _run(session)-- msg = _finished(caplog)- assert "status=complete" in msg- assert "cause=" not in msg- assert "failure_reason=" not in msgclass TestContentDiscipline:@@ -314,10 +303,6 @@ class TestDetailHelperDirectly:assert server._turn_failure_detail("", None) == ""assert server._turn_failure_detail(None) == ""- def test_fragment_carries_its_own_leading_space(self):- """The bookend appends it unconditionally, so it must self-format."""- out = server._turn_failure_detail("boom")- assert out.startswith(" ")def test_an_exception_with_no_message_still_names_its_type(self):assert "KeyError" in server._turn_failure_detail(KeyError())diff --git a/tests/tui_gateway/test_undo_command.py b/tests/tui_gateway/test_undo_command.pyindex 9e44e23e41e..0431d046614 100644--- a/tests/tui_gateway/test_undo_command.py+++ b/tests/tui_gateway/test_undo_command.py@@ -104,7 +104,6 @@ def test_undo_returns_prefill_with_target_text(server, session_with_history):assert result["type"] == "prefill"# Default /undo backs up one user turn — "question 3"assert result["message"] == "question 3"- assert "Undid" in result["notice"]assert s["history"]assert all("_row_id" in message for message in s["history"])diff --git a/tests/tui_gateway/test_user_messages.py b/tests/tui_gateway/test_user_messages.pydeleted file mode 100644index 371a0e1620a..00000000000--- a/tests/tui_gateway/test_user_messages.py+++ /dev/null@@ -1,61 +0,0 @@-"""Behaviour contracts for the user-facing copy the gateway sends to the TUI / Desktop.--Each test asserts the message says WHAT happened and WHICH command to run next, and that-the lead phrases clients pattern-match on (``session busy``, ``unknown method:``,-``invalid params for``) survive the rewording.-"""--from __future__ import annotations--import pytest--from tui_gateway import user_messages as um---def test_turn_error_text_leads_with_a_plain_title_and_keeps_the_raw_body_on_a_details_line():- raw = 'Error code: 401 - {"error": {"message": "Incorrect API key provided", "type": "invalid_request_error"}}'- text = um.turn_error_text(raw, {"layer": "auth", "code": "auth", "retryable": False, "provider": "openai"})- title, details, hint = text.split("\n")-- assert not title.startswith("Error")- assert "401" not in title and "{" not in title- assert "API key" in title and "openai" in title- assert details.startswith("Details: ") and "Incorrect API key provided" in details- assert "/model" in hint and "/retry" in hint---def test_turn_error_text_without_a_surface_still_names_the_next_step():- text = um.turn_error_text("HTTP 400: invalid model id 'kimi-k2.6'")-- assert "kimi-k2.6" in text- assert "/retry" in text or "/model" in text- assert not text.startswith("Error:")--[email protected]("command", ["undo", "compress", "reload-mcp", "rollback restore"])-def test_busy_message_names_the_real_gesture_not_a_missing_slash_command(command):- text = um.busy_message(command)-- assert text.startswith("session busy") # clients match this lead phrase (4009)- assert "/interrupt" not in text- # Shared gateway: name both gestures, never state the terminal one as the only option.- assert "Ctrl+C" in text and "Stop button" in text- assert "Press Ctrl+C" not in text- assert f"/{command}" in text---def test_agent_init_and_resume_failures_point_at_existing_commands():- init = um.agent_init_failed_message(RuntimeError("Unknown provider 'openrouterr'"))- assert not init.startswith("agent init failed")- assert "openrouterr" in init and "/model" in init and "hermes setup" in init- assert "/setup" not in init # ui-tui-only launcher; Desktop has no such command-- resume = um.resume_failed_message(ValueError("corrupt row"))- assert not resume.startswith("resume failed")- assert "corrupt row" in resume and "/sessions" in resume and "/new" in resume- assert "/sessions new" not in resume # ui-tui-only alias; Desktop ignores the argument---def test_still_starting_copy_is_not_phrased_as_fatal():- assert "timed out" not in um.AGENT_STILL_STARTING- assert "try again" in um.AGENT_STILL_STARTING.lower()diff --git a/tests/tui_gateway/test_vault_methods.py b/tests/tui_gateway/test_vault_methods.pyindex 43ef19ccc49..f12468840d6 100644--- a/tests/tui_gateway/test_vault_methods.py+++ b/tests/tui_gateway/test_vault_methods.py@@ -85,12 +85,10 @@ def test_add_validation_errors_are_clean(home):))assert err["code"] == 5095- assert "origin is required" in err["message"]assert "s3cret-pw-9000" not in json.dumps(err)err = _error(srv._methods["vault.add"](2, {"kind": "login", "label": "x"}))assert err["code"] == 5095- assert "secret payload is required" in err["message"]err = _error(srv._methods["vault.add"](@@ -98,7 +96,6 @@ def test_add_validation_errors_are_clean(home):))assert err["code"] == 5095- assert "unknown vault kind" in err["message"]assert "s3cret-pw-9000" not in json.dumps(err)diff --git a/tests/tui_gateway/test_voice_live_delegation.py b/tests/tui_gateway/test_voice_live_delegation.pyindex 34ba98f14b7..140b9940585 100644--- a/tests/tui_gateway/test_voice_live_delegation.py+++ b/tests/tui_gateway/test_voice_live_delegation.py@@ -105,7 +105,6 @@ class TestVoiceLiveTurnNote:assert busy_session["client_surface"] == "voice-live"note = server._hud_surface_note(busy_session)assert note.startswith(voice_live.VOICE_LIVE_TURN_NOTE)- assert "spoken" in note and "no markdown" in noteassert "User: what's the weather" in notedef test_voice_context_ignored_off_the_live_surface(self, busy_session):diff --git a/tests/tui_gateway/test_ws_keepalive.py b/tests/tui_gateway/test_ws_keepalive.pyindex 10ba431e685..aaab00ff10e 100644--- a/tests/tui_gateway/test_ws_keepalive.py+++ b/tests/tui_gateway/test_ws_keepalive.py@@ -44,14 +44,6 @@ def test_ws_socket_enables_keepalive() -> None:assert opts[(socket.IPPROTO_TCP, socket.TCP_NODELAY)] == 1# Keepalive always on.assert opts[(socket.SOL_SOCKET, socket.SO_KEEPALIVE)] == 1- # Idle/interval/count tuning is platform-specific: Linux exposes- # TCP_KEEPIDLE/INTVL/CNT, macOS only TCP_KEEPALIVE (idle seconds).- if hasattr(socket, "TCP_KEEPIDLE"):- assert opts[(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE)] == 30- assert opts[(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL)] == 10- assert opts[(socket.IPPROTO_TCP, socket.TCP_KEEPCNT)] == 3- elif hasattr(socket, "TCP_KEEPALIVE"):- assert opts[(socket.IPPROTO_TCP, socket.TCP_KEEPALIVE)] == 30def test_ws_socket_unreachable_is_silent() -> None:diff --git a/tests/tui_gateway/test_ws_keepalive_config.py b/tests/tui_gateway/test_ws_keepalive_config.pyindex 8b16e1d9278..9ac80b632be 100644--- a/tests/tui_gateway/test_ws_keepalive_config.py+++ b/tests/tui_gateway/test_ws_keepalive_config.py@@ -18,15 +18,6 @@ def _write_config(home, body: str) -> None:(home / "config.yaml").write_text(textwrap.dedent(body))-def test_dashboard_ws_defaults_present(_temp_home):- from hermes_cli.config import load_config-- _write_config(_temp_home, "model:\n default: test-model\n")- cfg = load_config()- dash = cfg.get("dashboard") or {}- assert dash.get("ws_ping_interval") == 20.0- assert dash.get("ws_ping_timeout") == 20.0- assert dash.get("ws_orphan_reap_grace_s") == 20.0def test_dashboard_ws_values_propagate_from_yaml(_temp_home):@@ -47,7 +38,7 @@ def test_dashboard_ws_values_propagate_from_yaml(_temp_home):assert dash["ws_ping_timeout"] == 10assert dash["ws_orphan_reap_grace_s"] == 90# Deep-merge: sibling defaults survive a partial user section.- assert dash.get("theme") == "default"+ assert "theme" in dashdef test_ws_orphan_reap_grace_reads_config(_temp_home):diff --git a/tests/verify/test_verify_cmd.py b/tests/verify/test_verify_cmd.pyindex cebf2b49c94..1adc17d9784 100644--- a/tests/verify/test_verify_cmd.py+++ b/tests/verify/test_verify_cmd.py@@ -77,19 +77,6 @@ def test_failing_phase_exit_code(tmp_path, capsys):assert payload["ok"] is False-def test_human_report(tmp_path, capsys):- manifest = tmp_path / ".hermes"- manifest.mkdir()- (manifest / "environment.json").write_text(- json.dumps({"recipe": {"name": "Fake", "test": ["echo ok"]}}),- encoding="utf-8",- )- code = run_verify_command(make_args(tmp_path, skip_start=True))- out = capsys.readouterr().out- assert code == 0- assert "Recipe: Fake" in out- assert "PASS" in out- assert "Result: OK" in outdef test_bad_path(tmp_path, capsys):diff --git a/tests/website/test_bot_mode_zh_hans.py b/tests/website/test_bot_mode_zh_hans.pydeleted file mode 100644index b52cc7cf52b..00000000000--- a/tests/website/test_bot_mode_zh_hans.py+++ /dev/null@@ -1,62 +0,0 @@-"""Regression for issue #94366.--The zh-Hans docs tree had no translation of the Bot Mode user guide, so-zh-Hans readers silently fell back to the English page. These checks are-invariants of the translation, not a mirror of the English page: an-English-only edit (new heading, new code block) must not turn main red.-"""--from __future__ import annotations--import re-from pathlib import Path--REPO_ROOT = Path(__file__).resolve().parents[2]-EN_DOC = REPO_ROOT / "website" / "docs" / "user-guide" / "bot-mode.md"-ZH_DOC = (- REPO_ROOT- / "website"- / "i18n"- / "zh-Hans"- / "docusaurus-plugin-content-docs"- / "current"- / "user-guide"- / "bot-mode.md"-)--FRONT_MATTER_RE = re.compile(r"\A---\n(.*?)\n---\n", re.DOTALL)-CODE_BLOCK_RE = re.compile(r"```[a-zA-Z]*\n(.*?)```", re.DOTALL)-# Front matter keys Docusaurus uses for routing; they must agree between the-# source and its translation or the zh-Hans page lands on another URL.-ROUTING_KEYS = ("id", "slug")---def _front_matter(text: str) -> dict[str, str]:- match = FRONT_MATTER_RE.match(text)- assert match, "page must start with a front matter block"- pairs = (line.split(":", 1) for line in match.group(1).splitlines() if ":" in line)- return {key.strip(): value.strip() for key, value in pairs}---def _machine_readable_lines(block: str) -> tuple[str, ...]:- # Comments are translated; commands, paths, config keys and payloads are not.- return tuple(line.split("#", 1)[0].rstrip() for line in block.strip().splitlines())---def test_translation_exists_and_routes_like_the_english_page():- en_meta = _front_matter(EN_DOC.read_text(encoding="utf-8"))- zh_meta = _front_matter(ZH_DOC.read_text(encoding="utf-8"))- assert zh_meta.get("title"), "zh-Hans page needs its own title"- for key in ROUTING_KEYS:- assert zh_meta.get(key) == en_meta.get(key), f"front matter '{key}' must match the English page"---def test_code_blocks_are_copied_from_the_english_page():- en_blocks = {_machine_readable_lines(b) for b in CODE_BLOCK_RE.findall(EN_DOC.read_text(encoding="utf-8"))}- zh_blocks = [_machine_readable_lines(b) for b in CODE_BLOCK_RE.findall(ZH_DOC.read_text(encoding="utf-8"))]- assert zh_blocks, "translation lost its code blocks"- stale = [b for b in zh_blocks if b not in en_blocks]- assert not stale, (- "zh-Hans code blocks must be byte-accurate copies of blocks that still exist "- f"in the English page (translation stale for: {stale})"- )diff --git a/tests/website/test_check_doc_links.py b/tests/website/test_check_doc_links.pyindex 21face2e0da..acbb2c844b4 100644--- a/tests/website/test_check_doc_links.py+++ b/tests/website/test_check_doc_links.py@@ -24,9 +24,6 @@ def checker():return module-def test_hand_authored_docs_have_no_route_style_links(checker):- """The live tree stays clean: every route-style link 404s on GitHub."""- assert checker.main(["--en-only"]) == 0def test_fix_rewrites_route_to_relative_path_keeping_anchor(checker, tmp_path, monkeypatch):diff --git a/tests/website/test_extract_skills.py b/tests/website/test_extract_skills.pyindex 0cb2c202815..181a3dbabda 100644--- a/tests/website/test_extract_skills.py+++ b/tests/website/test_extract_skills.py@@ -106,15 +106,8 @@ def test_source_url_empty_for_unknown_source_without_identifier(mod):# _guess_category# ---------------------------------------------------------------------------def test_guess_category_maps_known_tag(mod):- assert mod._guess_category(["security"]) == "security"- assert mod._guess_category(["machine-learning"]) == "mlops"- assert mod._guess_category(["crypto"]) == "blockchain"-def test_guess_category_accepts_literal_curated_key(mod):- # A skill tagged literally with a curated category key should route there.- assert mod._guess_category(["devops"]) == "devops"def test_guess_category_rejects_junk_tag(mod):diff --git a/tests/website/test_generate_llms_txt.py b/tests/website/test_generate_llms_txt.pyindex 738ba55a092..e9975af75e1 100644--- a/tests/website/test_generate_llms_txt.py+++ b/tests/website/test_generate_llms_txt.py@@ -127,7 +127,3 @@ def test_per_skill_catalog_pages_stay_out(gen):assert "reference/skills-catalog" in gen.iter_docs(), "the summary page must remain"-def test_bot_mode_is_reachable(gen, index):- """The page behind the original complaint, and the answer it has to carry."""- assert "user-guide/bot-mode" in _linked(gen, index)- assert "hermes peer dm" in (gen.DOCS / "user-guide" / "bot-mode.md").read_text(encoding="utf-8")diff --git a/tests/website/test_generate_skill_docs.py b/tests/website/test_generate_skill_docs.pyindex fca56519190..a6cf6fb3e6d 100644--- a/tests/website/test_generate_skill_docs.py+++ b/tests/website/test_generate_skill_docs.py@@ -100,17 +100,5 @@ def test_already_wrapped_source_double_wraps_harmlessly(gen_module):assert "<!-- ascii-guard-ignore-end -->" in result-def test_box_drawing_detection_covers_common_chars(gen_module):- """Smoke-test that the char set covers box-drawing ranges actually used- in skill diagrams."""- # Sample from real SKILL.md diagrams (segment-anything, research-paper-writing, etc.)- for ch in "┌┐└┘─│├┤┬┴┼═║╔╗╚╝╭╮╯╰▶◀▲▼":- assert ch in gen_module._BOX_DRAWING_CHARS, f"missing: {ch!r}"---def test_bundled_catalog_explains_missing_local_skills(gen_module):- """The bundled catalog should explain how to restore a listed skill that- was removed from the local profile's skills tree."""- result = gen_module.build_catalog_md_bundled([])- assert "respects local deletions and user edits" in result- assert "hermes skills reset <name> --restore" in result++diff --git a/tests/website/test_slash_commands_doc_parity.py b/tests/website/test_slash_commands_doc_parity.pydeleted file mode 100644index 8c9ef1bfb90..00000000000--- a/tests/website/test_slash_commands_doc_parity.py+++ /dev/null@@ -1,105 +0,0 @@-"""Doc-fact contract: slash-commands.md must match the command registry.--Parse the real surface and cross-check the published doc in both directions.-This class of drift has bitten before: ``/loop`` shipped with a feature page-(user-guide/features/loops.md) but never got a row in the slash-commands-reference, and the zh-Hans doc carried retired ``/credits``/``/billing`` rows-for months (PR #69639).--Two directions, both driven by ``hermes_cli.commands.COMMAND_REGISTRY``-(the single source every surface derives from):--1. Every registered command must be documented under at least one visible- form — its canonical name or any declared alias. (IronClaw rule: "any- visible alias form counts".) This keeps new CommandDefs from shipping- undocumented.-2. Every command token that appears as a table row in the doc must resolve- to a registered name or alias. This keeps retired commands from- lingering in the doc after they leave the registry.--Only the English doc is gated: i18n copies lag by design and are synced-in dedicated passes.-"""--from __future__ import annotations--import re-from pathlib import Path--import pytest--REPO_ROOT = Path(__file__).resolve().parents[2]-DOC_PATH = REPO_ROOT / "website" / "docs" / "reference" / "slash-commands.md"--# Table rows look like: | `/name ...` | description |-# Only the leading command token of a row is a doc-fact claim; command-# mentions in prose or descriptions are not rows.-_ROW_CMD_RE = re.compile(r"^\|\s*`/([a-z0-9_-]+)", re.MULTILINE)---def _mentioned(form: str, doc_text: str) -> bool:- """``/form`` as a whole command token — a bare substring test would let the- alias ``/q`` be "documented" by ``/queue`` and ``/v`` by ``/version``."""- return re.search(rf"/{re.escape(form)}(?![A-Za-z0-9_-])", doc_text) is not None--# Doc rows that are deliberately not CommandDef entries.-_NON_REGISTRY_ROWS = {- # Dynamic skill invocation — every installed skill becomes /<skill-name>.- "skill-name",-}--[email protected](scope="module")-def registry():- from hermes_cli.commands import COMMAND_REGISTRY-- return COMMAND_REGISTRY--[email protected](scope="module")-def doc_text() -> str:- assert DOC_PATH.is_file(), f"missing doc: {DOC_PATH}"- return DOC_PATH.read_text(encoding="utf-8")---def test_every_registered_command_is_documented(registry, doc_text):- """Each command must appear in the doc as /name or any /alias."""- missing = []- for cmd in registry:- forms = [cmd.name, *(cmd.aliases or ())]- if not any(_mentioned(form, doc_text) for form in forms):- missing.append(cmd.name)- assert not missing, (- "Commands registered in hermes_cli/commands.py but absent from "- f"website/docs/reference/slash-commands.md: {missing}. "- "Add a table row (Session/Configuration/Tools & Skills/Info for the "- "CLI table, and the messaging table if the command works on the "- "gateway), or document one of its aliases."- )---def test_every_documented_row_is_registered(registry, doc_text):- """Each doc table row's command token must exist in the registry."""- known = {c.name for c in registry}- for c in registry:- known.update(c.aliases or ())- known |= _NON_REGISTRY_ROWS-- unknown = sorted(- {tok for tok in _ROW_CMD_RE.findall(doc_text) if tok not in known}- )- assert not unknown, (- "slash-commands.md documents commands that no longer exist in "- f"COMMAND_REGISTRY: {unknown}. Remove the stale rows (or register "- "the command)."- )---def test_doc_parses_at_least_the_known_surface(doc_text):- """Sanity: the row regex actually sees the tables (guards against a- format change silently turning both contracts vacuous)."""- rows = set(_ROW_CMD_RE.findall(doc_text))- assert len(rows) >= 60, (- f"only {len(rows)} command rows parsed from slash-commands.md — "- "table format may have changed; update _ROW_CMD_RE."- )