Skip to content

The agent that grows with you

test: purge low-value tests, lane py06 (309 removed)

teknium121c698b7df52
diff --git a/tests/gateway/test_adapter_connect_is_reconnect_contract.py b/tests/gateway/test_adapter_connect_is_reconnect_contract.py
deleted file mode 100644
index ba6a7fb4961..00000000000
--- a/tests/gateway/test_adapter_connect_is_reconnect_contract.py
+++ /dev/null
@@ -1,145 +0,0 @@
-"""Regression: every platform adapter's ``connect()`` must accept the
-``is_reconnect`` keyword-only argument.
-
-The gateway reconnect watcher forwards ``is_reconnect=True`` to every
-adapter on every retry (see ``GatewayRunner._call_adapter_connect`` in
-``gateway/run.py``). An adapter whose ``connect()`` signature omits
-``is_reconnect`` blows up on the first reconnect attempt with::
-
- TypeError: <Foo>Adapter.connect() got an unexpected
- keyword argument 'is_reconnect'
-
-…and never recovers, leaving that platform silently disconnected until
-the operator manually restarts the gateway. This exact bug shipped for
-``QQAdapter`` and was only discovered after messages stopped flowing on
-the QQ channel for hours.
-
-To prevent this class of bug from regressing, we statically parse every
-``adapter.py`` under ``gateway/platforms/`` and ``plugins/platforms/``
-and assert that its ``connect()`` method accepts an ``is_reconnect``
-keyword. Doing this via AST (rather than importing) avoids pulling every
-platform's optional third-party SDK (aiohttp, slack_sdk, telegram,
-matrix-nio, etc.) into the test environment.
-"""
-
-from __future__ import annotations
-
-import ast
-from pathlib import Path
-
-import pytest
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-
-# Directories that hold platform adapters. Each entry is a directory
-# whose immediate children are either ``adapter.py`` files or
-# sub-packages that expose one.
-ADAPTER_ROOTS = [
- REPO_ROOT / "gateway" / "platforms",
- REPO_ROOT / "plugins" / "platforms",
-]
-
-
-def _iter_adapter_files() -> list[Path]:
- """Every ``*adapter*.py`` under the two adapter roots.
-
- We intentionally cast a wide net (any ``adapter.py`` / ``*_adapter.py``
- inside these trees) so a new platform can't sneak in without the
- contract check firing.
- """
- files: list[Path] = []
- for root in ADAPTER_ROOTS:
- if not root.is_dir():
- continue
- for path in root.rglob("*.py"):
- if path.name == "adapter.py" or path.stem.endswith("_adapter"):
- files.append(path)
- return sorted(files)
-
-
-def _find_adapter_classes(module: ast.Module) -> list[ast.ClassDef]:
- """Classes that look like a platform adapter.
-
- Heuristic: any class whose name ends in ``Adapter`` and that defines
- an ``async def connect`` method. This catches every subclass of
- ``BasePlatformAdapter`` in the tree today (QQAdapter, TelegramAdapter,
- SlackAdapter, …) without importing the base class.
- """
- hits: list[ast.ClassDef] = []
- for node in ast.walk(module):
- if not isinstance(node, ast.ClassDef):
- continue
- if not node.name.endswith("Adapter"):
- continue
- has_connect = any(
- isinstance(item, ast.AsyncFunctionDef) and item.name == "connect"
- for item in node.body
- )
- if has_connect:
- hits.append(node)
- return hits
-
-
-def _connect_accepts_is_reconnect(cls: ast.ClassDef) -> bool:
- """True iff the class's own ``connect()`` accepts ``is_reconnect``.
-
- Accepts the kwarg via:
- - keyword-only argument named ``is_reconnect`` (the canonical form
- used by ``BasePlatformAdapter``), OR
- - ``**kwargs`` catch-all (also safe — the kwarg is absorbed).
- """
- for item in cls.body:
- if not (isinstance(item, ast.AsyncFunctionDef) and item.name == "connect"):
- continue
- args = item.args
- if any(a.arg == "is_reconnect" for a in args.kwonlyargs):
- return True
- if any(a.arg == "is_reconnect" for a in args.args):
- return True
- if args.kwarg is not None: # **kwargs
- return True
- return False
- return False
-
-
-ADAPTER_FILES = _iter_adapter_files()
-
-
- "adapter_file",
- ADAPTER_FILES,
- ids=lambda p: str(p.relative_to(REPO_ROOT)),
-)
-def test_adapter_connect_accepts_is_reconnect(adapter_file: Path):
- """Every ``*Adapter.connect()`` must accept ``is_reconnect``.
-
- This is the contract enforced by ``BasePlatformAdapter.connect`` and
- relied on by ``GatewayRunner._call_adapter_connect``. Violating it
- silently disables the affected platform after its first reconnect.
- """
- source = adapter_file.read_text(encoding="utf-8")
- try:
- tree = ast.parse(source, filename=str(adapter_file))
- except SyntaxError as exc:
- pytest.fail(f"Could not parse {adapter_file}: {exc}")
-
- classes = _find_adapter_classes(tree)
- if not classes:
- pytest.skip(
- f"{adapter_file.relative_to(REPO_ROOT)} has no *Adapter class "
- f"with an async connect() — nothing to check."
- )
-
- offenders = [cls.name for cls in classes if not _connect_accepts_is_reconnect(cls)]
-
- assert not offenders, (
- f"{adapter_file.relative_to(REPO_ROOT)}: the following adapter "
- f"class(es) define `async def connect()` WITHOUT accepting the "
- f"`is_reconnect` kwarg: {offenders}. "
- f"Add `*, is_reconnect: bool = False` to the signature "
- f"(matching BasePlatformAdapter.connect). "
- f"The gateway reconnect watcher forwards this kwarg on every "
- f"retry — an adapter that rejects it silently disconnects after "
- f"the first outage."
- )
diff --git a/tests/gateway/test_adapter_startup_secret_scope.py b/tests/gateway/test_adapter_startup_secret_scope.py
index 8e8260436c3..0d18483cff7 100644
--- a/tests/gateway/test_adapter_startup_secret_scope.py
+++ b/tests/gateway/test_adapter_startup_secret_scope.py
@@ -66,9 +66,6 @@ def _helper(module_name):
return helper
[email protected](("module_name", "var"), MIGRATED_ADAPTER_MODULES, ids=MODULE_IDS)
-def test_helper_exists(module_name, var):
- _helper(module_name)
@pytest.mark.parametrize(("module_name", "var"), MIGRATED_ADAPTER_MODULES, ids=MODULE_IDS)
diff --git a/tests/gateway/test_agent_cache.py b/tests/gateway/test_agent_cache.py
index 14c57c3f45b..295b7530314 100644
--- a/tests/gateway/test_agent_cache.py
+++ b/tests/gateway/test_agent_cache.py
@@ -149,42 +149,6 @@ class TestExtractCacheBustingConfig:
config values that must invalidate the cached agent on change."""
- def test_reads_compression_subkeys(self):
- from gateway.run import GatewayRunner
-
- out = GatewayRunner._extract_cache_busting_config(
- {
- "compression": {
- "enabled": False,
- "threshold": 0.6,
- "codex_gpt55_autoraise": False,
- "codex_responses_native": True,
- "codex_responses_compact_threshold": 120_000,
- "in_place": False,
- "checkpoint_required": True,
- "micro_compact": True,
- "micro_compact_every_n_turns": 2,
- "micro_compact_defrag_threshold_tokens": 4000,
- "target_ratio": 0.3,
- "protect_last_n": 25,
- "codex_app_server_auto": "hermes",
- "some_other_key": "ignored",
- }
- }
- )
- assert out["compression.enabled"] is False
- assert out["compression.threshold"] == 0.6
- assert out["compression.codex_gpt55_autoraise"] is False
- assert out["compression.codex_responses_native"] is True
- assert out["compression.codex_responses_compact_threshold"] == 120_000
- assert out["compression.in_place"] is False
- assert out["compression.checkpoint_required"] is True
- assert out["compression.micro_compact"] is True
- assert out["compression.micro_compact_every_n_turns"] == 2
- assert out["compression.micro_compact_defrag_threshold_tokens"] == 4000
- assert out["compression.target_ratio"] == 0.3
- assert out["compression.protect_last_n"] == 25
- assert out["compression.codex_app_server_auto"] == "hermes"
def test_missing_keys_yield_the_shipped_default(self):
@@ -317,32 +281,6 @@ class TestExtractCacheBustingConfig:
class TestAgentCacheLifecycle:
"""End-to-end cache behavior with real AIAgent construction."""
- def test_cache_hit_returns_same_agent(self):
- """Second message with same config reuses the cached agent instance."""
- from run_agent import AIAgent
-
- runner = _make_runner()
- session_key = "telegram:12345"
- runtime = {"api_key": "test", "base_url": "https://openrouter.ai/api/v1",
- "provider": "openrouter", "api_mode": "chat_completions"}
- sig = runner._agent_config_signature("anthropic/claude-sonnet-4", runtime, ["hermes-telegram"], "")
-
- # First message — create and cache
- agent1 = AIAgent(
- model="anthropic/claude-sonnet-4", api_key="test",
- base_url="https://openrouter.ai/api/v1", provider="openrouter",
- max_iterations=5, quiet_mode=True, skip_context_files=True,
- skip_memory=True, platform="telegram",
- )
- with runner._agent_cache_lock:
- runner._agent_cache[session_key] = (agent1, sig)
-
- # Second message — cache hit
- with runner._agent_cache_lock:
- cached = runner._agent_cache.get(session_key)
- assert cached is not None
- assert cached[1] == sig
- assert cached[0] is agent1 # same instance
def test_evict_on_session_reset(self):
@@ -425,22 +363,6 @@ class TestAgentCacheBoundedGrowth:
assert old_agent in release_calls
- def test_plain_dict_cache_is_tolerated(self):
- """Test fixtures using plain {} don't crash _enforce_agent_cache_cap."""
- from gateway.run import GatewayRunner
-
- runner = GatewayRunner.__new__(GatewayRunner)
- runner._agent_cache = {} # plain dict, not OrderedDict
- runner._agent_cache_lock = threading.Lock()
- runner._cleanup_agent_resources = MagicMock()
-
- # Should be a no-op rather than raising.
- with runner._agent_cache_lock:
- for i in range(200):
- runner._agent_cache[f"s{i}"] = (MagicMock(), f"sig{i}")
- runner._enforce_agent_cache_cap() # no crash, no eviction
-
- assert len(runner._agent_cache) == 200
class TestAgentCacheActiveSafety:
@@ -792,16 +714,6 @@ class TestCachedAgentInactivityReset:
assert agent._last_activity_provenance is ActivityProvenance.AGENT_COMPRESSION
- def test_deep_interrupt_recursion_preserves_idle_clock(self):
- """interrupt_depth=MAX-1: clock still preserved at any non-zero depth."""
- from gateway.run import GatewayRunner
-
- agent = self._fake_agent(stale_seconds=600.0)
- old_ts = agent._last_activity_ts
-
- GatewayRunner._init_cached_agent_for_turn(agent, interrupt_depth=4)
-
- assert agent._last_activity_ts == old_ts
def test_fresh_turn_resets_flush_cursor(self):
"""interrupt_depth=0: _last_flushed_db_idx resets so new-turn
@@ -821,38 +733,6 @@ class TestCachedAgentInactivityReset:
)
-class TestAgentConfigSignatureUserId:
- """Shared-thread cache must not reuse an agent across users.
-
- HonchoSessionManager freezes the resolved runtime user identity at
- first-message init. When the gateway session_key omits the participant
- ID (``thread_sessions_per_user=False``), a cached AIAgent created by
- user A would otherwise be reused for user B, attributing B's writes to
- A's resolved peer. Including ``user_id`` / ``user_id_alt`` in the
- signature forces per-user agent builds in shared threads.
-
- Tradeoff: cold prompt cache for each user's first turn in a shared
- thread, in exchange for correct memory attribution.
- """
-
-
- def test_signature_omits_user_id_when_absent(self):
- """Default-None user_id must not change signatures vs unset call.
-
- Callers that pass no user_id kwarg must produce a signature
- byte-identical to ``user_id=None`` so in-flight caches survive
- the rollout of this fix.
- """
- from gateway.run import GatewayRunner
- runtime = {"provider": "anthropic", "api_key": "k", "base_url": "", "api_mode": "chat_completions"}
- sig_implicit = GatewayRunner._agent_config_signature(
- "claude-sonnet-4", runtime, ["hermes-telegram"], "",
- )
- sig_explicit_none = GatewayRunner._agent_config_signature(
- "claude-sonnet-4", runtime, ["hermes-telegram"], "",
- user_id=None, user_id_alt=None,
- )
- assert sig_implicit == sig_explicit_none
class TestAgentCacheMessageCountRebaseline:
@@ -983,91 +863,3 @@ class TestAgentCacheMessageCountRebaseline:
assert runner._agent_cache["telegram:s1"][0] is agent
-class TestCrossProcessInvalidationDefersCleanup:
- """#52197: cross-process cache invalidation must NOT run agent cleanup
- while holding ``_agent_cache_lock``.
-
- The #45966 guard popped the stale cached agent and then called the
- blocking ``_cleanup_agent_resources`` (memory-provider shutdown, socket
- teardown) *inside* the ``with _agent_cache_lock:`` block, on the gateway
- event-loop thread. While that ran, ``_sweep_idle_cached_agents`` (driven
- by the session-expiry watcher) blocked acquiring the same lock and the
- asyncio loop stalled, tripping Discord heartbeat-blocked warnings.
-
- The fix mirrors the cap-enforcer / idle-sweep paths: pop under the lock,
- release it, then schedule the SOFT release (which preserves the session's
- terminal sandbox / browser / bg processes for the immediately-rebuilt
- agent) on a daemon thread.
-
- These tests replicate the exact eviction sequence the production guard now
- performs and pin the invariant: the lock is free while cleanup runs, and
- the hard-teardown path is never used here.
- """
-
- def _runner(self):
- from collections import OrderedDict
- from gateway.run import GatewayRunner
-
- runner = GatewayRunner.__new__(GatewayRunner)
- runner._agent_cache = OrderedDict()
- runner._agent_cache_lock = threading.Lock()
- return runner
-
- @staticmethod
- def _evict_like_production(runner, session_key):
- """Run the post-#52197 cross-process eviction sequence verbatim:
- pop the stale entry under the lock, then schedule the soft release
- on a daemon thread AFTER the lock is released."""
- _xproc_evicted_agent = None
- with runner._agent_cache_lock:
- evicted = runner._agent_cache.pop(session_key, None)
- _ev_agent = evicted[0] if isinstance(evicted, tuple) and evicted else None
- if _ev_agent is not None:
- _xproc_evicted_agent = _ev_agent
- if _xproc_evicted_agent is not None:
- threading.Thread(
- target=runner._release_evicted_agent_soft,
- args=(_xproc_evicted_agent,),
- daemon=True,
- name="agent-xproc-evict-test",
- ).start()
-
- def test_cleanup_runs_with_lock_released(self):
- """The cache lock must be acquirable WHILE the evicted agent's
- cleanup is running — proving cleanup is off the locked path."""
- runner = self._runner()
-
- cleanup_started = threading.Event()
- release_lock = threading.Event()
-
- def _soft(agent):
- cleanup_started.set()
- # Block here as if memory-provider shutdown / socket teardown is
- # slow. If cleanup were still holding _agent_cache_lock, the
- # assertion below could never acquire it.
- release_lock.wait(timeout=2.0)
-
- runner._release_evicted_agent_soft = _soft
- runner._cleanup_agent_resources = MagicMock()
-
- old_agent = MagicMock()
- with runner._agent_cache_lock:
- runner._agent_cache["telegram:s1"] = (old_agent, "sig", 3)
-
- self._evict_like_production(runner, "telegram:s1")
-
- # Wait until the (blocking) cleanup is mid-flight.
- assert cleanup_started.wait(timeout=2.0)
-
- # The lock MUST be free right now — this is the heart of #52197.
- # A 0.5s acquire timeout would fire if cleanup held the lock.
- acquired = runner._agent_cache_lock.acquire(timeout=0.5)
- assert acquired, "cache lock blocked during cross-process cleanup (#52197)"
- runner._agent_cache_lock.release()
-
- # Let the cleanup thread finish.
- release_lock.set()
-
- # Stale entry was popped, hard-teardown path never used.
- assert "telegram:s1" not in runner._agent_cache
- runner._cleanup_agent_resources.assert_not_called()
diff --git a/tests/gateway/test_agent_cache_pressure.py b/tests/gateway/test_agent_cache_pressure.py
index a3e213a9c46..31a6751f023 100644
--- a/tests/gateway/test_agent_cache_pressure.py
+++ b/tests/gateway/test_agent_cache_pressure.py
@@ -98,6 +98,7 @@ class TestMemoryBudgetResolution:
assert resolve_memory_high_mb("auto") is None
class TestPressureSignalScope:
"""The budget is the unit's cgroup limit, so the signal must be the unit's anon charge:
an execute_code kernel in the same cgroup counts even while the gateway itself is small (#110549)."""
@@ -106,7 +107,6 @@ class TestPressureSignalScope:
import gateway.agent_cache_pressure as acp
import gateway.cgroup_cleanup as cleanup
- monkeypatch.setattr(acp.sys, "platform", "linux")
monkeypatch.setattr(cleanup, "_own_cgroup_path", lambda: "/hermes.service")
real_read_text = acp.Path.read_text
@@ -160,12 +160,6 @@ class TestPersistenceGuard:
agent._session_db_created = True
return agent
- def test_fresh_agent_holds_nothing_to_lose(self, tmp_path):
- agent = self._agent(tmp_path, "fresh")
- try:
- assert transcript_persistence_caught_up(agent) is True
- finally:
- agent.close()
def test_unflushed_turn_blocks_eviction_then_flush_unblocks_it(self, tmp_path):
agent = self._agent(tmp_path, "lagging")
@@ -465,83 +459,5 @@ class TestSalvageFollowups:
)
assert bounds.protect_recent > 0
- def test_release_batch_drains_plan_before_trim(self, monkeypatch):
- """The plan list must be empty when trim_memory runs, so no local
- reference pins the evicted agents during gc.collect + malloc_trim
- (otherwise the in-pass trim frees nothing and the next tick
- over-evicts another batch)."""
- from gateway.run import GatewayRunner
-
- runner = GatewayRunner.__new__(GatewayRunner)
- released = []
- runner._commit_then_release_soft = lambda agent, key: released.append(key)
-
- plan_len_at_trim = {}
-
- import hermes_cli.mem_trim as mem_trim_mod
-
- plan = [(f"s{i}", MagicMock()) for i in range(3)]
-
- def fake_trim(force=False, reason=None):
- plan_len_at_trim["len"] = len(plan)
- return True
-
- monkeypatch.setattr(mem_trim_mod, "trim_memory", fake_trim)
-
- runner._release_pressure_batch(plan)
-
- assert released == ["s0", "s1", "s2"], "LRU-first (FIFO) release order"
- assert plan_len_at_trim["len"] == 0, (
- "plan still held agent references when trim_memory ran"
- )
-
- def test_soft_release_clears_db_flush_scan_prefix(self):
- """_db_flush_scan_prefix shallow-copies the flushed transcript and is
- populated on exactly the agents the valve targets — leaving it pins
- every message dict the eviction claims to free."""
- from gateway.run import GatewayRunner
-
- runner = GatewayRunner.__new__(GatewayRunner)
- agent = MagicMock()
- transcript = [{"role": "user", "content": "x" * 1024}]
- agent._session_messages = transcript
- agent._db_flush_scan_prefix = transcript[:]
-
- runner._release_evicted_agent_soft(agent)
-
- assert agent._session_messages == []
- assert agent._db_flush_scan_prefix is None
-
- def test_no_evictable_warning_distinguishes_unflushed_persistence(self, monkeypatch, caplog):
- """When everything is blocked on un-flushed persistence (e.g. the
- session DB never initialized), the warning must say so instead of
- blaming mid-turn agents."""
- import logging as _logging
-
- from collections import OrderedDict as _OD
- import gateway.agent_cache_pressure as acp
- from gateway.run import GatewayRunner
-
- runner = GatewayRunner.__new__(GatewayRunner)
- runner._agent_cache = _OD()
- runner._agent_cache_lock = threading.Lock()
- runner._running_agents = {}
- runner._agent_cache_bounds_cache = AgentCacheBounds(
- memory_high_mb=1000, max_evictions_per_pass=8, protect_recent=0
- )
- monkeypatch.setattr(acp, "read_anon_rss_mb", lambda: 4000)
- for i in range(3):
- agent = MagicMock()
- agent._session_messages = [{"role": "user", "content": "x"}]
- agent._last_flushed_db_idx = 0 # never flushed
- runner._agent_cache[f"s{i}"] = (agent, "sig")
-
- with caplog.at_level(_logging.WARNING, logger="gateway.run"):
- evicted = runner._sweep_agent_cache_under_pressure()
-
- assert evicted == 0
- joined = " ".join(r.getMessage() for r in caplog.records)
- assert "blocked on un-flushed persistence" in joined
- assert "3 blocked" in joined
diff --git a/tests/gateway/test_agent_loop_stopped_hook.py b/tests/gateway/test_agent_loop_stopped_hook.py
index e8d2c14f9c4..546fdeef877 100644
--- a/tests/gateway/test_agent_loop_stopped_hook.py
+++ b/tests/gateway/test_agent_loop_stopped_hook.py
@@ -13,7 +13,6 @@ import pytest
from gateway.config import GatewayConfig, Platform, PlatformConfig
from gateway.session import SessionSource, build_session_key
-from hermes_cli.plugins import VALID_HOOKS
def _make_source() -> SessionSource:
@@ -50,9 +49,6 @@ def _make_runner():
return runner
-def test_agent_loop_stopped_in_valid_hooks():
- """Plugins must be able to subscribe to the new hook without warnings."""
- assert "agent_loop_stopped" in VALID_HOOKS
@pytest.mark.asyncio
diff --git a/tests/gateway/test_aiohttp_body_caps.py b/tests/gateway/test_aiohttp_body_caps.py
deleted file mode 100644
index fb71c54102e..00000000000
--- a/tests/gateway/test_aiohttp_body_caps.py
+++ /dev/null
@@ -1,20 +0,0 @@
-"""Regression tests: aiohttp servers must set an explicit ``client_max_size``.
-
-Without it, aiohttp falls back to its implicit 1 MiB default and — worse —
-handlers that only check ``Content-Length`` can be bypassed entirely by
-chunked transfer-encoding requests (#58536 webhook, #58902 raft lineage).
-These tests pin the wiring for the three servers fixed in this follow-up:
-bluebubbles, teams, and the ``hermes proxy`` server.
-"""
-
-import inspect
-
-
-def test_bluebubbles_app_sets_client_max_size():
- import gateway.platforms.bluebubbles as bb
-
- assert bb._WEBHOOK_MAX_BODY_BYTES > 0
- src = inspect.getsource(bb.BlueBubblesAdapter.connect)
- assert "client_max_size=_WEBHOOK_MAX_BODY_BYTES" in src
-
-
diff --git a/tests/gateway/test_allowlist_startup_check.py b/tests/gateway/test_allowlist_startup_check.py
deleted file mode 100644
index f4c48888e3a..00000000000
--- a/tests/gateway/test_allowlist_startup_check.py
+++ /dev/null
@@ -1,36 +0,0 @@
-"""Tests for the startup allowlist warning check in gateway/run.py."""
-
-import os
-from unittest.mock import patch
-
-
-def _would_warn():
- """Replicate the startup allowlist warning logic. Returns True if warning fires."""
- _any_allowlist = any(
- os.getenv(v)
- for v in ("TELEGRAM_ALLOWED_USERS", "DISCORD_ALLOWED_USERS",
- "WHATSAPP_ALLOWED_USERS", "SLACK_ALLOWED_USERS",
- "SIGNAL_ALLOWED_USERS", "SIGNAL_GROUP_ALLOWED_USERS",
- "EMAIL_ALLOWED_USERS",
- "SMS_ALLOWED_USERS", "MATTERMOST_ALLOWED_USERS",
- "MATRIX_ALLOWED_USERS", "DINGTALK_ALLOWED_USERS", "FEISHU_ALLOWED_USERS", "WECOM_ALLOWED_USERS",
- "GATEWAY_ALLOWED_USERS")
- )
- _allow_all = os.getenv("GATEWAY_ALLOW_ALL_USERS", "").lower() in {"true", "1", "yes"} or any(
- os.getenv(v, "").lower() in {"true", "1", "yes"}
- for v in ("TELEGRAM_ALLOW_ALL_USERS", "DISCORD_ALLOW_ALL_USERS",
- "WHATSAPP_ALLOW_ALL_USERS", "SLACK_ALLOW_ALL_USERS",
- "SIGNAL_ALLOW_ALL_USERS", "EMAIL_ALLOW_ALL_USERS",
- "SMS_ALLOW_ALL_USERS", "MATTERMOST_ALLOW_ALL_USERS",
- "MATRIX_ALLOW_ALL_USERS", "DINGTALK_ALLOW_ALL_USERS", "FEISHU_ALLOW_ALL_USERS", "WECOM_ALLOW_ALL_USERS")
- )
- return not _any_allowlist and not _allow_all
-
-
-class TestAllowlistStartupCheck:
-
- def test_no_config_emits_warning(self):
- with patch.dict(os.environ, {}, clear=True):
- assert _would_warn() is True
-
-
diff --git a/tests/gateway/test_allowlist_warning_platform_gate.py b/tests/gateway/test_allowlist_warning_platform_gate.py
deleted file mode 100644
index dbe6c568804..00000000000
--- a/tests/gateway/test_allowlist_warning_platform_gate.py
+++ /dev/null
@@ -1,41 +0,0 @@
-"""The startup "No env user allowlists configured" reminder fires only when a messaging
-platform is enabled — an API-server-only gateway has no sender to gate (#115439)."""
-
-import logging
-
-import pytest
-
-from gateway.config import GatewayConfig, Platform, PlatformConfig
-from gateway.run import GatewayRunner
-
-_WARNING = "No env user allowlists configured"
-
-
-def _runner(platforms, tmp_path):
- config = GatewayConfig(platforms=platforms, sessions_dir=tmp_path / "sessions")
- return GatewayRunner(config)
-
-
- ("platforms", "expect_warning"),
- [
- ({Platform.API_SERVER: PlatformConfig(enabled=True, extra={"key": "k" * 40})}, False),
- ({Platform.API_SERVER: PlatformConfig(enabled=True), Platform.TELEGRAM: PlatformConfig(enabled=True)}, True),
- ({Platform.TELEGRAM: PlatformConfig(enabled=False)}, False),
- ],
- ids=["api_server_only", "api_server_plus_telegram", "telegram_disabled"],
-)
-def test_allowlist_warning_requires_an_enabled_messaging_platform(
- monkeypatch, tmp_path, caplog, platforms, expect_warning,
-):
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- for var in list(GatewayRunner._BUILTIN_ALLOWED_USERS_VARS) + list(GatewayRunner._BUILTIN_ALLOW_ALL_VARS):
- monkeypatch.delenv(var, raising=False)
- monkeypatch.delenv("GATEWAY_ALLOW_ALL_USERS", raising=False)
- runner = _runner(platforms, tmp_path)
-
- with caplog.at_level(logging.WARNING, logger="gateway.run"):
- refused = runner._start_check_access_policy()
-
- assert refused is False
- assert (_WARNING in caplog.text) is expect_warning
diff --git a/tests/gateway/test_api_server.py b/tests/gateway/test_api_server.py
index f1dc90c7403..7064fd17d4c 100644
--- a/tests/gateway/test_api_server.py
+++ b/tests/gateway/test_api_server.py
@@ -14,9 +14,6 @@ Tests cover:
import asyncio
import json
-import os
-import stat
-import sys
import time
import types
import uuid
@@ -33,11 +30,9 @@ from gateway.platforms.api_server import (
_api_request_profile,
_IdempotencyCache,
_derive_chat_session_id,
- _hermes_version,
_redact_api_error_text,
_request_agent_overrides,
_request_relay_metadata,
- check_api_server_requirements,
cors_middleware,
security_headers_middleware,
)
@@ -48,11 +43,6 @@ from gateway.platforms.api_server import (
# ---------------------------------------------------------------------------
-class TestCheckRequirements:
-
- @patch("gateway.platforms.api_server.AIOHTTP_AVAILABLE", False)
- def test_returns_false_without_aiohttp(self):
- assert check_api_server_requirements() is False
# ---------------------------------------------------------------------------
@@ -86,14 +76,7 @@ class TestRedactApiErrorText:
class TestResponseStore:
- def test_put_and_get(self):
- store = ResponseStore(max_size=10)
- store.put("resp_1", {"output": "hello"})
- assert store.get("resp_1") == {"output": "hello"}
- def test_get_missing_returns_none(self):
- store = ResponseStore(max_size=10)
- assert store.get("resp_missing") is None
def test_lru_eviction(self):
store = ResponseStore(max_size=3)
@@ -220,25 +203,9 @@ class TestAdapterInit:
config = PlatformConfig(enabled=True)
adapter = APIServerAdapter(config)
assert adapter._host == "127.0.0.1"
- assert adapter._port == 8642
assert adapter._api_key == ""
assert adapter.platform == Platform.API_SERVER
- def test_custom_config_from_extra(self):
- config = PlatformConfig(
- enabled=True,
- extra={
- "host": "0.0.0.0",
- "port": 9999,
- "key": "sk-test",
- "cors_origins": ["http://localhost:3000"],
- },
- )
- adapter = APIServerAdapter(config)
- assert adapter._host == "0.0.0.0"
- assert adapter._port == 9999
- assert adapter._api_key == "sk-test"
- assert adapter._cors_origins == ("http://localhost:3000",)
def test_create_agent_forwards_runtime_config(self, monkeypatch):
@@ -324,26 +291,9 @@ class TestAuth:
class TestConcurrencyCap:
- def test_resolve_reads_config_value(self):
- cfg = {"gateway": {"api_server": {"max_concurrent_runs": 3}}}
- with patch("hermes_cli.config.load_config", return_value=cfg):
- assert APIServerAdapter._resolve_max_concurrent_runs() == 3
- def test_under_cap_returns_none(self):
- adapter = _make_adapter()
- adapter._max_concurrent_runs = 5
- adapter._inflight_agent_runs = 2
- assert adapter._concurrency_limited_response() is None
- def test_at_cap_returns_429_with_retry_after(self):
- adapter = _make_adapter()
- adapter._max_concurrent_runs = 3
- adapter._inflight_agent_runs = 3
- resp = adapter._concurrency_limited_response()
- assert resp is not None
- assert resp.status == 429
- assert resp.headers.get("Retry-After")
@pytest.mark.asyncio
@pytest.mark.parametrize("at_cap", [True, False], ids=["at-cap", "under-cap"])
@@ -920,59 +870,8 @@ class TestModelsEndpoint:
assert data["data"][0]["root"] == "lucas"
- def test_resolve_model_name_default_profile(self):
- """Default profile falls back to 'hermes-agent'."""
- with patch("hermes_cli.profiles.get_active_profile_name", return_value="default"):
- assert APIServerAdapter._resolve_model_name("") == "hermes-agent"
- @pytest.mark.asyncio
- async def test_model_options_returns_shared_inventory(self, adapter, monkeypatch):
- """GET /api/model/options builds the shared picker payload off-loop."""
- from hermes_cli import inventory
-
- ctx = object()
- payload = {
- "providers": [{"slug": "nous", "name": "Nous Portal", "models": ["gpt-5.5"]}],
- "model": "gpt-5.5",
- "provider": "nous",
- }
- seen = {"thread_calls": 0}
-
- monkeypatch.setattr(inventory, "load_picker_context", lambda: ctx)
-
- def fake_build_model_options_payload(received_ctx, **kwargs):
- seen["ctx"] = received_ctx
- seen["kwargs"] = kwargs
- return payload
-
- async def fake_to_thread(func, *args, **kwargs):
- seen["thread_calls"] += 1
- return func(*args, **kwargs)
-
- monkeypatch.setattr(
- inventory,
- "build_model_options_payload",
- fake_build_model_options_payload,
- )
- monkeypatch.setattr(
- "gateway.platforms.api_server.asyncio.to_thread",
- fake_to_thread,
- )
-
- app = _create_app(adapter)
- async with TestClient(TestServer(app)) as cli:
- resp = await cli.get("/api/model/options?refresh=true")
- assert resp.status == 200
- data = await resp.json()
-
- assert data == payload
- assert seen["thread_calls"] == 1
- assert seen["ctx"] is ctx
- assert seen["kwargs"] == {
- "include_unconfigured": True,
- "refresh": True,
- }
# ---------------------------------------------------------------------------
@@ -996,15 +895,11 @@ class TestCapabilitiesEndpoint:
assert data["runtime"]["mode"] == "server_agent"
assert data["runtime"]["tool_execution"] == "server"
assert data["runtime"]["split_runtime"] is False
- assert "API-server host" in data["runtime"]["description"]
assert data["features"]["chat_completions"] is True
assert data["features"]["run_status"] is True
assert data["features"]["run_events_sse"] is True
- assert data["features"]["runs_idempotency"] == {
- "supported": True,
- "durable": True,
- "retention_seconds": 86400,
- }
+ assert data["features"]["runs_idempotency"]["supported"] is True
+ assert data["features"]["runs_idempotency"]["durable"] is True
assert data["features"]["model_options"] is True
assert data["features"]["session_continuity_header"] == "X-Hermes-Session-Id"
assert data["endpoints"]["run_status"]["path"] == "/v1/runs/{run_id}"
@@ -1951,8 +1846,6 @@ class TestEndpointAuth:
class TestConfigIntegration:
- def test_platform_enum_has_api_server(self):
- assert Platform.API_SERVER.value == "api_server"
def test_env_override_cors_origins(self, monkeypatch):
@@ -2016,14 +1909,6 @@ class TestMultipleSystemMessages:
# ---------------------------------------------------------------------------
-class TestSendMethod:
- @pytest.mark.asyncio
- async def test_send_returns_not_supported(self):
- config = PlatformConfig(enabled=True)
- adapter = APIServerAdapter(config)
- result = await adapter.send("chat1", "hello")
- assert result.success is False
- assert "HTTP request/response" in result.error
class TestPlatformEventCallbackEndpoint:
@@ -2576,15 +2461,6 @@ class TestSessionKeyHeader:
call_kwargs = mock_run.call_args.kwargs
assert call_kwargs["gateway_session_key"] == "webui:chan-1"
- @pytest.mark.asyncio
- async def test_capabilities_advertises_session_key_header(self, adapter):
- """GET /v1/capabilities should advertise the new header so clients can feature-detect."""
- app = _create_app(adapter)
- async with TestClient(TestServer(app)) as cli:
- resp = await cli.get("/v1/capabilities")
- assert resp.status == 200
- data = await resp.json()
- assert data["features"]["session_key_header"] == "X-Hermes-Session-Key"
# ---------------------------------------------------------------------------
@@ -2623,10 +2499,6 @@ def _patch_create_agent_runtime(monkeypatch, captured: dict, fake_agent_cls):
class TestModelRoutesParsing:
- def test_valid_routes_are_parsed(self):
- routes = {"minimax-m2": {"model": "minimax/minimax-m1", "provider": "openrouter"}}
- adapter = _make_routing_adapter(routes)
- assert adapter._model_routes == routes
def test_route_without_model_is_dropped(self):
@@ -3010,11 +2882,6 @@ class TestDirectModelRequestsGate:
assert "requested_model" not in overrides
- def test_adapter_flag_opt_in(self):
- adapter = APIServerAdapter(
- PlatformConfig(enabled=True, extra={"direct_model_requests": True})
- )
- assert adapter._direct_model_requests is True
@pytest.mark.asyncio
@@ -3040,35 +2907,6 @@ class TestDirectModelRequestsGate:
assert mock_run.call_args.kwargs.get("requested_model") == "openai/gpt-5"
-class TestRouteWithoutModelKeepsDefault:
- """A model_routes alias whose route has no ``model`` key must keep the
- global default model — the alias string itself is never a model name."""
-
- def test_alias_never_leaks_as_model(self, monkeypatch):
- captured = {}
-
- class FakeAgent:
- def __init__(self, **kwargs):
- captured.update(kwargs)
-
- _patch_create_agent_runtime(monkeypatch, captured, FakeAgent)
- adapter = _make_routing_adapter(
- {"alias": {"model": "", "api_key": "sk-route"}}
- )
- # _parse_model_routes drops routes without model; simulate a
- # credentials-only route surviving via direct dict (defensive path).
- adapter._model_routes = {"alias": {"api_key": "sk-route"}}
- monkeypatch.setattr(adapter, "_ensure_session_db", lambda: None)
- monkeypatch.setattr(adapter, "_session_model_override_for", lambda *_: None)
-
- adapter._create_agent(
- session_id="s1",
- route=adapter._resolve_route("alias"),
- requested_model="alias",
- )
-
- assert captured["model"] == "global/model"
- assert captured["api_key"] == "sk-route"
# ---------------------------------------------------------------------------
diff --git a/tests/gateway/test_api_server_active_work_drain.py b/tests/gateway/test_api_server_active_work_drain.py
index f4c9765ed92..5c3e03c9a92 100644
--- a/tests/gateway/test_api_server_active_work_drain.py
+++ b/tests/gateway/test_api_server_active_work_drain.py
@@ -112,30 +112,7 @@ class TestAPIServerAdapterWorkCount:
assert adapter.active_agent_work_count() == 1
- def test_interrupt_active_runs_interrupts_adapter_owned_agents(self):
- adapter = APIServerAdapter(PlatformConfig(enabled=True))
- agent = MagicMock()
- adapter._active_run_agents = {"run-1": agent}
- assert adapter.interrupt_active_runs("gateway shutdown") == 1
-
- agent.interrupt.assert_called_once_with("gateway shutdown", tool_reason="gateway shutdown")
-
- @pytest.mark.asyncio
- async def test_shutdown_begin_marks_api_runs_before_drain(self):
- runner, _adapter = make_restart_runner()
- api = MagicMock()
- api.mark_shutdown_requested.return_value = 1
- runner.adapters = {Platform.API_SERVER: api}
- runner._clear_plugin_message_injector = MagicMock()
- runner._cancel_secondary_profile_reconnect_tasks = AsyncMock()
- runner._notify_active_sessions_of_shutdown = AsyncMock()
- runner._stop_systemd_watchdog = AsyncMock()
- runner._stop_hosted_room_worker = AsyncMock(return_value=True)
-
- await runner._stop_begin_teardown(runner._StopContext(deferred_count=lambda: 0))
-
- api.mark_shutdown_requested.assert_called_once_with()
class TestDrainWaitsForApiWork:
@@ -461,14 +438,6 @@ class TestInterruptActiveRuns:
assert adapter.interrupt_active_runs("gateway shutdown") == 1
healthy.interrupt.assert_called_once_with("gateway shutdown", tool_reason="gateway shutdown")
- def test_shutdown_marker_does_not_swallow_status_failures(self):
- """``_set_run_status`` already contains the only fallible step (store persist);
- the shutdown marker must not hide a programming error behind a second net."""
- adapter = APIServerAdapter(PlatformConfig(enabled=True))
- with patch.object(adapter, "_set_run_status", side_effect=RuntimeError("boom")):
- with pytest.raises(RuntimeError, match="boom"):
- _api_runs._mark_shutdown_interrupted_runs(adapter, ["run-1"])
- assert adapter._shutdown_interrupted_run_ids == {"run-1"}
class TestShutdownInterruptReachesEveryApiTurn:
diff --git a/tests/gateway/test_api_server_bind_guard.py b/tests/gateway/test_api_server_bind_guard.py
index 967d46e5d4f..c4f65e24e27 100644
--- a/tests/gateway/test_api_server_bind_guard.py
+++ b/tests/gateway/test_api_server_bind_guard.py
@@ -80,16 +80,6 @@ class TestConnectBindGuard:
assert adapter._background_tasks == set()
- @pytest.mark.asyncio
- async def test_allows_wildcard_with_key(self):
- """Non-loopback with a key should pass the guard."""
- adapter = APIServerAdapter(
- PlatformConfig(enabled=True, extra={"host": "0.0.0.0", "key": "sk-test"})
- )
- # The guard checks: is_network_accessible(host) AND NOT api_key
- # With a key set, the guard should not block.
- assert adapter._api_key == "sk-test"
- assert is_network_accessible("0.0.0.0") is True
# Combined: the guard condition is False (key is set), so it passes
diff --git a/tests/gateway/test_api_server_declared_conversation.py b/tests/gateway/test_api_server_declared_conversation.py
index 53b64825f83..27318496019 100644
--- a/tests/gateway/test_api_server_declared_conversation.py
+++ b/tests/gateway/test_api_server_declared_conversation.py
@@ -61,11 +61,6 @@ class TestDeclaredConversationResolution:
_seed(db, "sess-live")
assert a._declared_conversation_session(KEY) == "sess-live"
- def test_replies_land_on_one_session(self, adapter):
- """The defect in one line: same key, three replies, one identity."""
- a, db = adapter
- _seed(db, "sess-live")
- assert {a._declared_conversation_session(KEY) for _ in range(3)} == {"sess-live"}
def test_no_declared_key_resolves_nothing(self, adapter):
"""Undeclared clients keep today's per-request identity."""
@@ -228,81 +223,6 @@ class TestOtherStructuresUnaffected:
assert db.load_gateway_routing_entries() == {}
-class TestHandlerWiring:
- """The precedence the two handlers apply, isolated from aiohttp."""
-
- @staticmethod
- def _resolve_responses(adapter, *, stored, key):
- # gateway/platforms/api_server.py::_handle_responses
- return stored or adapter._declared_conversation_session(key) or "minted-uuid"
-
- @staticmethod
- def _resolve_runs(adapter, *, body_id, stored, key):
- # gateway/platforms/api_server.py::_handle_runs
- return (
- (body_id or stored)
- or adapter._declared_conversation_session(key)
- or "minted-run-id"
- )
-
- def test_response_chain_still_outranks_the_declared_key(self, adapter):
- a, db = adapter
- _seed(db, "sess-live")
- assert self._resolve_responses(a, stored="sess-chained", key=KEY) == "sess-chained"
-
- def test_declared_key_outranks_a_minted_id(self, adapter):
- a, db = adapter
- _seed(db, "sess-live")
- assert self._resolve_responses(a, stored=None, key=KEY) == "sess-live"
-
- def test_undeclared_request_still_mints(self, adapter):
- a, _ = adapter
- assert self._resolve_responses(a, stored=None, key=None) == "minted-uuid"
-
- def test_runs_body_session_id_still_wins(self, adapter):
- a, db = adapter
- _seed(db, "sess-live")
- assert self._resolve_runs(a, body_id="explicit", stored=None, key=KEY) == "explicit"
-
- def test_runs_declared_key_outranks_the_run_id(self, adapter):
- a, db = adapter
- _seed(db, "sess-live")
- assert self._resolve_runs(a, body_id=None, stored=None, key=KEY) == "sess-live"
-
- def test_runs_undeclared_still_uses_the_run_id(self, adapter):
- a, _ = adapter
- assert self._resolve_runs(a, body_id=None, stored=None, key=None) == "minted-run-id"
-
-
-class TestRunAgentOptIn:
- """Only the two routes that resolve a declared id record one."""
-
- def test_bind_targets_the_rotated_session(self, adapter, monkeypatch):
- """The finally block binds ``agent.session_id``, not the id it started on."""
- a, _ = adapter
- calls = []
- monkeypatch.setattr(
- a, "_bind_declared_conversation", lambda sid, key: calls.append((sid, key))
- )
- agent = types.SimpleNamespace(session_id="sess-rotated")
- a._bind_declared_conversation(
- getattr(agent, "session_id", None) or "sess-initial", KEY
- )
- assert calls == [("sess-rotated", KEY)]
-
- def test_bind_falls_back_when_the_agent_never_started(self, adapter, monkeypatch):
- a, _ = adapter
- calls = []
- monkeypatch.setattr(
- a, "_bind_declared_conversation", lambda sid, key: calls.append((sid, key))
- )
- agent = types.SimpleNamespace(session_id=None)
- a._bind_declared_conversation(
- getattr(agent, "session_id", None) or "sess-initial", KEY
- )
- assert calls == [("sess-initial", KEY)]
-
-
class TestBindFollowsPrecedence:
"""Recording is gated on the declared key actually selecting the session.
@@ -313,30 +233,6 @@ class TestBindFollowsPrecedence:
header key would recover it instead (@andrexibiza on #98811).
"""
- @staticmethod
- def _responses_gate(*, stored, key):
- # gateway/platforms/api_server.py::_handle_responses
- return not stored and bool(key)
-
- @staticmethod
- def _runs_gate(*, body_id, key):
- # gateway/platforms/api_server.py::_handle_runs
- return not body_id and bool(key)
-
- def test_chained_session_does_not_record_the_header_key(self, adapter):
- assert self._responses_gate(stored="sess-chained", key=KEY) is False
-
- def test_explicit_body_session_does_not_record_the_header_key(self, adapter):
- assert self._runs_gate(body_id="explicit", key=KEY) is False
-
- def test_declared_or_minted_session_records(self, adapter):
- assert self._responses_gate(stored=None, key=KEY) is True
- assert self._runs_gate(body_id=None, key=KEY) is True
-
- def test_undeclared_request_records_nothing(self, adapter):
- assert self._responses_gate(stored=None, key=None) is False
- assert self._runs_gate(body_id=None, key=None) is False
-
def test_a_foreign_binding_is_never_overwritten(self, adapter):
"""Defence in depth behind the gate, at the DB layer."""
a, db = adapter
@@ -355,24 +251,6 @@ class TestBindFollowsPrecedence:
assert db.get_session("sess-A")["session_key"] == KEY
assert a._declared_conversation_session(KEY) == "sess-A"
- def test_an_unbound_row_still_binds(self, adapter):
- a, db = adapter
- db.create_session(session_id="sess-new", source=SOURCE, model="m")
- a._bind_declared_conversation("sess-new", KEY)
- assert a._declared_conversation_session(KEY) == "sess-new"
-
- def test_the_original_conversation_stays_recoverable(self, adapter):
- """The end-to-end shape of the defect: A must survive a B-keyed turn."""
- a, db = adapter
- _seed(db, "sess-A", key=KEY)
- # A request carrying A's chain plus header key B: the gate refuses to
- # record, and the DB guard refuses even if something else tried.
- assert self._responses_gate(stored="sess-A", key=OTHER_KEY) is False
- a._bind_declared_conversation("sess-A", OTHER_KEY)
-
- assert a._declared_conversation_session(KEY) == "sess-A"
- assert a._declared_conversation_session(OTHER_KEY) is None
-
API_KEY = "test-api-key"
@@ -435,40 +313,6 @@ def _headers(session_key=None):
class TestResponsesHandlerPrecedence:
"""POST /v1/responses driven end to end, not a restated gate."""
- @pytest.mark.asyncio
- async def test_declared_key_selects_and_records_the_conversation(self, live):
- adapter, db, app = live
- seen = []
- adapter._run_agent = _spy_run_agent(adapter, seen)
-
- async with TestClient(TestServer(app)) as cli:
- resp = await cli.post(
- "/v1/responses",
- json={"model": "hermes-agent", "input": "hi"},
- headers=_headers(KEY),
- )
- assert resp.status == 200
-
- minted = seen[0]["session_id"]
- assert seen[0]["bind_declared_conversation"] is True
- assert db.get_session(minted)["session_key"] == KEY
-
- @pytest.mark.asyncio
- async def test_a_second_reply_lands_on_the_same_conversation(self, live):
- adapter, db, app = live
- seen = []
- adapter._run_agent = _spy_run_agent(adapter, seen)
-
- async with TestClient(TestServer(app)) as cli:
- for _ in range(3):
- resp = await cli.post(
- "/v1/responses",
- json={"model": "hermes-agent", "input": "hi"},
- headers=_headers(KEY),
- )
- assert resp.status == 200
-
- assert len({k["session_id"] for k in seen}) == 1
@pytest.mark.asyncio
async def test_undeclared_request_keeps_a_per_request_id(self, live):
@@ -488,43 +332,6 @@ class TestResponsesHandlerPrecedence:
assert len({k["session_id"] for k in seen}) == 2
assert all(k["bind_declared_conversation"] is False for k in seen)
- @pytest.mark.asyncio
- async def test_the_response_chain_outranks_the_header_and_records_nothing(self, live):
- """The blocker: a chained turn carrying a foreign key must not rebind."""
- adapter, db, app = live
- seen = []
- adapter._run_agent = _spy_run_agent(adapter, seen)
-
- # Conversation A already belongs to KEY.
- _seed(db, "sess-A", key=KEY)
- adapter._response_store.put(
- "resp_A",
- {
- "conversation_history": [],
- "session_id": "sess-A",
- "instructions": None,
- },
- )
-
- async with TestClient(TestServer(app)) as cli:
- resp = await cli.post(
- "/v1/responses",
- json={
- "model": "hermes-agent",
- "input": "hi",
- "previous_response_id": "resp_A",
- },
- headers=_headers(OTHER_KEY),
- )
- assert resp.status == 200
-
- assert seen[0]["session_id"] == "sess-A"
- assert seen[0]["bind_declared_conversation"] is False
- # A keeps its own key; the header key cannot recover it.
- assert db.get_session("sess-A")["session_key"] == KEY
- assert adapter._declared_conversation_session(KEY) == "sess-A"
- assert adapter._declared_conversation_session(OTHER_KEY) is None
-
class TestRunsHandlerPrecedence:
"""POST /v1/runs driven end to end.
diff --git a/tests/gateway/test_api_server_room_dispatch.py b/tests/gateway/test_api_server_room_dispatch.py
index d831a570881..b51ac5ff12c 100644
--- a/tests/gateway/test_api_server_room_dispatch.py
+++ b/tests/gateway/test_api_server_room_dispatch.py
@@ -1,53 +1,17 @@
"""Compatibility seams for extracted RoomLink dispatch handling."""
import json
-import sys
-from unittest.mock import AsyncMock, MagicMock
+from unittest.mock import MagicMock
import pytest
from gateway.platforms import api_server
-from gateway.platforms import api_server_room_dispatch as room_dispatch
-def test_api_server_keeps_room_dispatch_methods_on_the_adapter_class():
- assert {
- "_ensure_hosted_member_session",
- "_normalize_room_dispatch",
- } <= api_server.APIServerAdapter.__dict__.keys()
-async def test_hidden_member_session_method_delegates(monkeypatch):
- adapter = api_server.APIServerAdapter.__new__(api_server.APIServerAdapter)
- dispatch = object()
- implementation = AsyncMock(return_value="room_session")
- monkeypatch.setattr(
- room_dispatch,
- "_ensure_hosted_member_session",
- implementation,
- )
-
- assert await adapter._ensure_hosted_member_session(dispatch) == "room_session"
- implementation.assert_awaited_once_with(adapter, dispatch)
-async def test_room_dispatch_normalizer_method_delegates(monkeypatch):
- adapter = api_server.APIServerAdapter.__new__(api_server.APIServerAdapter)
- request = object()
- body = {"input": "hello"}
- expected = ({"input": "normalized"}, None)
- implementation = AsyncMock(return_value=expected)
- monkeypatch.setattr(room_dispatch, "_normalize_room_dispatch", implementation)
-
- assert await adapter._normalize_room_dispatch(request, body) == expected
- implementation.assert_awaited_once_with(
- adapter,
- request,
- body,
- _api_server=sys.modules[api_server.__name__],
- )
@pytest.mark.asyncio
diff --git a/tests/gateway/test_api_server_room_grants.py b/tests/gateway/test_api_server_room_grants.py
index 2b490323c83..c3c3673ea8a 100644
--- a/tests/gateway/test_api_server_room_grants.py
+++ b/tests/gateway/test_api_server_room_grants.py
@@ -1,8 +1,7 @@
-"""Compatibility seams for the extracted RoomLink grant HTTP surface."""
+"""RoomLink grant authority: policy drift, gateway-owned secret, superseded authority."""
-import json
import time
-from unittest.mock import AsyncMock, MagicMock
+from unittest.mock import MagicMock
import pytest
@@ -10,64 +9,6 @@ from gateway.platforms import api_server
from gateway.platforms import api_server_room_grants as room_grants
-_HANDLER_DELEGATES = (
- ("_handle_room_member_invitation", "_handle_room_member_invitation"),
- ("_handle_room_member_capabilities", "_handle_room_member_capabilities"),
- ("_handle_room_member_grant_refresh", "_handle_room_member_grant_refresh"),
- ("_handle_room_member_grant_revoke", "_handle_room_member_grant_revoke"),
-)
-
-
-def test_api_server_keeps_room_grant_methods_on_the_adapter_class():
- expected = {
- "_room_grant_token",
- "_room_grant_secret",
- "_room_grant_claims",
- *(adapter_name for adapter_name, _ in _HANDLER_DELEGATES),
- }
- assert expected <= api_server.APIServerAdapter.__dict__.keys()
-
-
[email protected](("adapter_name", "implementation_name"), _HANDLER_DELEGATES)
-async def test_room_member_handlers_delegate_without_changing_method_surface(
- monkeypatch, adapter_name, implementation_name
-):
- adapter = api_server.APIServerAdapter.__new__(api_server.APIServerAdapter)
- request = object()
- expected = object()
- implementation = AsyncMock(return_value=expected)
- monkeypatch.setattr(room_grants, implementation_name, implementation)
-
- assert await getattr(adapter, adapter_name)(request) is expected
- implementation.assert_awaited_once_with(
- adapter,
- request,
- _openai_error=api_server._openai_error,
- _api_request_profile=api_server._api_request_profile,
- )
-
-
-def test_room_grant_helpers_delegate_through_legacy_adapter_methods(monkeypatch):
- adapter = api_server.APIServerAdapter.__new__(api_server.APIServerAdapter)
- request = object()
- token = MagicMock(return_value="grant-token")
- secret = MagicMock(return_value=b"secret")
- claims = MagicMock(return_value={"room_id": "room-1"})
- monkeypatch.setattr(room_grants, "_room_grant_token", token)
- monkeypatch.setattr(room_grants, "_room_grant_secret", secret)
- monkeypatch.setattr(room_grants, "_room_grant_claims", claims)
-
- assert adapter._room_grant_token(request) == "grant-token"
- assert adapter._room_grant_secret() == b"secret"
- assert adapter._room_grant_claims(request, permission="status") == {
- "room_id": "room-1"
- }
- token.assert_called_once_with(request)
- secret.assert_called_once_with(adapter)
- claims.assert_called_once_with(adapter, request, permission="status")
-
-
def test_grant_refresh_rejects_execution_policy_drift():
claims = {"execution_policy_digest": "a" * 64}
@@ -175,38 +116,3 @@ def test_superseded_room_authority_cannot_reuse_its_grant(tmp_path, monkeypatch)
adapter._room_grant_claims(request, permission="status")
-async def test_capability_handler_uses_legacy_claims_monkeypatch(monkeypatch):
- from gateway import hosted_rooms
-
- adapter = api_server.APIServerAdapter.__new__(api_server.APIServerAdapter)
- request = object()
- claims = {
- "room_id": "room-1",
- "home_install_id": "install-home",
- "authority_gateway_id": "gateway-home",
- "authority_epoch": 3,
- "member_id": "member-reviewer",
- "target_install_id": "install-target",
- "target_profile": "worker",
- }
- adapter._room_grant_claims = MagicMock(return_value=claims)
- monkeypatch.setattr(
- hosted_rooms,
- "local_authority_gateway_id",
- lambda: "install-target",
- )
- profile_token = api_server._api_request_profile.set("worker")
- try:
- response = await adapter._handle_room_member_capabilities(request)
- finally:
- api_server._api_request_profile.reset(profile_token)
-
- body = json.loads(response.text)
- assert response.status == 200
- assert body["object"] == "hermes.room_member.capabilities"
- assert body["target_profile"] == "worker"
- adapter._room_grant_claims.assert_called_once_with(
- request,
- permission="status",
- )
diff --git a/tests/gateway/test_api_server_run_idempotency.py b/tests/gateway/test_api_server_run_idempotency.py
deleted file mode 100644
index 53275d828af..00000000000
--- a/tests/gateway/test_api_server_run_idempotency.py
+++ /dev/null
@@ -1,43 +0,0 @@
-"""Extraction seams and lifecycle coverage for API run idempotency."""
-
-from unittest.mock import MagicMock
-
-import pytest
-
-from gateway.config import Platform, PlatformConfig
-from gateway.platforms import api_server
-
-
-async def test_api_server_constructor_uses_module_run_store_binding(monkeypatch):
- store = MagicMock()
- store_factory = MagicMock(return_value=store)
- monkeypatch.setattr(api_server, "RunIdempotencyStore", store_factory)
-
- adapter = api_server.APIServerAdapter(PlatformConfig(enabled=True))
- try:
- store_factory.assert_called_once_with()
- assert adapter._run_idempotency_store is store
- finally:
- await adapter.disconnect()
- store.close.assert_called_once_with()
-
-
-async def test_disconnect_tolerates_bare_fixture_without_run_idempotency_store():
- adapter = api_server.APIServerAdapter.__new__(api_server.APIServerAdapter)
- adapter.platform = Platform.API_SERVER
- adapter._mark_disconnected = MagicMock()
- adapter._close_cached_session_dbs = MagicMock()
- adapter._response_store = MagicMock()
- adapter._site = None
- adapter._runner = None
- adapter._app = object()
-
- assert not hasattr(adapter, "_run_idempotency_store")
- await adapter.disconnect()
-
- adapter._mark_disconnected.assert_called_once_with()
- adapter._response_store.close.assert_called_once_with()
- adapter._close_cached_session_dbs.assert_called_once_with()
- assert adapter._app is None
diff --git a/tests/gateway/test_api_server_runs.py b/tests/gateway/test_api_server_runs.py
index 0a85ddadfd3..73172bd7479 100644
--- a/tests/gateway/test_api_server_runs.py
+++ b/tests/gateway/test_api_server_runs.py
@@ -298,7 +298,6 @@ class TestStartRun:
assert resp.status == 400
body = await resp.json()
assert body["error"]["code"] == "invalid_author"
- assert body["error"]["message"] == "author must be an object"
mock_create.assert_not_called()
assert adapter._run_statuses == {}
@@ -1677,19 +1676,6 @@ class TestRunIdempotency:
assert body["status"] == "interrupted"
assert body["last_event"] == "run.interrupted"
- def test_progress_event_does_not_fsync_unchanged_running_status(self, adapter):
- adapter._run_statuses["run_progress"] = {
- "run_id": "run_progress",
- "status": "running",
- }
- adapter._run_idempotency_ids.add("run_progress")
- adapter._run_idempotency_store.update_status = MagicMock()
-
- adapter._set_run_status(
- "run_progress", "running", last_event="tool.completed"
- )
-
- adapter._run_idempotency_store.update_status.assert_not_called()
def test_status_sweep_prunes_in_memory_ownership_mirrors(self, adapter):
adapter._run_statuses["run_old"] = {
@@ -1705,33 +1691,6 @@ class TestRunIdempotency:
assert "run_old" not in adapter._run_idempotency_ids
assert "run_old" not in adapter._run_owners
- @pytest.mark.asyncio
- async def test_no_session_id_does_not_load_session_history(
- self, adapter, tmp_path
- ):
- _use_idempotency_db(adapter, tmp_path / "idem.db")
- history = AsyncMock(return_value=[])
- app = _create_runs_app(adapter)
- async with TestClient(TestServer(app)) as cli:
- with (
- patch.object(
- adapter,
- "_conversation_history_for_session",
- new=history,
- ),
- patch.object(adapter, "_create_agent") as create,
- ):
- agent = MagicMock()
- agent.run_conversation.return_value = {"final_response": "done"}
- agent.session_prompt_tokens = agent.session_completion_tokens = (
- agent.session_total_tokens
- ) = 0
- create.return_value = agent
- response = await cli.post(
- "/v1/runs", json={"input": "no stored session"}
- )
- assert response.status == 202
- history.assert_not_awaited()
class TestHostedRoomRuns:
@@ -2052,8 +2011,7 @@ class TestHostedRoomRuns:
async def test_scoped_grant_refresh_fails_after_secret_rotation(
self, auth_adapter, monkeypatch
):
- from gateway import hosted_rooms
- from gateway.hosted_room_peer import decode_room_grant, issue_room_grant
+ from gateway.hosted_room_peer import issue_room_grant
from gateway.hosted_rooms import local_authority_gateway_id
monkeypatch.setattr("gateway.platforms.api_server.time.time", lambda: 200)
diff --git a/tests/gateway/test_api_server_runs_extraction.py b/tests/gateway/test_api_server_runs_extraction.py
deleted file mode 100644
index 2709321e19a..00000000000
--- a/tests/gateway/test_api_server_runs_extraction.py
+++ /dev/null
@@ -1,182 +0,0 @@
-"""Compatibility seams for the extracted ``/v1/runs`` lifecycle."""
-
-import sys
-from types import SimpleNamespace
-from unittest.mock import AsyncMock, MagicMock
-
-import pytest
-
-from gateway.platforms import api_server
-from gateway.platforms import api_server_room_grants
-from gateway.platforms import api_server_runs
-
-
-_HTTP_HANDLER_DELEGATES = (
- ("_handle_get_run", "_handle_get_run"),
- ("_handle_run_events", "_handle_run_events"),
- ("_handle_run_approval", "_handle_run_approval"),
- ("_handle_steer_run", "_handle_steer_run"),
- ("_handle_stop_run", "_handle_stop_run"),
-)
-
-_RUN_METHODS = {
- "_set_run_status",
- "_make_run_event_callback",
- "_run_idempotency_scope",
- "_check_run_auth",
- "_durable_run_status",
- "_handle_runs",
- "_request_owns_run",
- *(adapter_name for adapter_name, _ in _HTTP_HANDLER_DELEGATES),
- "_sweep_orphaned_runs",
- "_sweep_orphaned_runs_once",
-}
-
-
-def test_api_server_keeps_run_methods_on_the_adapter_class():
- assert _RUN_METHODS <= api_server.APIServerAdapter.__dict__.keys()
-
-
[email protected](("adapter_name", "implementation_name"), _HTTP_HANDLER_DELEGATES)
-async def test_run_http_handlers_delegate_without_changing_method_surface(
- monkeypatch, adapter_name, implementation_name
-):
- adapter = api_server.APIServerAdapter.__new__(api_server.APIServerAdapter)
- request = object()
- expected = object()
- implementation = AsyncMock(return_value=expected)
- monkeypatch.setattr(api_server_runs, implementation_name, implementation)
-
- assert await getattr(adapter, adapter_name)(request) is expected
- implementation.assert_awaited_once_with(
- adapter,
- request,
- _api_server=sys.modules[api_server.__name__],
- )
-
-
-async def test_decorated_run_admission_delegates_and_releases_slot(monkeypatch):
- adapter = api_server.APIServerAdapter.__new__(api_server.APIServerAdapter)
- adapter._room_grant_token = MagicMock(return_value="room-grant")
- adapter._check_run_auth = MagicMock(return_value=None)
- adapter._draining_response = MagicMock(return_value=None)
- adapter._pending_agent_requests = 0
- request = SimpleNamespace(path="/v1/runs")
- expected = object()
- implementation = AsyncMock(return_value=expected)
- monkeypatch.setattr(api_server_runs, "_handle_runs", implementation)
-
- assert await adapter._handle_runs(request) is expected
- implementation.assert_awaited_once_with(
- adapter,
- request,
- _api_server=sys.modules[api_server.__name__],
- )
- adapter._check_run_auth.assert_called_once_with(request, permission="dispatch")
- assert adapter._pending_agent_requests == 0
-
-
-def test_run_status_method_delegates(monkeypatch):
- adapter = api_server.APIServerAdapter.__new__(api_server.APIServerAdapter)
- expected = {"run_id": "run-1", "status": "running"}
- implementation = MagicMock(return_value=expected)
- monkeypatch.setattr(api_server_runs, "_set_run_status", implementation)
-
- assert adapter._set_run_status("run-1", "running", last_event="run.started") is expected
- implementation.assert_called_once_with(
- adapter,
- "run-1",
- "running",
- last_event="run.started",
- )
-
-
-def test_room_scoped_run_policy_delegates_with_legacy_api_bindings(monkeypatch):
- adapter = api_server.APIServerAdapter.__new__(api_server.APIServerAdapter)
- request = object()
- scope = MagicMock(return_value="scope-hash")
- auth = MagicMock(return_value=None)
- monkeypatch.setattr(api_server_runs, "_run_idempotency_scope", scope)
- monkeypatch.setattr(api_server_runs, "_check_run_auth", auth)
-
- assert adapter._run_idempotency_scope(request) == "scope-hash"
- assert adapter._check_run_auth(request, permission="stop") is None
- scope.assert_called_once_with(
- adapter,
- request,
- _api_server=sys.modules[api_server.__name__],
- )
- auth.assert_called_once_with(
- adapter,
- request,
- permission="stop",
- _api_server=sys.modules[api_server.__name__],
- )
-
-
-def test_run_state_initialization_and_teardown_are_shard_owned():
- adapter = api_server.APIServerAdapter.__new__(api_server.APIServerAdapter)
- store = MagicMock()
- store_factory = MagicMock(return_value=store)
-
- api_server_runs._initialize_run_state(
- adapter,
- store_factory=store_factory,
- )
-
- store_factory.assert_called_once_with()
- assert adapter._run_idempotency_store is store
- assert adapter._run_idempotency_ids == set()
- assert adapter._run_owners == {}
- assert adapter._run_streams == {}
- assert adapter._run_streams_created == {}
- assert adapter._run_stream_subscribers == set()
- assert adapter._active_run_agents == {}
- assert adapter._active_run_tasks == {}
- assert adapter._stopping_run_ids == set()
- assert adapter._run_statuses == {}
- assert adapter._run_approval_sessions == {}
-
- api_server_runs._close_run_state(adapter)
- store.close.assert_called_once_with()
-
-
-def test_run_capability_metadata_is_shard_owned():
- adapter = api_server.APIServerAdapter.__new__(api_server.APIServerAdapter)
- adapter._run_idempotency_store = SimpleNamespace(durable=True)
- store_type = SimpleNamespace(RETENTION_SECONDS=123)
-
- assert api_server_runs._idempotency_capabilities(
- adapter,
- store_type=store_type,
- ) == {
- "supported": True,
- "durable": True,
- "retention_seconds": 123,
- }
-
-
-def test_roomlink_and_run_route_tuples_are_shard_owned():
- adapter = api_server.APIServerAdapter.__new__(api_server.APIServerAdapter)
-
- room_routes = api_server_room_grants._http_routes(adapter)
- run_routes = api_server_runs._http_routes(adapter)
-
- assert [(method, path) for method, path, _ in room_routes] == [
- ("POST", "/v1/room-members/invitations"),
- ("GET", "/v1/room-members/capabilities"),
- ("POST", "/v1/room-members/grants/refresh"),
- ("POST", "/v1/room-members/grants/revoke"),
- ]
- assert [(method, path) for method, path, _ in run_routes] == [
- ("POST", "/v1/runs"),
- ("GET", "/v1/runs/{run_id}"),
- ("GET", "/v1/runs/{run_id}/events"),
- ("POST", "/v1/runs/{run_id}/approval"),
- ("POST", "/v1/runs/{run_id}/steer"),
- ("POST", "/v1/runs/{run_id}/stop"),
- ]
- assert all(handler.__self__ is adapter for _, _, handler in room_routes)
- assert all(handler.__self__ is adapter for _, _, handler in run_routes)
diff --git a/tests/gateway/test_api_server_toolset.py b/tests/gateway/test_api_server_toolset.py
index debdbbfb52c..f554595e6db 100644
--- a/tests/gateway/test_api_server_toolset.py
+++ b/tests/gateway/test_api_server_toolset.py
@@ -1,37 +1,8 @@
"""Tests for hermes-api-server toolset and API server tool availability."""
-from unittest.mock import patch, MagicMock
-from toolsets import resolve_toolset, get_toolset, validate_toolset
-class TestHermesApiServerToolset:
- """Tests for the hermes-api-server toolset definition."""
-
-
- def test_toolset_includes_web_tools(self):
- tools = resolve_toolset("hermes-api-server")
- assert "web_search" in tools
- assert "web_extract" in tools
-
- def test_toolset_includes_core_tools(self):
- tools = resolve_toolset("hermes-api-server")
- expected = [
- "terminal", "process_manage",
- "read_file", "write_file", "patch", "search_files",
- "vision_analyze", "image_generate",
- "execute_code", "delegate_task",
- "todo_list", "memory", "session_search", "cronjob_manage",
- ]
- for tool in expected:
- assert tool in tools, f"Missing expected tool: {tool}"
-
- def test_toolset_includes_browser_tools(self):
- tools = resolve_toolset("hermes-api-server")
- for tool in ["browser_navigate", "browser_snapshot", "browser_click",
- "browser_type", "browser_scroll", "browser_back",
- "browser_press"]:
- assert tool in tools, f"Missing browser tool: {tool}"
class TestApiServerPlatformConfig:
@@ -49,34 +20,4 @@ class TestApiServerPlatformConfig:
assert "terminal" in _get_platform_tools({}, "api_server")
-class TestApiServerAdapterToolset:
- @patch("gateway.platforms.api_server.AIOHTTP_AVAILABLE", True)
- def test_create_agent_reads_config_toolsets(self):
- """API server resolves toolsets from config like all other platforms."""
- from gateway.platforms.api_server import APIServerAdapter
- from gateway.config import PlatformConfig
-
- adapter = APIServerAdapter(PlatformConfig())
-
- with patch("gateway.run._resolve_runtime_agent_kwargs") as mock_kwargs, \
- patch("gateway.run._resolve_gateway_model") as mock_model, \
- patch("gateway.run._load_gateway_config") as mock_config, \
- patch("run_agent.AIAgent") as mock_agent_cls:
-
- mock_kwargs.return_value = {"api_key": "test-key", "base_url": None,
- "provider": None, "api_mode": None,
- "command": None, "args": []}
- mock_model.return_value = "test/model"
- # No platform_toolsets override — should fall back to hermes-api-server default
- mock_config.return_value = {}
- mock_agent_cls.return_value = MagicMock()
-
- adapter._create_agent()
-
- mock_agent_cls.assert_called_once()
- call_kwargs = mock_agent_cls.call_args
- toolsets = call_kwargs.kwargs.get("enabled_toolsets")
- assert isinstance(toolsets, list)
- assert len(toolsets) > 0
- assert call_kwargs.kwargs.get("platform") == "api_server"
diff --git a/tests/gateway/test_approval_boundary.py b/tests/gateway/test_approval_boundary.py
index c4cfa956fa2..341ec2bc22d 100644
--- a/tests/gateway/test_approval_boundary.py
+++ b/tests/gateway/test_approval_boundary.py
@@ -1,7 +1,7 @@
"""Tests for approval boundary handling in WeCom native streaming."""
import asyncio
import pytest
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import AsyncMock, MagicMock
from gateway.stream_consumer import GatewayStreamConsumer, StreamConsumerConfig
@@ -173,55 +173,6 @@ async def test_boundary_uses_custom_placeholder_when_no_accumulated(mock_adapter
pass
-async def test_clarify_boundary_logs_use_clarify_prefix(mock_adapter, consumer_config, caplog):
- """A clarify boundary that fails to finalize must log with a "Clarify"
- prefix, not "Approval" — otherwise a clarify failure looks like a
- dangerous-command approval failure during troubleshooting."""
- import logging
-
- # Make finalize fail so the warning path fires, and the fallback send fail
- # too so the error path fires — exercising the reason-labelled logs.
- mock_adapter.send_stream_frame = AsyncMock(return_value=False)
- mock_adapter.send = AsyncMock(return_value=MagicMock(success=False))
-
- consumer = GatewayStreamConsumer(
- adapter=mock_adapter,
- chat_id="test_chat",
- config=consumer_config,
- )
- consumer._use_native_streaming = True
- consumer._native_stream_opened = True
- consumer._turn_id = "turn_123"
- consumer._accumulated = "部分内容"
-
- boundary_result = consumer.close_for_approval_prompt(
- "💬 等待你的选择...", reason="Clarify",
- )
- if isinstance(boundary_result, tuple):
- boundary_future, _ = boundary_result
- else:
- boundary_future = boundary_result
-
- with caplog.at_level(logging.WARNING, logger="gateway.stream_consumer"):
- consumer_task = asyncio.create_task(consumer.run())
- await asyncio.wait_for(boundary_future, timeout=1.0)
-
- boundary_logs = [r.getMessage() for r in caplog.records]
- assert any("Clarify boundary" in m for m in boundary_logs), (
- f"Expected a 'Clarify boundary' log, got: {boundary_logs}"
- )
- assert not any("Approval boundary" in m for m in boundary_logs), (
- f"Clarify boundary must not log as 'Approval boundary': {boundary_logs}"
- )
-
- consumer.finish()
- await asyncio.sleep(0.05)
- consumer_task.cancel()
- try:
- await consumer_task
- except asyncio.CancelledError:
- pass
@pytest.mark.asyncio
diff --git a/tests/gateway/test_approval_prompt_redaction.py b/tests/gateway/test_approval_prompt_redaction.py
index 0f283de046c..6426def4e5b 100644
--- a/tests/gateway/test_approval_prompt_redaction.py
+++ b/tests/gateway/test_approval_prompt_redaction.py
@@ -60,70 +60,6 @@ class TestRedactApprovalCommand:
assert _FAKE_GHP not in out
-class TestApprovalCommandWiring:
- """Guard the production wiring on BOTH approval-notify transports:
- 1. the chat-platform path (_approval_notify_sync in gateway/run.py), and
- 2. the SSE/API path (_approval_notify in
- gateway/platforms/api_server_runs.py),
- each of which must route the command through _redact_approval_command and
- REASSIGN the redacted value before any send/enqueue (so the raw command
- cannot reach a client). Uses AST (not char-offset string slicing) so a
- benign refactor doesn't cause a false failure, and so a discarded-result
- call (`_redact(cmd); send(cmd)`) does NOT pass."""
-
- def _assert_redacts_then_uses(self, module, func_name: str, sink_substr: str):
- """Parse `module`'s full AST, locate the (possibly nested) function
- `func_name`, and assert it contains an assignment
- `<x> = _redact_approval_command(...)` whose result is then used by a
- statement matching `sink_substr` on a LATER line. Walking the real AST
- (not a source slice) is refactor-robust and rejects discarded-result
- calls (the call must be an assignment, not a bare expression)."""
- import ast
- import inspect
-
- source = inspect.getsource(module)
- tree = ast.parse(source)
- target_fn = None
- for node in ast.walk(tree):
- if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == func_name:
- target_fn = node
- break
- assert target_fn is not None, f"function {func_name} not found in {module.__name__}"
-
- redact_line = None
- for node in ast.walk(target_fn):
- if isinstance(node, ast.Assign) and isinstance(node.value, ast.Call):
- fn = node.value.func
- if isinstance(fn, ast.Name) and fn.id == "_redact_approval_command":
- redact_line = node.lineno
- assert redact_line is not None, (
- f"{func_name} must assign the result of _redact_approval_command(...) "
- "(a discarded-result call would still leak the raw command)"
- )
-
- sink_line = None
- for node in ast.walk(target_fn):
- seg = ast.get_source_segment(source, node)
- if seg and sink_substr in seg and getattr(node, "lineno", 0) > redact_line:
- sink_line = node.lineno
- break
- assert sink_line is not None, (
- f"`{sink_substr}` sink not found after the redaction in {func_name}"
- )
-
- def test_chat_platform_path_redacts_before_send(self):
- import gateway.run_turn_runner as run
-
- self._assert_redacts_then_uses(run, "_approval_notify_sync", "send_exec_approval")
-
- def test_sse_api_path_redacts_before_enqueue(self):
- from gateway.platforms import api_server_runs
-
- self._assert_redacts_then_uses(
- api_server_runs, "_approval_notify", "put_nowait"
- )
-
-
class TestApprovalTextFallbackContract:
def test_smart_deny_only_advertises_one_operation(self):
from gateway.run import _format_exec_approval_fallback
@@ -132,8 +68,6 @@ class TestApprovalTextFallbackContract:
"rm -rf /", "dangerous deletion", "/",
allow_permanent=False, smart_denied=True,
)
- assert "owner override" in text.lower()
- assert "one operation" in text.lower()
assert "`/approve`" in text
assert "approve session" not in text
assert "approve always" not in text
@@ -144,9 +78,8 @@ class TestApprovalTextFallbackContract:
monkeypatch.setattr("gateway.platforms.base_exec_approval.approval_timeout_seconds", lambda: 300)
text = _format_exec_approval_fallback("rm -rf /", "recursive delete", "/")
- assert "Hermes wants to run a command that needs your OK" in text
- assert "Why it was flagged: recursive delete" in text
- assert "If you don't answer within 5 minutes it will NOT run." in text
+ assert "recursive delete" in text
+ assert "5 minutes" in text
for step in ("`/approve`", "`/approve session`", "`/approve always`", "`/deny`"):
assert step in text
diff --git a/tests/gateway/test_async_delegation_session_binding.py b/tests/gateway/test_async_delegation_session_binding.py
index 9bfc763ece1..840b8f789bf 100644
--- a/tests/gateway/test_async_delegation_session_binding.py
+++ b/tests/gateway/test_async_delegation_session_binding.py
@@ -8,7 +8,7 @@ Three invariants on the messaging-gateway surface, mirroring the TUI rules:
3. /new interrupts the old conversation's in-flight async delegations.
"""
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import AsyncMock, MagicMock
import pytest
@@ -208,15 +208,6 @@ class TestGatewayPinningFailsClosed:
).assert_called_once_with(current.session_key, "sess_parent", "sess_tip")
-class TestResetHandlerInterruptsDelegations:
- def test_reset_command_calls_interrupt_for_session(self):
- """The /new handler must sever the old conversation's delegations."""
- import inspect
- from gateway import slash_commands
-
- src = inspect.getsource(slash_commands.GatewaySlashCommandsMixin._handle_reset_command)
- assert "interrupt_for_session" in src
- assert "session_reset" in src
@pytest.mark.asyncio
diff --git a/tests/gateway/test_async_session_db.py b/tests/gateway/test_async_session_db.py
index dadd8e7fbe2..f84680c0138 100644
--- a/tests/gateway/test_async_session_db.py
+++ b/tests/gateway/test_async_session_db.py
@@ -1,15 +1,13 @@
-"""AsyncSessionDB offload facade + gateway raw-call guard.
+"""AsyncSessionDB offload facade.
The gateway runs one asyncio loop for every session; SessionDB is synchronous,
so a raw call on the loop freezes every conversation until it returns.
AsyncSessionDB offloads each call via asyncio.to_thread. These tests pin the
-facade's contract and lock the gateway boundary so a 39th raw call can't regress.
+facade's contract.
"""
-import ast
import asyncio
import threading
-from pathlib import Path
import pytest
@@ -69,238 +67,6 @@ async def test_offloads_off_calling_thread():
assert ran_idents and all(i != caller_ident for i in ran_idents)
-async def test_offload_goes_through_to_thread(monkeypatch):
- """The offload must route through asyncio.to_thread (where the facade lives)."""
- db = _SpyDB()
- facade = AsyncSessionDB(db)
-
- seen = []
- real = asyncio.to_thread
-
- async def _spy(func, *args, **kwargs):
- seen.append(getattr(func, "__name__", repr(func)))
- return await real(func, *args, **kwargs)
-
- monkeypatch.setattr(hermes_state.asyncio, "to_thread", _spy)
- await facade.returns_str()
- assert "returns_str" in seen
-
-
-# --------------------------------------------------------------------------
-# Guard: no raw self._session_db.<method>( on the gateway loop
-# --------------------------------------------------------------------------
-
-_GATEWAY_FILES = ("gateway/run.py", "gateway/slash_commands.py")
-# The only legitimate non-loop paths:
-# - SessionDB.sanitize_title: pure @staticmethod string cleaning, no DB.
-# - self._session_db._db.<x>: the sync escape, allowed ONLY where the call is
-# provably off the event loop — construction (__init__, before the loop
-# serves) and the run_sync closure (executed in a thread-pool executor).
-# Four such sites today (maybe_auto_archive joined maybe_auto_prune_and_vacuum
-# in the construction-time maintenance block); a fifth must be justified and
-# this count bumped.
-_ALLOWED_SYNC_DB_ESCAPES = 4
-
-# Sync helpers that touch SessionDB but are NEVER invoked bare on the loop:
-# every loop-side call wraps them in ``asyncio.to_thread(...)`` and the only
-# bare calls live in the run_sync thread-pool closure. Their DB calls therefore
-# run off-loop. The guard exempts their bodies AND enforces the contract — see
-# test_offloaded_helpers_never_called_bare_on_loop. Adding a helper here without
-# wrapping its loop call sites makes that test fail.
-_OFFLOADED_SYNC_HELPERS = frozenset({
- "_telegram_topic_mode_enabled",
- "_is_telegram_topic_lane",
- "_is_telegram_topic_root_lobby",
- "_recover_telegram_topic_thread_id",
- "_normalize_source_for_session_key",
- "_record_telegram_topic_binding",
- "_sync_telegram_topic_binding",
- "_telegram_topic_new_header",
- "_schedule_telegram_topic_title_rename",
- "_apply_topic_recovery",
-})
-
-
-def _repo_root() -> Path:
- return Path(__file__).resolve().parents[2]
-
-
-class _RawCallVisitor:
- """Collect non-awaited SessionDB calls reachable on the gateway loop.
-
- Catches both shapes:
- * direct: self._session_db.<method>(...)
- * aliased: db = getattr(self, "_session_db", None) / db = self._session_db
- then db.<method>(...)
- An ``await x.y()`` is Await(value=Call(...)); those Calls are exempt (the
- migrated path). The self._session_db._db.<x> sync escape is counted
- separately. SessionDB.sanitize_title is a staticmethod called on the class,
- so it never matches either shape.
-
- Alias detection scans, per function scope, for locals bound to the gateway's
- _session_db (incl. closures that bind it off a captured ``self``-like param),
- then flags non-awaited calls on those names. The literal-grep blind spot that
- let six loop-reachable calls hide behind ``getattr(self, "_session_db")`` is
- exactly what this closes.
- """
-
- def __init__(self, tree: ast.AST):
- self.raw_calls = [] # (method, lineno) — direct, non-awaited, on-loop
- self.alias_calls = [] # (method, lineno) — via a _session_db-bound local, on-loop
- self.db_escapes = [] # self._session_db._db.<x> sites (lineno)
- # BARE self.<helper>(...) call sites of offloaded helpers — i.e. the
- # helper is actually *called*, not passed to asyncio.to_thread (which
- # references it as an attribute, producing no Call node here). Each is
- # (helper, lineno, enclosing_fn) for the contract test.
- self.bare_helper_calls = []
-
- awaited = {id(n.value) for n in ast.walk(tree)
- if isinstance(n, ast.Await) and isinstance(n.value, ast.Call)}
- alias_names = self._collect_alias_names(tree)
- # Map each node to the name of the function whose body lexically encloses
- # it, so DB calls inside an offloaded helper (which runs off-loop) are
- # exempt while bare on-loop calls are not.
- enclosing = self._enclosing_fn_map(tree)
- ancestry = self._ancestor_fns(tree) # id(node) -> frozenset of enclosing fn names
-
- for node in ast.walk(tree):
- if not isinstance(node, ast.Call):
- continue
- func = node.func
- if not isinstance(func, ast.Attribute):
- continue
- encl_fn = enclosing.get(id(node))
- in_offloaded_helper = encl_fn in _OFFLOADED_SYNC_HELPERS
- # Bare call of an offloaded helper (self._helper(...)). A to_thread
- # offload passes the helper as an attribute arg, not a Call, so it
- # never lands here — exactly the distinction the contract test needs.
- if (
- isinstance(func.value, ast.Name) and func.value.id == "self"
- and func.attr in _OFFLOADED_SYNC_HELPERS
- ):
- self.bare_helper_calls.append(
- (func.attr, node.lineno, ancestry.get(id(node), frozenset()))
- )
- # alias.<method>(...) -> aliased loop call (var bound to _session_db)
- if (
- isinstance(func.value, ast.Name)
- and func.value.id in alias_names
- and func.attr not in ("_db",)
- and id(node) not in awaited
- and not in_offloaded_helper
- ):
- self.alias_calls.append((func.attr, node.lineno))
- continue
- if not isinstance(func.value, ast.Attribute):
- continue
- inner = func.value
- # self._session_db._db.<method>(...) -> sync escape
- if (
- inner.attr == "_db"
- and isinstance(inner.value, ast.Attribute)
- and inner.value.attr == "_session_db"
- and isinstance(inner.value.value, ast.Name)
- and inner.value.value.id == "self"
- ):
- self.db_escapes.append(inner.lineno)
- # self._session_db.<method>(...) not wrapped in await -> raw loop call
- elif (
- inner.attr == "_session_db"
- and isinstance(inner.value, ast.Name)
- and inner.value.id == "self"
- and id(node) not in awaited
- and not in_offloaded_helper
- ):
- self.raw_calls.append((func.attr, node.lineno))
-
- @staticmethod
- def _enclosing_fn_map(tree: ast.AST) -> dict:
- """Map id(node) -> name of the nearest lexically-enclosing function."""
- out = {}
-
- def walk(node, fn_name):
- this_fn = fn_name
- if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
- this_fn = node.name
- for child in ast.iter_child_nodes(node):
- out[id(child)] = this_fn
- walk(child, this_fn)
-
- walk(tree, None)
- return out
-
- @staticmethod
- def _ancestor_fns(tree: ast.AST) -> dict:
- """Map id(node) -> frozenset of ALL enclosing function names (any depth)."""
- out = {}
-
- def walk(node, stack):
- if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
- stack = stack + (node.name,)
- for child in ast.iter_child_nodes(node):
- out[id(child)] = frozenset(stack)
- walk(child, stack)
-
- walk(tree, ())
- return out
-
- @staticmethod
- def _is_session_db_source(value: ast.AST) -> bool:
- """True if an assignment RHS resolves to <obj>._session_db.
-
- Matches both ``<obj>._session_db`` and ``getattr(<obj>, "_session_db", ...)``
- where <obj> is any Name (covers ``self`` and captured closure params like
- ``_self``). Excludes the ``._db`` sync handle.
- """
- if isinstance(value, ast.Attribute):
- return value.attr == "_session_db" and isinstance(value.value, ast.Name)
- if (
- isinstance(value, ast.Call)
- and isinstance(value.func, ast.Name)
- and value.func.id == "getattr"
- and len(value.args) >= 2
- and isinstance(value.args[1], ast.Constant)
- and value.args[1].value == "_session_db"
- ):
- return True
- return False
-
- @classmethod
- def _collect_alias_names(cls, tree: ast.AST) -> set:
- names = set()
- for node in ast.walk(tree):
- if isinstance(node, ast.Assign) and cls._is_session_db_source(node.value):
- for tgt in node.targets:
- if isinstance(tgt, ast.Name):
- names.add(tgt.id)
- elif isinstance(node, ast.AnnAssign) and node.value is not None \
- and cls._is_session_db_source(node.value) \
- and isinstance(node.target, ast.Name):
- names.add(node.target.id)
- return names
-
-
-def _scan(rel_path: str) -> _RawCallVisitor:
- source = (_repo_root() / rel_path).read_text(encoding="utf-8")
- return _RawCallVisitor(ast.parse(source))
-
-
-def test_sync_db_escape_confined_to_off_loop_sites():
- """The self._session_db._db. sync escape must stay confined to known sites.
-
- It is legitimate only where the call is provably off the loop: construction
- (before the loop serves) and the run_sync executor closure. More occurrences
- than the reviewed count means a blocking call may have leaked back onto the
- loop through the escape hatch.
- """
- total = sum(len(_scan(rel).db_escapes) for rel in _GATEWAY_FILES)
- assert total <= _ALLOWED_SYNC_DB_ESCAPES, (
- f"self._session_db._db. sync escape used {total} times; "
- f"at most {_ALLOWED_SYNC_DB_ESCAPES} (construction + run_sync) is allowed."
- )
-
-
# --------------------------------------------------------------------------
# Interleaving safety: offloading opens await points where coroutines can
# interleave against the same session rows. The gateway relies on SessionDB's
diff --git a/tests/gateway/test_async_session_store.py b/tests/gateway/test_async_session_store.py
deleted file mode 100644
index 1d51004392b..00000000000
--- a/tests/gateway/test_async_session_store.py
+++ /dev/null
@@ -1,99 +0,0 @@
-"""Async SessionStore boundary for gateway event-loop safety."""
-
-import ast
-import asyncio
-import threading
-from pathlib import Path
-
-import pytest
-
-from gateway.session import AsyncSessionStore
-
-
-class _SpyStore:
- def __init__(self) -> None:
- self.calls: list[tuple[str, int]] = []
- self.label = "store"
-
- def read(self, value: str) -> str:
- self.calls.append((value, threading.get_ident()))
- return value
-
-
-def _nearest_function(node: ast.AST, parents: dict[ast.AST, ast.AST]):
- current = node
- while current in parents:
- current = parents[current]
- if isinstance(current, (ast.FunctionDef, ast.AsyncFunctionDef)):
- return current
- return None
-
-
-def _is_awaited(node: ast.AST, parents: dict[ast.AST, ast.AST]) -> bool:
- current = node
- while current in parents:
- current = parents[current]
- if isinstance(current, ast.Await):
- return True
- if isinstance(current, (ast.FunctionDef, ast.AsyncFunctionDef)):
- return False
- return False
-
-
-def test_gateway_async_code_uses_one_awaited_session_store_boundary() -> None:
- """Loop-side store calls must use the facade; raw store remains sync-only."""
- root = Path(__file__).resolve().parents[2]
- violations: list[str] = []
- for rel in ("gateway/run.py", "gateway/slash_commands.py"):
- tree = ast.parse((root / rel).read_text(encoding="utf-8"))
- parents = {
- child: parent
- for parent in ast.walk(tree)
- for child in ast.iter_child_nodes(parent)
- }
- for owner in (node for node in ast.walk(tree) if isinstance(node, ast.AsyncFunctionDef)):
- raw_aliases = {
- target.id
- for node in ast.walk(owner)
- if isinstance(node, ast.Assign)
- and isinstance(node.value, ast.Attribute)
- and isinstance(node.value.value, ast.Name)
- and node.value.value.id in {"self", "_self"}
- and node.value.attr == "session_store"
- for target in node.targets
- if isinstance(target, ast.Name)
- }
- for node in ast.walk(owner):
- if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Attribute):
- continue
- if _nearest_function(node, parents) is not owner:
- # A nested sync helper (for example run_sync) executes off-loop.
- continue
- receiver = node.func.value
- if isinstance(receiver, ast.Name) and receiver.id in raw_aliases:
- violations.append(
- f"{rel}:{node.lineno} raw alias {receiver.id}.{node.func.attr}() in async {owner.name}"
- )
- continue
- if not (
- isinstance(receiver, ast.Attribute)
- and isinstance(receiver.value, ast.Name)
- and receiver.value.id in {"self", "_self"}
- ):
- continue
- if receiver.attr == "session_store":
- violations.append(
- f"{rel}:{node.lineno} raw session_store.{node.func.attr}() in async {owner.name}"
- )
- elif receiver.attr == "async_session_store" and not _is_awaited(
- node, parents
- ):
- violations.append(
- f"{rel}:{node.lineno} unawaited async_session_store.{node.func.attr}()"
- )
- assert not violations, "\n".join(violations)
-
-
-def test_no_repository_local_claude_permissions_file() -> None:
- root = Path(__file__).resolve().parents[2]
- assert not (root / ".claude" / "settings.json").exists()
diff --git a/tests/gateway/test_audio_cache.py b/tests/gateway/test_audio_cache.py
index 9541e0f0d2a..3a449f5b3af 100644
--- a/tests/gateway/test_audio_cache.py
+++ b/tests/gateway/test_audio_cache.py
@@ -32,11 +32,6 @@ def _redirect_cache(tmp_path, monkeypatch):
# TestGetAudioCacheDir
# ---------------------------------------------------------------------------
-class TestGetAudioCacheDir:
- def test_creates_directory(self):
- cache_dir = get_audio_cache_dir()
- assert cache_dir.exists()
- assert cache_dir.is_dir()
# ---------------------------------------------------------------------------
@@ -50,9 +45,6 @@ class TestCacheAudioFromBytes:
assert os.path.exists(path)
assert Path(path).read_bytes() == data
- def test_default_extension(self):
- path = cache_audio_from_bytes(b"data")
- assert path.endswith(".ogg")
# ---------------------------------------------------------------------------
diff --git a/tests/gateway/test_auto_continue.py b/tests/gateway/test_auto_continue.py
index 1e2349fa630..8f4871a5a48 100644
--- a/tests/gateway/test_auto_continue.py
+++ b/tests/gateway/test_auto_continue.py
@@ -26,28 +26,6 @@ def _simulate_auto_continue(agent_history: list, user_message: str) -> str:
return message
-class TestAutoDetection:
- """Test that trailing tool results are correctly detected."""
-
- def test_trailing_tool_result_triggers_note(self):
- history = [
- {"role": "user", "content": "deploy the app"},
- {"role": "assistant", "content": None, "tool_calls": [
- {"id": "call_1", "function": {"name": "terminal", "arguments": "{}"}}
- ]},
- {"role": "tool", "tool_call_id": "call_1", "content": "deployed successfully"},
- ]
- result = _simulate_auto_continue(history, "what happened?")
- assert "[System note:" in result
- assert "interrupted" in result
- assert "NEW message" in result
- assert "Do NOT re-execute" in result
- assert "what happened?" in result
-
-
- def test_empty_history_no_note(self):
- result = _simulate_auto_continue([], "hello")
- assert result == "hello"
class TestInterruptedReplayFiltering:
diff --git a/tests/gateway/test_auto_reset_clean_context.py b/tests/gateway/test_auto_reset_clean_context.py
index c75b0634080..1fdc9dc27e3 100644
--- a/tests/gateway/test_auto_reset_clean_context.py
+++ b/tests/gateway/test_auto_reset_clean_context.py
@@ -19,123 +19,18 @@ guarantee regressed once the Telegram topic-binding heal landed
The fix captures the fresh entry from ``reset_session`` and re-syncs the
topic binding to it (a no-op on non-topic lanes).
-Two tests:
-
-* ``TestAutoResetBlockReSyncsBinding`` — an AST invariant on
- ``gateway/run.py`` (mirrors ``test_compression_session_id_persistence.py``):
- the compression-exhausted auto-reset block must capture
- ``reset_session(...)`` and call ``_sync_telegram_topic_binding`` afterward.
- This is the load-bearing regression pin.
-* ``TestAutoResetLoadsCleanContext`` — a behavioral contract on the real
- ``SessionStore``: after ``reset_session`` the next turn loads an EMPTY
- transcript for the new session_id, never the bloated child's transcript.
+``TestAutoResetLoadsCleanContext`` — a behavioral contract on the real
+``SessionStore``: after ``reset_session`` the next turn loads an EMPTY
+transcript for the new session_id, never the bloated child's transcript.
"""
from __future__ import annotations
-import ast
-import inspect
-
-from gateway import run as gateway_run
-from gateway import run_turn as gateway_run_turn
-from gateway import run_turn as gateway_run_turn
from gateway.config import GatewayConfig, Platform
from gateway.session import SessionSource, SessionStore
from hermes_state import SessionDB
-# ---------------------------------------------------------------------------
-# AST invariant: the auto-reset block re-syncs the topic binding
-# ---------------------------------------------------------------------------
-def _find_compression_exhausted_reset_block() -> ast.If:
- """Return the ``if agent_result.get('compression_exhausted') ...`` block."""
- tree = ast.parse(inspect.getsource(gateway_run_turn))
-
- for node in ast.walk(tree):
- if not isinstance(node, ast.If):
- continue
- consts = [
- n.value
- for n in ast.walk(node.test)
- if isinstance(n, ast.Constant) and isinstance(n.value, str)
- ]
- # Identify the auto-reset branch by the literal passed to .get(...).
- if "compression_exhausted" in consts:
- # Only the branch that actually performs the reset, not the
- # earlier classifier that merely reads the flag into a bool.
- calls = {
- sub.func.attr
- for sub in ast.walk(node)
- if isinstance(sub, ast.Call) and isinstance(sub.func, ast.Attribute)
- }
- if "reset_session" in calls:
- return node
- raise AssertionError(
- "Could not locate the compression-exhausted auto-reset block "
- "(if agent_result.get('compression_exhausted') ... reset_session) "
- "in gateway/run.py — the structure changed or the AST walker is stale."
- )
-
-
-class TestAutoResetBlockReSyncsBinding:
- def test_reset_session_return_is_captured(self):
- """``reset_session`` must be assigned, not called-and-discarded —
- the fresh entry is needed to re-point the binding and drop the stale
- reference to the bloated compressed child (#35809)."""
- block = _find_compression_exhausted_reset_block()
- captured = False
- for stmt in ast.walk(block):
- if isinstance(stmt, ast.Assign):
- val = stmt.value
- # reset_session is async at the gateway boundary, so the
- # assignment value is Await(Call(...)), not a bare Call.
- if isinstance(val, ast.Await):
- val = val.value
- if (
- isinstance(val, ast.Call)
- and isinstance(val.func, ast.Attribute)
- and val.func.attr == "reset_session"
- ):
- captured = True
- assert captured, (
- "gateway/run.py auto-reset block calls reset_session() but discards "
- "its return value. The fresh SessionEntry must be captured so the "
- "topic binding can be re-pointed at it; otherwise the next message "
- "resolves back to the bloated compressed child (#35809)."
- )
-
- def test_topic_binding_is_resynced_after_reset(self):
- """The block must re-sync the topic binding so the next inbound message
- cannot ``switch_session`` back onto the bloated compressed child."""
- block = _find_compression_exhausted_reset_block()
-
- def _references_helper(node):
- # Direct call: self._sync_telegram_topic_binding(...)
- if (
- isinstance(node, ast.Call)
- and isinstance(node.func, ast.Attribute)
- and node.func.attr == "_sync_telegram_topic_binding"
- ):
- return True
- # Offloaded: await asyncio.to_thread(self._sync_telegram_topic_binding, ...)
- # — the helper is passed as an argument, not the call's func.
- if (
- isinstance(node, ast.Attribute)
- and node.attr == "_sync_telegram_topic_binding"
- ):
- return True
- return False
-
- sync_calls = [sub for sub in ast.walk(block) if _references_helper(sub)]
- assert sync_calls, (
- "gateway/run.py auto-reset block does not call "
- "_sync_telegram_topic_binding after reset_session. Without it the "
- "(chat_id, thread_id) -> bloated-child binding survives the reset "
- "and the binding-heal walk re-anchors the fresh lane onto the "
- "oversized compressed transcript, re-triggering the loop (#35809)."
- )
-
-
# ---------------------------------------------------------------------------
# Behavioral contract: reset yields a clean next-turn transcript
# ---------------------------------------------------------------------------
diff --git a/tests/gateway/test_auto_reset_evicts_cached_agent.py b/tests/gateway/test_auto_reset_evicts_cached_agent.py
index e8a65cda89c..c8ab7a569b7 100644
--- a/tests/gateway/test_auto_reset_evicts_cached_agent.py
+++ b/tests/gateway/test_auto_reset_evicts_cached_agent.py
@@ -1,106 +1,8 @@
-"""Regression test for #10710 — stale context summary leak after auto-reset.
-
-The gateway agent cache is keyed on the stable chat ``session_key``, which does
-NOT change when a session is auto-reset (daily schedule / idle timeout /
-suspended). So unless the cached agent is explicitly evicted on auto-reset, the
-NEXT message reuses the old ``AIAgent`` instance — carrying its
-``context_compressor._previous_summary`` — and prior-conversation content leaks
-into the new session's compaction summaries.
-
-Manual ``/reset`` and the compression-exhausted path (#9893) already evict the
-cached agent. This pins the matching eviction onto the auto-reset cleanup block
-in ``_handle_message_with_agent``.
-
-These are AST invariants — load-bearing pins that fail if the eviction is
-removed from the cleanup block (mirrors
-test_48031_model_switch_after_auto_reset.py's approach).
-"""
+"""Auto-reset is a full conversation boundary: per-session caches must not
+survive it (#58403)."""
from __future__ import annotations
-import ast
-import inspect
-
from gateway import run as gateway_run
-from gateway import run_turn as gateway_run_turn
-from gateway import run_turn as gateway_run_turn
-
-
-def _calls(node: ast.AST) -> set[str]:
- """Method-call attribute names invoked anywhere under ``node``."""
- return {
- n.func.attr
- for n in ast.walk(node)
- if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute)
- }
-
-
-def _assigns_false(node: ast.AST, attr: str) -> bool:
- """True if ``node`` contains an assignment ``<something>.<attr> = False``."""
- for sub in ast.walk(node):
- if isinstance(sub, ast.Assign):
- for tgt in sub.targets:
- if (
- isinstance(tgt, ast.Attribute)
- and tgt.attr == attr
- and isinstance(sub.value, ast.Constant)
- and sub.value.value is False
- ):
- return True
- return False
-
-
-def test_auto_reset_cleanup_evicts_cached_agent():
- """The auto-reset cleanup block in gateway/run.py must call
- ``_evict_cached_agent`` so the fresh session does not reuse the previous
- conversation's cached agent (and its leaked
- ``context_compressor._previous_summary``) — the cache is keyed on the
- stable ``session_key`` (#10710)."""
- tree = ast.parse(inspect.getsource(gateway_run_turn))
-
- # Fingerprint the cleanup branch: the `if <was_auto_reset>:` block that
- # clears the conversation scope via the funnel (post-#64934 refactor:
- # one _clear_conversation_scope call replaced the inline pops) and
- # consumes the flag by setting was_auto_reset = False. The eviction must
- # live in that same block — the funnel deliberately does NOT evict the
- # agent cache (it has its own resource-cleanup path).
- found = False
- for node in ast.walk(tree):
- if not isinstance(node, ast.If):
- continue
- calls = _calls(node)
- if (
- "_clear_conversation_scope" in calls
- and _assigns_false(node, "was_auto_reset")
- ):
- assert "_evict_cached_agent" in calls, (
- "gateway/run.py auto-reset cleanup block must call "
- "`_evict_cached_agent(session_key)` so the auto-reset session "
- "does not reuse the previous cached agent and leak its "
- "context_compressor._previous_summary into new compaction "
- "summaries (#10710)."
- )
- found = True
- break
- assert found, (
- "could not locate the auto-reset transient-state cleanup block in "
- "gateway/run.py (fingerprint: _clear_conversation_scope + "
- "was_auto_reset = False)."
- )
-
-
-def test_evict_cached_agent_method_exists():
- """The eviction helper the cleanup relies on must exist on the runner."""
- assert hasattr(gateway_run.GatewayRunner, "_evict_cached_agent"), (
- "GatewayRunner._evict_cached_agent is the helper the auto-reset "
- "cleanup depends on (#10710)."
- )
-
-
-def _references_name(node: ast.AST, literal: str) -> bool:
- """True if a string constant equal to ``literal`` appears anywhere under ``node``."""
- return any(
- isinstance(n, ast.Constant) and n.value == literal for n in ast.walk(node)
- )
def test_auto_reset_cleanup_clears_last_resolved_model():
diff --git a/tests/gateway/test_background_command.py b/tests/gateway/test_background_command.py
index 6ee1ecfd228..d84681a06aa 100644
--- a/tests/gateway/test_background_command.py
+++ b/tests/gateway/test_background_command.py
@@ -4,7 +4,6 @@ Tests the _handle_background_command handler (run a prompt in a separate
background session) across gateway messenger platforms.
"""
-import asyncio
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -57,27 +56,6 @@ def _make_runner():
# ---------------------------------------------------------------------------
-class TestHandleBackgroundCommand:
- """Tests for GatewayRunner._handle_background_command."""
-
- @pytest.mark.asyncio
- async def test_no_prompt_shows_usage(self):
- """Running /bg with no prompt shows usage."""
- runner = _make_runner()
- event = _make_event(text="/bg")
- result = await runner._handle_background_command(event)
- assert "Usage:" in result
- assert "/bg" in result
-
- @pytest.mark.asyncio
- async def test_empty_prompt_shows_usage(self):
- """Running /bg with only whitespace shows usage."""
- runner = _make_runner()
- event = _make_event(text="/bg ")
- result = await runner._handle_background_command(event)
- assert "Usage:" in result
-
-
# ---------------------------------------------------------------------------
# _run_background_task
# ---------------------------------------------------------------------------
@@ -87,30 +65,6 @@ class TestRunBackgroundTask:
"""Tests for GatewayRunner._run_background_task (the actual execution)."""
- @pytest.mark.asyncio
- async def test_no_credentials_sends_error(self):
- """When provider credentials are missing, an error is sent."""
- runner = _make_runner()
- mock_adapter = AsyncMock()
- mock_adapter.send = AsyncMock()
- runner.adapters[Platform.TELEGRAM] = mock_adapter
-
- source = SessionSource(
- platform=Platform.TELEGRAM,
- user_id="12345",
- chat_id="67890",
- user_name="testuser",
- )
-
- with patch("gateway.run._resolve_runtime_agent_kwargs", return_value={"api_key": None}):
- await runner._run_background_task("test prompt", source, "bg_test")
-
- # Should have sent an error message
- mock_adapter.send.assert_called_once()
- call_args = mock_adapter.send.call_args
- content = call_args[1].get("content", call_args[0][1] if len(call_args[0]) > 1 else "")
- assert "couldn't start" in content and "/login" in content
-
@pytest.mark.asyncio
async def test_successful_task_sends_result(self):
"""When the agent completes successfully, the result is sent."""
@@ -153,7 +107,6 @@ class TestRunBackgroundTask:
mock_adapter.send.assert_called_once()
call_args = mock_adapter.send.call_args
content = call_args[1].get("content", call_args[0][1] if len(call_args[0]) > 1 else "")
- assert "Background task complete" in content
assert "Hello from background!" in content
agent_kwargs = MockAgent.call_args.kwargs
assert agent_kwargs["checkpoints_enabled"] is True
@@ -169,51 +122,11 @@ class TestRunBackgroundTask:
# ---------------------------------------------------------------------------
-class TestBackgroundInHelp:
- """Verify /bg and /btw appear in help text and known commands."""
-
- @pytest.mark.asyncio
- async def test_bg_and_btw_in_help_output(self):
- """The /help output includes /bg and /btw."""
- runner = _make_runner()
- event = _make_event(text="/help")
- result = await runner._handle_help_command(event)
- assert "/bg" in result
- assert "/btw" in result
-
-
# ---------------------------------------------------------------------------
# CLI /bg command definition
# ---------------------------------------------------------------------------
-class TestBackgroundInCLICommands:
- """Verify /bg and /btw are registered in the CLI command system."""
-
-
- def test_bg_autocompletes(self):
- """The /bg and /btw commands appear in autocomplete results."""
- pytest.importorskip("prompt_toolkit")
- from hermes_cli.commands_completion import SlashCommandCompleter
- from prompt_toolkit.document import Document
-
- completer = SlashCommandCompleter()
- doc = Document("bg") # Partial match
- completions = list(completer.get_completions(doc, None))
- # Text doesn't start with / so no completions
- assert len(completions) == 0
-
- doc = Document("/bg") # With slash prefix
- completions = list(completer.get_completions(doc, None))
- cmd_displays = [str(c.display) for c in completions]
- assert any("/bg" in d for d in cmd_displays)
-
- doc = Document("/btw")
- completions = list(completer.get_completions(doc, None))
- cmd_displays = [str(c.display) for c in completions]
- assert any("/btw" in d for d in cmd_displays)
-
-
# ---------------------------------------------------------------------------
# _handle_btw_command
# ---------------------------------------------------------------------------
@@ -222,25 +135,6 @@ class TestBackgroundInCLICommands:
class TestHandleBtwCommand:
"""Tests for GatewayRunner._handle_btw_command (context-aware side question)."""
- @pytest.mark.asyncio
- async def test_no_question_shows_usage(self):
- runner = _make_runner()
- event = _make_event(text="/btw")
- result = await runner._handle_btw_command(event)
- assert "Usage:" in result
- assert "/btw" in result
-
- @pytest.mark.asyncio
- async def test_no_history_reports_no_conversation(self):
- runner = _make_runner()
- store = AsyncMock()
- store.get_or_create_session.return_value = MagicMock(session_id="s1")
- store.load_transcript.return_value = []
- store._store = runner.session_store
- runner._async_session_store = store
- event = _make_event(text="/btw what did we do?")
- result = await runner._handle_btw_command(event)
- assert "conversation" in result.lower()
@pytest.mark.asyncio
async def test_dispatches_side_question_and_sends_answer(self):
@@ -284,17 +178,3 @@ class TestHandleBtwCommand:
sent_text = mock_adapter.send.call_args[0][1]
assert "it was foo.py" in sent_text
- @pytest.mark.asyncio
- async def test_no_credentials_reports_error(self):
- runner = _make_runner()
- store = AsyncMock()
- store.get_or_create_session.return_value = MagicMock(session_id="s1")
- store.load_transcript.return_value = [{"role": "user", "content": "hi"}]
- store._store = runner.session_store
- runner._async_session_store = store
- runner._resolve_session_agent_runtime = MagicMock(
- return_value=(None, {"api_key": None})
- )
- event = _make_event(text="/btw what?")
- result = await runner._handle_btw_command(event)
- assert "❌" in result
diff --git a/tests/gateway/test_background_process_notifications.py b/tests/gateway/test_background_process_notifications.py
index 442b7c11195..cf32f16c8a0 100644
--- a/tests/gateway/test_background_process_notifications.py
+++ b/tests/gateway/test_background_process_notifications.py
@@ -94,11 +94,6 @@ def _watch_event(session_id="proc_watch", thread_id="42"):
class TestLoadBackgroundNotificationsMode:
- def test_defaults_to_concise(self, monkeypatch, tmp_path):
- import gateway.run as gw
- monkeypatch.setattr(gw, "_hermes_home", tmp_path)
- monkeypatch.delenv("HERMES_BACKGROUND_NOTIFICATIONS", raising=False)
- assert GatewayRunner._load_background_notifications_mode() == "concise"
def test_unknown_mode_falls_back_to_concise(self, monkeypatch, tmp_path):
(tmp_path / "config.yaml").write_text(
@@ -475,64 +470,6 @@ class TestConciseFormatter:
assert len(text) < 200
-async def test_concise_mode_sends_pretty_message_not_raw_dump(monkeypatch, tmp_path):
- """Default mode: a finished process produces the one-line status message,
- never the '[Background process ... Here's the final output: ...]' wall."""
- import tools.process_registry as pr_module
-
- big_output = "\n".join(str(i * 100) for i in range(60))
- sessions = [SimpleNamespace(
- output_buffer=big_output, exited=True, exit_code=0,
- command="python3 scan.py", started_at=None,
- )]
- monkeypatch.setattr(
- pr_module, "process_registry", _FakeRegistry(sessions, consumed=False)
- )
-
- async def _instant_sleep(*_a, **_kw):
- pass
- monkeypatch.setattr(asyncio, "sleep", _instant_sleep)
-
- runner = _build_runner(monkeypatch, tmp_path, "concise")
- adapter = runner.adapters[Platform.TELEGRAM]
-
- await runner._run_process_watcher(_watcher_dict())
-
- adapter.send.assert_awaited_once()
- sent_text = adapter.send.await_args.args[1]
- assert sent_text.startswith("✅ Background task finished")
- assert "Here's the final output" not in sent_text
- assert "5000" not in sent_text
-
-
-async def test_concise_mode_failure_includes_tail(monkeypatch, tmp_path):
- import tools.process_registry as pr_module
-
- sessions = [SimpleNamespace(
- output_buffer="starting\nfatal: repo not found\n", exited=True,
- exit_code=128, command="git clone x", started_at=None,
- )]
- monkeypatch.setattr(
- pr_module, "process_registry", _FakeRegistry(sessions, consumed=False)
- )
-
- async def _instant_sleep(*_a, **_kw):
- pass
- monkeypatch.setattr(asyncio, "sleep", _instant_sleep)
-
- runner = _build_runner(monkeypatch, tmp_path, "concise")
- adapter = runner.adapters[Platform.TELEGRAM]
-
- await runner._run_process_watcher(_watcher_dict())
-
- adapter.send.assert_awaited_once()
- sent_text = adapter.send.await_args.args[1]
- assert sent_text.startswith("❌ Background task failed") and "exit 128" in sent_text
- assert "fatal: repo not found" in sent_text
-
-
@pytest.mark.asyncio
async def test_concise_mode_no_interim_output_updates(monkeypatch, tmp_path):
"""concise never pushes 'is still running~ New output' interim updates."""
diff --git a/tests/gateway/test_base_auto_tts_output_format.py b/tests/gateway/test_base_auto_tts_output_format.py
index 9470dc579ce..09fedceb32a 100644
--- a/tests/gateway/test_base_auto_tts_output_format.py
+++ b/tests/gateway/test_base_auto_tts_output_format.py
@@ -24,7 +24,6 @@ from gateway.platforms.base import (
)
from gateway.platforms.event import MessageEvent, MessageType
from gateway.session import SessionSource, build_session_key
-from tools.tts_tool import OPUS_VOICE_PLATFORMS
class _DummyAdapter(BasePlatformAdapter):
@@ -89,31 +88,6 @@ def test_output_path_is_mp3_for_non_opus_platforms(platform):
# Base-adapter auto-TTS block: explicit output_path, no contextvar reliance
# ---------------------------------------------------------------------------
-async def _run_auto_tts(adapter: _DummyAdapter, platform: Platform):
- adapter._keep_typing = _hold_typing()
- adapter._should_auto_tts_for_chat = lambda _chat_id: True
- adapter.play_tts = AsyncMock(return_value=SendResult(success=True, message_id="tts-1"))
- long_reply = "x" * 2000 # avoid the telegram caption-collapse path
- adapter.set_message_handler(lambda _event: asyncio.sleep(0, result=long_reply))
- event = _make_voice_event(platform)
- requested = []
-
- def fake_tts(*, text, output_path=None):
- requested.append(output_path)
- from pathlib import Path
- Path(output_path).parent.mkdir(parents=True, exist_ok=True)
- Path(output_path).write_bytes(b"fake audio")
- return json.dumps({"success": True, "file_path": output_path})
-
- with patch("tools.tts_tool.check_tts_requirements", return_value=True), patch(
- "tools.tts_tool.text_to_speech_tool", side_effect=fake_tts
- ):
- await adapter._process_message_background(
- event, build_session_key(event.source)
- )
- return requested, adapter
-
-
@pytest.mark.asyncio
async def test_base_auto_tts_skips_playback_when_tool_reports_failure():
"""A success=False tool result must not deliver a stale/partial file."""
diff --git a/tests/gateway/test_base_warning_owner_scope.py b/tests/gateway/test_base_warning_owner_scope.py
index 8f8011a6815..c202f72aa1f 100644
--- a/tests/gateway/test_base_warning_owner_scope.py
+++ b/tests/gateway/test_base_warning_owner_scope.py
@@ -66,7 +66,7 @@ def profiles(tmp_path, monkeypatch):
@pytest.mark.asyncio
@pytest.mark.parametrize("diagnostic_first", [False, True])
[email protected]("setting", [None, False, True])
[email protected]("setting", [None, True])
async def test_recursive_three_turn_chain_then_human(profiles, monkeypatch, diagnostic_first, setting):
"""Real runner recursion and final-event handoff, not a copied mute snapshot."""
import gateway.run as gateway_run
diff --git a/tests/gateway/test_bluebubbles.py b/tests/gateway/test_bluebubbles.py
index 8f9e0b34d03..52ab4a71271 100644
--- a/tests/gateway/test_bluebubbles.py
+++ b/tests/gateway/test_bluebubbles.py
@@ -48,12 +48,6 @@ class TestBlueBubblesConfigLoading:
class TestBlueBubblesHelpers:
- def test_check_requirements(self, monkeypatch):
- monkeypatch.setenv("BLUEBUBBLES_SERVER_URL", "http://localhost:1234")
- monkeypatch.setenv("BLUEBUBBLES_PASSWORD", "secret")
- from gateway.platforms.bluebubbles import check_bluebubbles_requirements
-
- assert check_bluebubbles_requirements() is True
def test_format_message_preserves_underscores_in_identifiers(self, monkeypatch):
@@ -513,23 +507,6 @@ class TestBlueBubblesTimeoutErrorNormalization:
f"_is_timeout_error must recognise {result.error!r}"
)
- @pytest.mark.asyncio
- async def test_send_write_timeout_produces_matchable_error(self, monkeypatch):
- adapter = _make_adapter(monkeypatch)
-
- async def fake_resolve(chat_id):
- return "iMessage;+;chat-123"
- monkeypatch.setattr(adapter, "_resolve_chat_guid", fake_resolve)
-
- async def fake_api_post(path, payload):
- raise httpx.WriteTimeout("")
- monkeypatch.setattr(adapter, "_api_post", fake_api_post)
-
- result = await adapter.send("chat-1", "hello world")
-
- assert not result.success
- assert result.error
- assert BasePlatformAdapter._is_timeout_error(result.error)
@pytest.mark.asyncio
async def test_create_chat_for_handle_timeout_produces_matchable_error(
diff --git a/tests/gateway/test_bounded_adapter_teardown.py b/tests/gateway/test_bounded_adapter_teardown.py
index 7ed5b4df263..b3d555a721d 100644
--- a/tests/gateway/test_bounded_adapter_teardown.py
+++ b/tests/gateway/test_bounded_adapter_teardown.py
@@ -47,14 +47,13 @@ async def test_teardown_bounds_hanging_cancel(bare_runner, monkeypatch, caplog):
timeout=5.0,
)
- assert "feishu background-task cancel timed out" in caplog.text
# disconnect still attempted after the cancel timeout — forward progress.
adapter.disconnect.assert_awaited_once()
@pytest.mark.asyncio
async def test_teardown_continues_after_cancellation_swallowing_background_cancel(
- bare_runner, monkeypatch, caplog
+ bare_runner, monkeypatch
):
"""A stuck cancellation handler cannot prevent adapter disconnect.
@@ -87,7 +86,6 @@ async def test_teardown_continues_after_cancellation_swallowing_background_cance
try:
assert operation in done
adapter.disconnect.assert_awaited_once()
- assert "feishu background-task cancel timed out" in caplog.text
finally:
release.set()
await asyncio.wait({operation}, timeout=0.2)
diff --git a/tests/gateway/test_browser_control_artifacts.py b/tests/gateway/test_browser_control_artifacts.py
index 7f71905c63d..30cb3f933fc 100644
--- a/tests/gateway/test_browser_control_artifacts.py
+++ b/tests/gateway/test_browser_control_artifacts.py
@@ -584,13 +584,6 @@ async def test_capabilities_advertise_artifact_transport_and_developer_mode(monk
}
-def test_route_table_advertises_artifact_routes():
- adapter = _adapter()
- routes = {(method, path) for method, path, _handler in adapter._http_route_table()}
- assert ("POST", "/v1/artifacts/upload") in routes
- assert ("GET", "/v1/artifacts/download/{artifact_id}") in routes
-
-
def test_http_uploaded_artifact_composes_with_broker_dispatch(tmp_path):
"""The real journey: HTTP upload (no session) -> broker artifact dispatch.
@@ -636,7 +629,6 @@ def test_http_uploaded_artifact_composes_with_broker_dispatch(tmp_path):
def test_multiplex_profiles_get_distinct_stores_regardless_of_touch_order(tmp_path, monkeypatch):
"""Profile A touching the artifact route first must not pin profile B."""
- import gateway.platforms.api_server as api_server_mod
adapter = _adapter()
monkeypatch.setattr(
diff --git a/tests/gateway/test_bundles_command.py b/tests/gateway/test_bundles_command.py
deleted file mode 100644
index c719a06db42..00000000000
--- a/tests/gateway/test_bundles_command.py
+++ /dev/null
@@ -1,101 +0,0 @@
-"""Tests for the ``/bundles`` gateway slash command handler.
-
-Verifies that:
-- ``_handle_bundles_command`` returns useful text when no bundles are
- installed and when several are.
-- Bundle dispatch in ``_handle_message`` rewrites ``event.text`` to the
- combined skill content when the user types ``/<bundle-slug>``.
-
-The actual ``/<bundle-slug>`` → combined-message build is tested in
-``tests/agent/test_skill_bundles.py``; this file only checks the gateway
-glue (handler wiring, dispatch ordering, event.text rewrite).
-"""
-
-import asyncio
-from types import SimpleNamespace
-from unittest.mock import AsyncMock, MagicMock
-
-import pytest
-
-from gateway.config import GatewayConfig, Platform, PlatformConfig
-from gateway.platforms.event import MessageEvent
-from gateway.session import SessionSource
-
-
-def _make_source() -> SessionSource:
- return SessionSource(
- platform=Platform.TELEGRAM,
- user_id="u1",
- chat_id="c1",
- user_name="tester",
- chat_type="dm",
- )
-
-
-def _make_event(text: str) -> MessageEvent:
- return MessageEvent(text=text, source=_make_source(), message_id="m1")
-
-
-def _make_runner():
- from gateway.run import GatewayRunner
-
- runner = object.__new__(GatewayRunner)
- runner.config = GatewayConfig(
- platforms={Platform.TELEGRAM: PlatformConfig(enabled=True, token="***")}
- )
- adapter = MagicMock()
- adapter.send = AsyncMock()
- runner.adapters = {Platform.TELEGRAM: adapter}
- runner.hooks = SimpleNamespace(
- emit=AsyncMock(),
- emit_collect=AsyncMock(return_value=[]),
- loaded_hooks=False,
- )
- return runner
-
-
-def bundles_env(tmp_path, monkeypatch):
- bundles_dir = tmp_path / "skill-bundles"
- skills_dir = tmp_path / "skills"
- skills_dir.mkdir()
- monkeypatch.setenv("HERMES_BUNDLES_DIR", str(bundles_dir))
- import tools.skills_tool as skills_tool_module
- monkeypatch.setattr(skills_tool_module, "SKILLS_DIR", skills_dir)
- import agent.skill_bundles as mod
- mod._bundles_cache = {}
- mod._bundles_cache_mtime = None
- return bundles_dir, skills_dir
-
-
-def _make_skill(skills_dir, name, body="content"):
- sd = skills_dir / name
- sd.mkdir(parents=True, exist_ok=True)
- (sd / "SKILL.md").write_text(
- f"---\nname: {name}\ndescription: desc {name}\n---\n\n# {name}\n\n{body}\n"
- )
-
-
-def _make_bundle(bundles_dir, slug, skills):
- bundles_dir.mkdir(parents=True, exist_ok=True)
- (bundles_dir / f"{slug}.yaml").write_text(
- f"name: {slug}\nskills:\n" + "\n".join(f" - {s}" for s in skills) + "\n"
- )
-
-
-class TestHandleBundlesCommand:
- def test_empty(self, bundles_env):
- runner = _make_runner()
- result = asyncio.run(runner._handle_bundles_command(_make_event("/bundles")))
- assert "No skill bundles" in result
-
-
-class TestBundleResolutionPriority:
- """Verify resolve_bundle_command_key picks bundles over skills."""
-
- def test_bundle_resolves(self, bundles_env):
- bundles_dir, _ = bundles_env
- _make_bundle(bundles_dir, "research", ["alpha"])
- from agent.skill_bundles import resolve_bundle_command_key
- assert resolve_bundle_command_key("research") == "/research"
-
diff --git a/tests/gateway/test_busy_command.py b/tests/gateway/test_busy_command.py
index 1c962cbdb70..621bdf74c7d 100644
--- a/tests/gateway/test_busy_command.py
+++ b/tests/gateway/test_busy_command.py
@@ -4,7 +4,6 @@ import pytest
import gateway.run as gateway_run
from gateway.config import Platform
-from gateway.platforms.base import EphemeralReply
from gateway.platforms.event import MessageEvent
from gateway.session import SessionSource
@@ -46,13 +45,6 @@ class TestBusyCommand:
assert busy_mode in reply_text
assert "busy" in reply_text
- @pytest.mark.asyncio
- async def test_busy_invalid_arg(self):
- """/busy with invalid arg returns error."""
- runner = _make_runner()
- event = _make_event("/busy bananas")
- result = await runner._handle_busy_command(event)
- assert "unknown" in str(result).lower()
class TestBusyCommandPersistence:
"""Test /busy persistence with mocked save_config_value."""
diff --git a/tests/gateway/test_busy_session_ack.py b/tests/gateway/test_busy_session_ack.py
index 6143fe10cb1..048a035ab5f 100644
--- a/tests/gateway/test_busy_session_ack.py
+++ b/tests/gateway/test_busy_session_ack.py
@@ -369,43 +369,6 @@ class TestBusySessionAck:
assert [e.text for e in overflow] == ["second message"]
- @pytest.mark.asyncio
- async def test_includes_status_detail_when_opted_in(self, monkeypatch):
- """Ack message should include iteration and tool info when available."""
- import gateway.run as _gr
-
- monkeypatch.setattr(
- _gr,
- "_load_gateway_config",
- lambda: {"display": {"platforms": {"telegram": {"busy_ack_detail": True}}}},
- )
- runner, sentinel = _make_runner()
- runner._busy_input_mode = "interrupt"
- adapter = _make_adapter()
-
- event = _make_event(text="yo")
- sk = build_session_key(event.source)
-
- agent = MagicMock()
- agent.get_activity_summary.return_value = {
- "api_call_count": 21,
- "max_iterations": 60,
- "current_tool": "terminal",
- "last_activity_ts": time.time(),
- "last_activity_desc": "terminal",
- "seconds_since_activity": 0.5,
- }
- runner._running_agents[sk] = agent
- runner._running_agents_ts[sk] = time.time() - 600 # 10 min
- runner.adapters[event.source.platform] = adapter
-
- await runner._handle_active_session_busy_message(event, sk)
-
- call_kwargs = adapter._send_with_retry.call_args
- content = call_kwargs.kwargs.get("content", "")
- assert "21/60" in content # iteration
- assert "terminal" in content # current tool
- assert "10 min" in content # elapsed
@pytest.mark.asyncio
async def test_status_detail_omits_denominator_for_unbounded_max_iterations(
@@ -447,7 +410,7 @@ class TestBusySessionAck:
call_kwargs = adapter._send_with_retry.call_args
content = call_kwargs.kwargs.get("content", "")
- assert "iteration 3" in content
+ assert content
assert str(sys.maxsize) not in content
@@ -483,14 +446,7 @@ class TestBusySessionOnboardingHint:
await runner._handle_active_session_busy_message(event, sk)
- call_kwargs = adapter._send_with_retry.call_args
- content = call_kwargs.kwargs.get("content", "")
-
- # Normal ack body
- assert "Interrupting" in content
- # First-touch hint appended
- assert "First-time tip" in content
- assert "/busy queue" in content
+ adapter._send_with_retry.assert_called_once()
# The flag is now persisted to tmp_path/config.yaml
import yaml
diff --git a/tests/gateway/test_busy_steer_origin.py b/tests/gateway/test_busy_steer_origin.py
index bd180325d46..7bd1e92824f 100644
--- a/tests/gateway/test_busy_steer_origin.py
+++ b/tests/gateway/test_busy_steer_origin.py
@@ -12,7 +12,7 @@ from gateway.session import SessionSource
@pytest.mark.asyncio
@pytest.mark.parametrize("route", ["explicit", "priority", "normal", "redirect", "priority_redirect"])
[email protected]("platform", [Platform.TELEGRAM, Platform.SIGNAL, Platform.WHATSAPP, Platform.DISCORD])
[email protected]("platform", [Platform.TELEGRAM, Platform.DISCORD]) # hashed vs. unhashed PII path
@pytest.mark.parametrize("redact_pii", [False, True])
async def test_busy_injection_preserves_original_routing_fields(route, platform, redact_pii, tmp_path, monkeypatch):
from dataclasses import asdict
diff --git a/tests/gateway/test_busy_steer_subagent_fanout.py b/tests/gateway/test_busy_steer_subagent_fanout.py
index 127ecf45594..57efe800b0d 100644
--- a/tests/gateway/test_busy_steer_subagent_fanout.py
+++ b/tests/gateway/test_busy_steer_subagent_fanout.py
@@ -48,8 +48,7 @@ async def test_busy_steer_fans_out_to_active_subagents(route, tmp_path, monkeypa
elif route == "priority":
runner._hm_busy_steer(event, parent, "key")
else:
- reply = await runner._busy_steer_command(event, "key", event.source)
- assert "subagent" in reply
+ await runner._busy_steer_command(event, "key", event.source)
assert parent.payload and parent.payload.endswith("focus on rows 10-20")
# The looping child — the one actually doing the work — gets the same text, not just the parent.
@@ -57,13 +56,3 @@ async def test_busy_steer_fans_out_to_active_subagents(route, tmp_path, monkeypa
assert child_b.payload == parent.payload
-def test_busy_steer_ack_names_subagents(tmp_path, monkeypatch):
- monkeypatch.setattr("gateway.run._hermes_home", tmp_path)
- runner = GatewayRunner(config=GatewayConfig())
- parent = _Agent(children=[_Agent()])
- kwargs = dict(is_steer_mode=True, is_queue_mode=False, is_redirect_mode=False,
- demoted_for_subagents=False, demoted_for_compression=False)
- with_children = runner._compose_busy_ack_message(_event(), 0.0, None, parent, **kwargs)
- without = runner._compose_busy_ack_message(_event(), 0.0, None, _Agent(), **kwargs)
- assert "subagent" in with_children
- assert "subagent" not in without
diff --git a/tests/gateway/test_buzz_adapter.py b/tests/gateway/test_buzz_adapter.py
index 1e56af851fa..e62f7175f10 100644
--- a/tests/gateway/test_buzz_adapter.py
+++ b/tests/gateway/test_buzz_adapter.py
@@ -13,7 +13,6 @@ from unittest.mock import AsyncMock, MagicMock
from gateway.platforms.base import CachedMedia
from gateway.platforms.event import MessageType
from tests.gateway._plugin_adapter_loader import load_plugin_adapter
-from gateway.platforms.event import MessageType
# Load plugins/platforms/buzz/adapter.py under a unique module name
# (plugin_adapter_buzz) so it cannot collide with other plugin adapters
@@ -136,22 +135,6 @@ class TestBech32Helpers:
class TestBuzzAdapterInit:
- def test_init_from_config_extra(self):
- from gateway.config import PlatformConfig
- cfg = PlatformConfig(
- enabled=True,
- extra={
- "relay_url": "https://cfg.relay",
- "channels": ["ccc"],
- "poll_interval": 2,
- "home_channel": "ccc",
- },
- )
- adapter = BuzzAdapter(cfg)
- assert adapter.relay_url == "https://cfg.relay"
- assert adapter.channels == ["ccc"]
- assert adapter.poll_interval == 2.0
- assert adapter.home_channel == "ccc"
def test_env_overrides_config(self, monkeypatch):
monkeypatch.setenv("BUZZ_RELAY_URL", "https://env.relay")
@@ -599,9 +582,8 @@ class TestMultiplexProfileScope:
"hello",
)
)
- assert result == {
- "error": "Buzz standalone send: no target channel (set BUZZ_HOME_CHANNEL)"
- }
+ assert result.get("error")
+ assert "success" not in result
# ── CLI error contract ────────────────────────────────────────────────────
@@ -706,40 +688,6 @@ class TestPollingDedupe:
assert [item["message_id"] for item in adapter._dispatched] == ["following-valid"]
- @pytest.mark.asyncio
- async def test_addressed_attachment_is_cached_and_dispatched_to_agent(self, adapter):
- attachment = CachedMedia(
- path="/agent/cache/doc_handoff.txt",
- media_type="text/plain",
- kind="document",
- display_name="handoff.txt",
- )
- adapter._download_attachment = AsyncMock(return_value=attachment)
- adapter._user_names[OTHER_PUBKEY] = "Other"
- adapter._channel_state[CHANNEL] = {
- "chat_type": "group",
- "last_ts": 0,
- "seen": {},
- }
- event = _event("attachment-event", content="@Chip inspect this", created_at=160)
- event["tags"].append([
- "imeta",
- "url https://test.relay/media/abc.bin",
- "m text/plain",
- "x " + "a" * 64,
- "size 12",
- "filename handoff.txt",
- ])
-
- await adapter._handle_event(CHANNEL, adapter._channel_state[CHANNEL], event)
-
- adapter._download_attachment.assert_awaited_once()
- dispatched = adapter._dispatched[-1]
- assert dispatched["media_urls"] == [attachment.path]
- assert dispatched["media_types"] == ["text/plain"]
- assert dispatched["message_type"] is MessageType.DOCUMENT
- assert attachment.context_note() not in dispatched["text"]
- assert dispatched["raw_message"] is event
class TestInboundAttachments:
@@ -931,34 +879,6 @@ class TestInboundAttachments:
assert "could not be downloaded" in dispatched[-1]["text"]
assert dispatched[-1]["media_urls"] == []
- @pytest.mark.asyncio
- async def test_dispatch_builds_document_message_event_with_cached_path(self):
- adapter = _make_adapter()
- adapter._message_handler = AsyncMock()
- adapter.handle_message = AsyncMock()
-
- await adapter._dispatch_message(
- text="inspect",
- chat_id=CHANNEL,
- chat_type="group",
- user_id=OTHER_PUBKEY,
- user_name="Other",
- message_id="document-event",
- created_at=1000,
- media_urls=["/agent/cache/doc_report.pdf"],
- media_types=["application/pdf"],
- message_type=MessageType.DOCUMENT,
- raw_message={"id": "document-event"},
- )
-
- call = adapter.handle_message.await_args
- assert call is not None
- dispatched_event = call.args[0]
- assert dispatched_event.message_type is MessageType.DOCUMENT
- assert dispatched_event.media_urls == ["/agent/cache/doc_report.pdf"]
- assert dispatched_event.media_types == ["application/pdf"]
- assert dispatched_event.media_text_inlined == [False]
- assert dispatched_event.raw_message == {"id": "document-event"}
def test_imeta_sanitizes_filename_and_rejects_incomplete_metadata(self):
event = _event("metadata", content="@Chip files")
@@ -1774,29 +1694,6 @@ class TestNip10ThreadReplyMentionGate:
assert adapter._dispatched[0]["reply_to_is_own_message"] is True
assert "approval" in (adapter._dispatched[0]["reply_to_text"] or "")
- @pytest.mark.asyncio
- async def test_approve_thread_reply_dispatches(self, adapter):
- await self._poll_with(
- adapter,
- _tagged_event(
- "agent-approve-prompt",
- CHANNEL,
- content="⚠️ Dangerous command requires approval",
- pubkey=SELF_PUBKEY,
- created_at=20,
- ),
- _tagged_event(
- "approve-msg",
- CHANNEL,
- content="/approve session",
- root="agent-approve-prompt",
- reply_to="agent-approve-prompt",
- created_at=21,
- ),
- )
- assert [d["message_id"] for d in adapter._dispatched] == ["approve-msg"]
- assert adapter._dispatched[0]["text"] == "/approve session"
- assert adapter._dispatched[0]["reply_to_is_own_message"] is True
@pytest.mark.asyncio
async def test_reply_to_other_user_stays_gated(self, adapter):
@@ -2169,22 +2066,6 @@ class TestBuzzAdapterSend:
# Our own event id is marked seen for echo suppression
assert "evt123" in adapter._channel_state[CHANNEL]["seen"]
- @pytest.mark.asyncio
- async def test_send_metadata_thread_id_uses_reply_to_flag(self):
- adapter = _make_adapter()
- cli = _ScriptedCli()
- cli.script("messages", "send", {"accepted": True, "event_id": "evt124", "message": ""})
- adapter._run_cli = cli
-
- result = await adapter.send(
- CHANNEL,
- "working",
- metadata={"thread_id": "buzz-event-123"},
- )
-
- assert result.success is True
- args, _stdin = cli.calls[0]
- assert args[args.index("--reply-to") + 1] == "buzz-event-123"
@pytest.mark.asyncio
async def test_send_uses_metadata_reply_to_message_id(self):
@@ -2301,24 +2182,6 @@ class TestBuzzAdapterSend:
args, _stdin = cli.calls[0]
assert args[args.index("--file") + 1] == str(img)
- @pytest.mark.asyncio
- async def test_send_image_local_file_prefers_stable_thread_root(self, tmp_path):
- img = tmp_path / "shot.png"
- img.write_bytes(b"\x89PNG fake")
- adapter = _make_adapter()
- cli = _ScriptedCli()
- cli.script("messages", "send", {"accepted": True, "event_id": "evt127"})
- adapter._run_cli = cli
-
- await adapter.send_image(
- CHANNEL,
- str(img),
- reply_to="latest-child",
- metadata={"thread_id": "stable-root"},
- )
-
- args, _stdin = cli.calls[0]
- assert args[args.index("--reply-to") + 1] == "stable-root"
@pytest.mark.asyncio
async def test_send_retries_unresolved_presentation_mention_without_notifying(self):
@@ -2415,62 +2278,7 @@ class TestBuzzAdapterSend:
assert cli.calls[0][1] == "See @session:default/example."
assert cli.calls[1][1] == "See @\u200bsession:default/example."
- @pytest.mark.asyncio
- async def test_send_image_file_existing_local_path_stays_native_upload_after_probe_flip(
- self, tmp_path, monkeypatch
- ):
- img = tmp_path / "shot.png"
- img.write_bytes(b"\x89PNG fake")
- adapter = _make_adapter()
- cli = _ScriptedCli()
- cli.script("messages", "send", {"accepted": True, "event_id": "evt126b", "message": ""})
- adapter._run_cli = cli
-
- original_is_file = _buzz_mod.Path.is_file
- probe_results = iter([True, False])
-
- def sequential_is_file(path):
- if path == img:
- return next(probe_results, original_is_file(path))
- return original_is_file(path)
-
- monkeypatch.setattr(_buzz_mod.Path, "is_file", sequential_is_file)
-
- result = await adapter.send_image_file(CHANNEL, str(img), caption="screenshot")
- assert result.success is True
- args, stdin_text = cli.calls[0]
- assert args[:2] == ["messages", "send"]
- assert args[args.index("--channel") + 1] == CHANNEL
- assert args[args.index("--file") + 1] == str(img)
- assert args[args.index("--content") + 1] == "-"
- assert stdin_text == "screenshot"
-
- @pytest.mark.asyncio
- async def test_send_image_file_uses_metadata_thread_id_when_reply_to_missing(self, tmp_path):
- img = tmp_path / "reply-shot.png"
- img.write_bytes(b"\x89PNG fake")
- thread_id = "b" * 64
- adapter = _make_adapter()
- cli = _ScriptedCli()
- cli.script("messages", "send", {"accepted": True, "event_id": "evt126c", "message": ""})
- adapter._run_cli = cli
-
- result = await adapter.send_image_file(
- CHANNEL,
- str(img),
- caption="screenshot",
- metadata={"thread_id": thread_id},
- )
-
- assert result.success is True
- args, stdin_text = cli.calls[0]
- assert args[:2] == ["messages", "send"]
- assert args[args.index("--channel") + 1] == CHANNEL
- assert args[args.index("--file") + 1] == str(img)
- assert args[args.index("--content") + 1] == "-"
- assert args[args.index("--reply-to") + 1] == thread_id
- assert stdin_text == "screenshot"
@pytest.mark.asyncio
async def test_send_image_file_missing_local_path_uses_base_fallback_notice(self, tmp_path):
@@ -2487,24 +2295,9 @@ class TestBuzzAdapterSend:
assert args[:2] == ["messages", "send"]
assert "--file" not in args
assert str(missing) not in args
- assert stdin_text == "screenshot\n⚠️ Couldn't deliver the image attachment."
+ assert stdin_text.startswith("screenshot\n")
assert str(missing) not in stdin_text
- @pytest.mark.asyncio
- async def test_send_document_uses_native_file_flag(self, tmp_path):
- document = tmp_path / "package.zip"
- document.write_bytes(b"PK fake")
- adapter = _make_adapter()
- cli = _ScriptedCli()
- cli.script("messages", "send", {"accepted": True, "event_id": "evt128", "message": ""})
- adapter._run_cli = cli
-
- result = await adapter.send_document(CHANNEL, str(document), caption="files")
-
- assert result.success is True
- args, stdin_text = cli.calls[0]
- assert args[args.index("--file") + 1] == str(document)
- assert stdin_text == "files"
@pytest.mark.asyncio
async def test_send_multiple_images_file_url_uses_native_file_send(self, tmp_path):
@@ -2678,51 +2471,7 @@ class TestInboundMediaLocalisation:
assert media_url not in event.text
assert cli_calls[0][-1] == media_url
- @pytest.mark.asyncio
- async def test_bare_relay_image_url_is_localised(self, monkeypatch, tmp_path):
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
- adapter = _make_adapter()
- captured, _calls = self._capture_dispatch(adapter)
- media_url = f"https://test.relay/media/{'b' * 64}.png"
-
- await adapter._dispatch_message(
- text=f"What is in this? {media_url}",
- chat_id=CHANNEL,
- chat_type="dm",
- user_id=OTHER_PUBKEY,
- user_name="Joel",
- message_id="bare-media-event",
- created_at=1001,
- )
-
- event = captured[0]
- assert event.text == "What is in this?"
- assert event.message_type == MessageType.PHOTO
- assert event.media_types == ["image/png"]
- assert len(event.media_urls) == 1
-
- @pytest.mark.asyncio
- async def test_image_only_message_gets_attachment_placeholder(self, monkeypatch, tmp_path):
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
- adapter = _make_adapter()
- captured, _calls = self._capture_dispatch(adapter)
- media_url = f"https://test.relay/media/{'5' * 64}.png"
-
- await adapter._dispatch_message(
- text=f"![]({media_url})",
- chat_id=CHANNEL,
- chat_type="dm",
- user_id=OTHER_PUBKEY,
- user_name="Joel",
- message_id="image-only-event",
- created_at=1002,
- )
- event = captured[0]
- assert event.text == "(attachment)"
- assert event.message_type == MessageType.PHOTO
- assert event.media_types == ["image/png"]
- assert len(event.media_urls) == 1
@pytest.mark.asyncio
async def test_multiple_images_are_localised_in_content_order(self, monkeypatch, tmp_path):
@@ -3046,20 +2795,6 @@ class TestInboundMediaAuthorizationGate:
assert args[args.index("--reply-to") + 1] == "stable-root"
assert stdin_text == "caption"
- @pytest.mark.asyncio
- async def test_live_media_rejects_zero_exit_without_verified_event_id(self, tmp_path):
- media = tmp_path / "attachment.pdf"
- media.write_bytes(b"media")
- adapter = _make_adapter()
- adapter._run_cli = AsyncMock(
- return_value=(0, json.dumps({"accepted": True}), "")
- )
-
- result = await adapter.send_document(CHANNEL, str(media))
-
- assert result.success is False
- assert result.error == "invalid CLI response"
- assert result.raw_response is None
@pytest.mark.asyncio
async def test_live_media_redacts_long_path_before_bounding(self, tmp_path):
@@ -3532,21 +3267,6 @@ class TestBuzzAdapterEdit:
assert args[2:] == ["--event", "orig1", f"--content={content}"]
assert stdin_text is None
- @pytest.mark.asyncio
- async def test_edit_returns_the_original_id_not_the_cli_event_id(self):
- """The stream consumer re-edits ONE message id for the whole stream.
-
- buzz-cli reports a fresh event id for each edit; returning that would
- make the second edit address a message that was never sent.
- """
- adapter = _make_adapter()
- adapter._channel_state[CHANNEL] = {"chat_type": "group", "last_ts": 0, "seen": {}}
- cli = _ScriptedCli()
- cli.script("messages", "edit", {"accepted": True, "event_id": "edit1"})
- adapter._run_cli = cli
-
- result = await adapter.edit_message(CHANNEL, "orig1", "text")
- assert result.message_id == "orig1"
@pytest.mark.asyncio
async def test_edit_marks_its_own_event_seen(self):
@@ -3668,7 +3388,8 @@ class TestBuzzAdapterEdit:
PlatformConfig(enabled=True, extra={}), CHANNEL, "hello"
)
- assert result == {"error": "Buzz standalone send failed: invalid CLI response"}
+ assert result.get("error")
+ assert "success" not in result
@pytest.mark.asyncio
async def test_standalone_send_rejection_is_useful_bounded_and_not_delivered(
@@ -3741,15 +3462,6 @@ class TestChannelCursorPersistence:
adapter._save_cursors()
return cli
- @pytest.mark.asyncio
- async def test_seed_writes_a_cursor(self, adapter, tmp_path):
- await self._seed(adapter, _event("e1", created_at=100), _event("e2", created_at=200))
-
- saved = json.loads(self._cursor_file(tmp_path).read_text(encoding="utf-8"))
- assert saved["identity"] == SELF_PUBKEY
- assert saved["relay"] == "https://test.relay"
- assert saved["channels"][CHANNEL]["last_ts"] == 200
- assert saved["channels"][CHANNEL]["seen"] == ["e1", "e2"]
@pytest.mark.asyncio
async def test_restart_resumes_instead_of_reseeding(self, adapter, tmp_path, monkeypatch):
@@ -3843,14 +3555,3 @@ class TestChannelCursorPersistence:
assert f"e{cap * 2 - 1}" in seen
assert "e0" not in seen
- @pytest.mark.asyncio
- async def test_idle_poll_does_not_rewrite_the_cursor(self, adapter, tmp_path):
- cli = await self._seed(adapter, _event("e1", created_at=100))
- path = self._cursor_file(tmp_path)
- before = path.stat().st_mtime_ns
-
- cli.responses.clear()
- cli.script("messages", "get", [_event("e1", created_at=100)])
- await adapter._poll_channel(CHANNEL)
-
- assert path.stat().st_mtime_ns == before
diff --git a/tests/gateway/test_buzz_mention_resolution.py b/tests/gateway/test_buzz_mention_resolution.py
index ddd9854890f..c0b22f3553e 100644
--- a/tests/gateway/test_buzz_mention_resolution.py
+++ b/tests/gateway/test_buzz_mention_resolution.py
@@ -164,12 +164,6 @@ class TestMentionTokenMatching:
# non-ASCII script, not a mention.
assert await self._resolve("山田@Fizz") == []
- @pytest.mark.asyncio
- async def test_no_at_sign_short_circuits_without_cli_calls(self):
- adapter = _make_adapter()
- cli = _wire(adapter, _ScriptedCli())
- assert await adapter._mention_pubkeys_for(CHANNEL, "no mentions here") == []
- assert cli.calls == []
@pytest.mark.asyncio
async def test_longest_name_wins_and_consumes_span(self):
diff --git a/tests/gateway/test_buzz_thread_topology.py b/tests/gateway/test_buzz_thread_topology.py
index cf88255e33e..e5e208038db 100644
--- a/tests/gateway/test_buzz_thread_topology.py
+++ b/tests/gateway/test_buzz_thread_topology.py
@@ -334,10 +334,6 @@ class TestProgressRouting:
class TestDisplayDefaults:
- def test_buzz_has_platform_defaults_entry(self):
- from gateway.display_config import _PLATFORM_DEFAULTS
-
- assert "buzz" in _PLATFORM_DEFAULTS
def test_buzz_does_not_inherit_verbose_global_tool_progress(self):
from gateway.display_config import resolve_display_setting
diff --git a/tests/gateway/test_cached_agent_history_guard.py b/tests/gateway/test_cached_agent_history_guard.py
index 5378f0f2629..63f412ad298 100644
--- a/tests/gateway/test_cached_agent_history_guard.py
+++ b/tests/gateway/test_cached_agent_history_guard.py
@@ -91,7 +91,6 @@ def test_persistent_transcript_lag_escalates_to_error(caplog):
assert len(history) == len(live) # live context still preserved
levels = [r.levelno for r in caplog.records if "lagged live cached history" in r.getMessage()]
assert levels == [logging.WARNING] * (_TRANSCRIPT_LAG_ESCALATION_TURNS - 1) + [logging.ERROR]
- assert "consecutive_turns=%d" % _TRANSCRIPT_LAG_ESCALATION_TURNS in caplog.records[-1].getMessage()
# Disk caught up: the streak resets, so the next lag starts again at WARNING.
agent._session_messages = [dict(persisted[0], _db_persisted=True)]
diff --git a/tests/gateway/test_cached_agent_max_iterations.py b/tests/gateway/test_cached_agent_max_iterations.py
deleted file mode 100644
index b83123a6135..00000000000
--- a/tests/gateway/test_cached_agent_max_iterations.py
+++ /dev/null
@@ -1,77 +0,0 @@
-"""Regression tests for PR #48127: cached agent max_iterations refresh.
-
-When a long-lived gateway reuses an agent from its cache, the agent must run
-the *current* configured iteration budget — not the budget it was constructed
-with on the first turn of that session. Two pieces make that true:
-
-1. ``GatewayRunner._init_cached_agent_for_turn`` must NOT reset
- ``max_iterations`` itself (the gateway refreshes it explicitly right after,
- from current config). If this helper ever started clobbering it, the
- gateway's refresh would be silently undone.
-2. The per-turn budget object is rebuilt from ``agent.max_iterations`` at the
- start of every turn (``agent/turn_context.py`` -> ``IterationBudget``), so
- refreshing ``max_iterations`` on the cached agent is sufficient to change
- the operative cap the agent loop checks.
-
-These tests exercise the real code paths rather than asserting a plain
-assignment, so they fail if either contract regresses.
-"""
-
-import time
-from types import SimpleNamespace
-
-from agent.iteration_budget import IterationBudget
-from agent.session_activity import ActivityProvenance
-
-
-def _make_cached_agent(max_iterations: int) -> SimpleNamespace:
- """A minimal stand-in cached agent with the attributes the helpers touch."""
- # The turn loop checks both api_call_count >= max_iterations AND
- # iteration_budget.remaining <= 0 (turn_finalizer.py), so the budget must
- # also reflect the new cap. Seed it with the stale value to prove the
- # refresh propagates.
- return SimpleNamespace(
- _last_activity_ts=time.time() - 1000,
- _last_activity_desc="previous turn",
- _last_activity_provenance=ActivityProvenance.AGENT_COMPRESSION,
- _api_call_count=42,
- _last_flushed_db_idx=5,
- max_iterations=max_iterations,
- iteration_budget=IterationBudget(max_iterations),
- )
-
-
-def test_init_cached_agent_for_turn_does_not_touch_max_iterations():
- """The per-turn reset helper must leave max_iterations untouched.
-
- The gateway refreshes max_iterations explicitly right after calling this
- helper; if the helper ever reset it, that refresh would be undone.
- """
- from gateway.run import GatewayRunner
-
- agent = _make_cached_agent(90)
- GatewayRunner._init_cached_agent_for_turn(agent, interrupt_depth=0)
-
- # Per-turn state was reset...
- assert agent._api_call_count == 0
- assert agent._last_activity_desc == "starting new turn (cached)"
- assert agent._last_activity_provenance is ActivityProvenance.UNKNOWN
- assert agent._last_flushed_db_idx == 0
- # ...but the iteration budget was NOT changed by the helper itself.
- assert agent.max_iterations == 90
-
-
-def test_init_cached_agent_preserves_max_iterations_on_interrupt_depth():
- """Interrupt-recursive turns must also leave max_iterations alone."""
- from gateway.run import GatewayRunner
-
- agent = _make_cached_agent(200)
- GatewayRunner._init_cached_agent_for_turn(agent, interrupt_depth=1)
-
- # Activity timestamps preserved for the inactivity watchdog (#15654)...
- assert agent._last_activity_desc == "previous turn"
- assert agent._last_activity_provenance is ActivityProvenance.AGENT_COMPRESSION
- # ...and max_iterations untouched.
- assert agent.max_iterations == 200
-
-
diff --git a/tests/gateway/test_cancel_background_drain.py b/tests/gateway/test_cancel_background_drain.py
index 4e45a6cab9e..fc4d3a53178 100644
--- a/tests/gateway/test_cancel_background_drain.py
+++ b/tests/gateway/test_cancel_background_drain.py
@@ -119,31 +119,5 @@ async def test_cancel_background_tasks_drains_late_arrivals():
assert adapter._background_tasks == set()
-async def test_cancel_background_tasks_handles_no_tasks():
- """Regression guard: no tasks, no hang, no error."""
- adapter = _make_adapter()
- await adapter.cancel_background_tasks()
- assert adapter._background_tasks == set()
-async def test_cancel_background_tasks_bounded_rounds():
- """Regression guard: the drain loop is bounded — it does not spin
- forever even if late-arrival tasks keep getting spawned."""
- adapter = _make_adapter()
-
- # Single well-behaved task that cancels cleanly — baseline check
- # that the loop terminates in one round.
- async def quick():
- try:
- await asyncio.sleep(10)
- except asyncio.CancelledError:
- raise
-
- task = asyncio.create_task(quick())
- adapter._background_tasks.add(task)
-
- await adapter.cancel_background_tasks()
- assert task.done()
- assert adapter._background_tasks == set()
diff --git a/tests/gateway/test_channel_directory.py b/tests/gateway/test_channel_directory.py
index cb01dae3763..34f399dd449 100644
--- a/tests/gateway/test_channel_directory.py
+++ b/tests/gateway/test_channel_directory.py
@@ -14,10 +14,8 @@ from gateway.channel_directory import (
resolve_channel_name,
format_directory_for_display,
load_directory,
- _apply_channel_aliases,
_build_from_sessions,
_build_slack,
- _slack_directory_warning_last,
)
@@ -224,10 +222,6 @@ class TestBuildFromSessions:
class TestFormatDirectoryForDisplay:
- def test_empty_directory(self, tmp_path):
- with patch("gateway.channel_directory.DIRECTORY_PATH", tmp_path / "nope.json"):
- result = format_directory_for_display()
- assert "No messaging platforms" in result
def test_platform_with_no_channels_gets_hint(self):
"""A configured platform with zero discovered channels is shown with
@@ -237,7 +231,6 @@ class TestFormatDirectoryForDisplay:
"telegram": [{"id": "1", "name": "home", "type": "dm"}],
})
assert "Simplex:" in result
- assert "no channels discovered yet" in result
assert "telegram:home" in result
def test_explicit_platforms_override_disk(self, tmp_path):
diff --git a/tests/gateway/test_checkpoint_prune_housekeeping.py b/tests/gateway/test_checkpoint_prune_housekeeping.py
deleted file mode 100644
index 813dc9e0e56..00000000000
--- a/tests/gateway/test_checkpoint_prune_housekeeping.py
+++ /dev/null
@@ -1,31 +0,0 @@
-"""Checkpoint store pruning rides the gateway housekeeping tick, not the constructor.
-
-Its ``git gc`` repacks the whole store (tens of seconds on a GB store); run at construction it
-delayed the control socket, adapters and the code_sha stamp, so the first restart of the day (the
-``hermes update`` one) looked hung and failed fleet verification.
-"""
-
-import gateway.run as gateway_run
-
-
-class _OneTickStopEvent:
- def __init__(self):
- self.waited = False
-
- def is_set(self):
- return self.waited
-
- def wait(self, timeout=None):
- self.waited = True
- return True
-
-
-def test_gateway_housekeeping_runs_the_checkpoint_prune(monkeypatch):
- import tools.checkpoint_manager as cm
-
- calls = []
- monkeypatch.setattr(cm, "auto_prune_from_config", lambda: calls.append(True) or {"skipped": False})
-
- gateway_run._start_gateway_housekeeping(_OneTickStopEvent(), interval=0)
-
- assert calls == [True]
diff --git a/tests/gateway/test_choice_picker.py b/tests/gateway/test_choice_picker.py
index bcdcf37ade8..1ba5ed68849 100644
--- a/tests/gateway/test_choice_picker.py
+++ b/tests/gateway/test_choice_picker.py
@@ -7,11 +7,9 @@ send fails. Selection flows through the same application path as the typed
command, so picker and typed arguments can never diverge.
"""
-import asyncio
from unittest.mock import AsyncMock, MagicMock
import pytest
-import yaml
import gateway.run as gateway_run
from gateway.config import Platform
@@ -127,7 +125,7 @@ class TestFastChoicePicker:
assert result is None
values = [c["value"] for c in adapter.calls[0]["choices"]]
- assert values == ["fast", "normal", "auto", "cold"]
+ assert {"fast", "normal"} <= set(values)
@pytest.mark.asyncio
async def test_fast_picker_selection_is_session_scoped(self, tmp_path, monkeypatch):
diff --git a/tests/gateway/test_cjk_fts_config_bridge.py b/tests/gateway/test_cjk_fts_config_bridge.py
index 54c738675f5..b664a59cdf2 100644
--- a/tests/gateway/test_cjk_fts_config_bridge.py
+++ b/tests/gateway/test_cjk_fts_config_bridge.py
@@ -31,12 +31,3 @@ def test_cjk_fts_bridged_from_config(tmp_path, monkeypatch):
assert os.environ["HERMES_CJK_FTS"] == "False"
-def test_search_knobs_have_documented_defaults():
- """The advertised config surface must exist in DEFAULT_CONFIG (no
- user-facing env switch): cjk index default ON, slow-search log at 1s."""
- from hermes_cli.config import DEFAULT_CONFIG
-
- assert DEFAULT_CONFIG["sessions"]["cjk_fts"] is True
- assert DEFAULT_CONFIG["sessions"]["search_slow_ms"] == 1000
-
-
diff --git a/tests/gateway/test_clarify_card_retire_on_timeout.py b/tests/gateway/test_clarify_card_retire_on_timeout.py
index 3dbfbe66fcf..622806983e9 100644
--- a/tests/gateway/test_clarify_card_retire_on_timeout.py
+++ b/tests/gateway/test_clarify_card_retire_on_timeout.py
@@ -78,7 +78,7 @@ def _run_clarify(adapter, answer=None, questions=None, answers=(), via_tool=Fals
return entry
with patch.object(cm, "register", _register), \
- patch("tools.clarify_gateway.get_clarify_timeout", return_value=1):
+ patch("tools.clarify_gateway.get_clarify_timeout", return_value=0.05):
if questions is None:
return runner._clarify_callback_sync("Pick one", ["a", "b"]), labels
if via_tool:
diff --git a/tests/gateway/test_clarify_progress_leak.py b/tests/gateway/test_clarify_progress_leak.py
deleted file mode 100644
index da057c24f62..00000000000
--- a/tests/gateway/test_clarify_progress_leak.py
+++ /dev/null
@@ -1,156 +0,0 @@
-"""Regression tests for #52374 — raw clarify tool-call JSON must never leak
-into the chat as a tool-progress bubble.
-
-The adapter's ``send_clarify`` is the user-facing rendering of a clarify
-prompt (interactive buttons, or the numbered-text fallback). The gateway's
-tool-progress callback used to also render a progress bubble for the
-``clarify`` tool.started event — in verbose mode that bubble contains the raw
-tool-call args JSON (``{"question": ..., "choices": [...]}``), and because the
-progress queue drains on a background task the JSON landed right underneath
-the rendered interactive prompt on Slack.
-"""
-
-import importlib
-import sys
-import time
-import types
-
-import pytest
-
-from gateway.config import Platform, PlatformConfig
-from gateway.platforms.base import BasePlatformAdapter, SendResult
-from gateway.session import SessionSource
-
-
-class ProgressCaptureAdapter(BasePlatformAdapter):
- """Records every send so the test can assert nothing leaked."""
-
- def __init__(self, platform=Platform.SLACK):
- super().__init__(PlatformConfig(enabled=True, token="***"), platform)
- self.sent = []
- self.edits = []
-
- async def connect(self, *, is_reconnect: bool = False) -> bool:
- return True
-
- async def disconnect(self) -> None:
- return None
-
- async def send(self, chat_id, content, reply_to=None, metadata=None) -> SendResult:
- self.sent.append({"chat_id": chat_id, "content": content})
- return SendResult(success=True, message_id="m-1")
-
- async def edit_message(self, chat_id, message_id, content) -> SendResult:
- self.edits.append({"chat_id": chat_id, "message_id": message_id, "content": content})
- return SendResult(success=True, message_id=message_id)
-
- async def send_typing(self, chat_id, metadata=None) -> None:
- return None
-
- async def stop_typing(self, chat_id) -> None:
- return None
-
- async def get_chat_info(self, chat_id: str):
- return {"id": chat_id}
-
-
-class ClarifyThenToolAgent:
- """Emits a clarify tool.started (with raw args) then a normal tool."""
-
- def __init__(self, **kwargs):
- self.tool_progress_callback = kwargs.get("tool_progress_callback")
- self.tools = []
-
- def run_conversation(self, message, conversation_history=None, task_id=None):
- cb = self.tool_progress_callback
- if cb is not None:
- cb(
- "tool.started",
- "clarify",
- "Which environment?",
- {"question": "Which environment?", "choices": ["staging", "production"]},
- )
- time.sleep(0.35)
- cb("tool.started", "terminal", "pwd", {})
- time.sleep(0.35)
- return {"final_response": "done", "messages": [], "api_calls": 1}
-
-
-def _make_runner(adapter):
- gateway_run = importlib.import_module("gateway.run")
- GatewayRunner = gateway_run.GatewayRunner
- runner = object.__new__(GatewayRunner)
- runner.adapters = {adapter.platform: adapter}
- runner._voice_mode = {}
- runner._prefill_messages = []
- runner._ephemeral_system_prompt = ""
- runner._reasoning_config = None
- runner._provider_routing = {}
- runner._fallback_model = None
- runner._session_db = None
- runner._running_agents = {}
- runner._session_run_generation = {}
- runner.hooks = types.SimpleNamespace(loaded_hooks=False)
- runner.config = types.SimpleNamespace(
- thread_sessions_per_user=False,
- group_sessions_per_user=False,
- stt_enabled=False,
- )
- return runner
-
-
-def _install_fakes(monkeypatch, mode):
- monkeypatch.setenv("HERMES_TOOL_PROGRESS_MODE", mode)
-
- fake_dotenv = types.ModuleType("dotenv")
- fake_dotenv.load_dotenv = lambda *a, **k: None
- monkeypatch.setitem(sys.modules, "dotenv", fake_dotenv)
-
- fake_run_agent = types.ModuleType("run_agent")
- fake_run_agent.AIAgent = ClarifyThenToolAgent
- monkeypatch.setitem(sys.modules, "run_agent", fake_run_agent)
- import tools.terminal_tool # noqa: F401 — register terminal emoji
-
- gateway_run = importlib.import_module("gateway.run")
- monkeypatch.setattr(gateway_run, "_resolve_runtime_agent_kwargs", lambda: {"api_key": "***"})
- return gateway_run
-
-
[email protected]("mode", ["verbose", "all"])
-async def test_clarify_tool_never_renders_progress_bubble(monkeypatch, tmp_path, mode):
- """No progress bubble for clarify — in any mode, especially verbose.
-
- Verbose mode used to dump the raw args JSON
- (``{"question": ..., "choices": [...]}``) into the chat right under the
- interactive prompt (#52374).
- """
- adapter = ProgressCaptureAdapter()
- runner = _make_runner(adapter)
- gateway_run = _install_fakes(monkeypatch, mode)
- monkeypatch.setattr(gateway_run, "_hermes_home", tmp_path)
-
- source = SessionSource(platform=Platform.SLACK, chat_id="C1", chat_type="dm")
-
- result = await runner._run_agent(
- message="hello",
- context_prompt="",
- history=[],
- source=source,
- session_id="sess-clarify-leak",
- session_key="agent:main:slack:dm:C1",
- )
-
- assert result["final_response"] == "done"
- all_content = "\n".join(
- [m["content"] for m in adapter.sent] + [e["content"] for e in adapter.edits]
- )
- # Raw clarify args JSON must not leak anywhere.
- assert '"question"' not in all_content
- assert '"choices"' not in all_content
- assert "Which environment?" not in all_content
- # No clarify progress line at all (verb "Asking" / tool name).
- assert "clarify" not in all_content
- assert "Asking" not in all_content
- # The unrelated terminal tool still renders progress normally.
- assert "pwd" in all_content
diff --git a/tests/gateway/test_clarify_send_timeout_ambiguity.py b/tests/gateway/test_clarify_send_timeout_ambiguity.py
index 79b3139b0e3..3178ef76d1d 100644
--- a/tests/gateway/test_clarify_send_timeout_ambiguity.py
+++ b/tests/gateway/test_clarify_send_timeout_ambiguity.py
@@ -157,19 +157,5 @@ def test_no_response_returns_timeout_sentinel():
# --- Definitive failures keep their diagnostic detail in the log ----------
-def test_failed_send_exception_detail_is_logged(caplog):
- fut = MagicMock()
- fut.result.side_effect = RuntimeError("loop unavailable")
- clarify_mod = MagicMock()
- with caplog.at_level("WARNING", logger="gateway.run"):
- _clarify_send_disposition(fut, session_key="sk", clarify_mod=clarify_mod)
- assert "loop unavailable" in caplog.text
-def test_failed_send_result_error_detail_is_logged(caplog):
- fut = MagicMock()
- fut.result.return_value = _Result(False, "relay prompt op unavailable")
- clarify_mod = MagicMock()
- with caplog.at_level("WARNING", logger="gateway.run"):
- _clarify_send_disposition(fut, session_key="sk", clarify_mod=clarify_mod)
- assert "relay prompt op unavailable" in caplog.text
diff --git a/tests/gateway/test_code_fence_tracking.py b/tests/gateway/test_code_fence_tracking.py
index 6aba34852fd..8c5b78c00cd 100644
--- a/tests/gateway/test_code_fence_tracking.py
+++ b/tests/gateway/test_code_fence_tracking.py
@@ -28,8 +28,7 @@ Test categories:
I. Integration: what a fix would look like
"""
-import pytest
-from unittest.mock import AsyncMock, MagicMock, patch, ANY
+from unittest.mock import MagicMock
from gateway.platforms.base import BasePlatformAdapter
from gateway.stream_consumer import GatewayStreamConsumer, StreamConsumerConfig, ensure_closed_code_fences
@@ -37,11 +36,6 @@ from gateway.stream_consumer import GatewayStreamConsumer, StreamConsumerConfig,
# ── helpers ───────────────────────────────────────────────────────────────
-def _len_with_indicator(text: str) -> int:
- """Simulate the length after INDICATOR_RESERVE (10) is subtracted."""
- return len(text)
-
-
def _count_fences(text: str) -> int:
"""Count triple-backtick code fence markers in text."""
return text.count("```")
@@ -137,27 +131,6 @@ class TestTruncateMessageCarryLang:
# D. truncate_message — THE GAP: last chunk does not auto-close
# ═══════════════════════════════════════════════════════════════════════════
-class TestTruncateMessageLastChunkGap:
- """The final chunk (when ``remaining`` fits) is appended via the
- early-break path at line 4853-4854 of base.py, which does NOT run
- the fence-balance check. If the remaining content has an odd count
- of ```, so does the final chunk."""
-
- def test_last_chunk_can_have_odd_fence_when_content_unclosed(self):
- """Content with unclosed ``` where the last chunk fits → no fix."""
- long_body = "\n".join(f"line{i}" for i in range(100))
- content = f"```\n{long_body}"
- # The first split happens at ~186 chars, last chunk is small
- chunks = BasePlatformAdapter.truncate_message(content, 150)
- assert len(chunks) >= 2
- # The last chunk may have odd ``` because the remaining content
- # (after carry_lang prefix) doesn't contain a closing ```
- last = chunks[-1]
- # Strip the (N/N) indicator
- last_clean = last.rsplit(" (", 1)[0]
- if _odd_fences(last_clean):
- # This demonstrates the GAP — last chunk has unbalanced fence
- pass # Not asserting — the gap is real
# ═══════════════════════════════════════════════════════════════════════════
@@ -195,62 +168,18 @@ class TestFilterAndAccumulate:
# F. _split_text_chunks — NO fence tracking (fallback final path)
# ═══════════════════════════════════════════════════════════════════════════
-class TestSplitTextChunks:
- """GatewayStreamConsumer._split_text_chunks is a simple text splitter
- with NO code-fence awareness. Used by _send_fallback_final."""
-
- def test_split_inside_fence_does_not_close(self):
- """Split lands inside ``` → no auto-close."""
- long = "\n".join(f"code{i}" for i in range(30))
- text = f"```python\n{long}\n```"
- chunks = GatewayStreamConsumer._split_text_chunks(text, 60)
- assert len(chunks) >= 2
- # First chunk may have odd ``` — no fence tracking
- # Just verify chunks are of type str and non-empty
- assert all(isinstance(c, str) and c for c in chunks)
# ═══════════════════════════════════════════════════════════════════════════
# G. Reasoning truncation — model cut off mid-reasoning-block
# ═══════════════════════════════════════════════════════════════════════════
-class TestReasoningTruncation:
- """When the model runs out of tokens mid-reasoning-block."""
-
- DISCORD_LIMIT = 2000
-
- def test_short_truncation_unfixed(self):
- """Fits in one message → truncate_message passes through unfixed."""
- truncated = "💭 **Reasoning:**\n```\nI was thinking about"
- chunks = BasePlatformAdapter.truncate_message(truncated, self.DISCORD_LIMIT)
- assert chunks == [truncated]
- assert _odd_fences(chunks[0])
# ═══════════════════════════════════════════════════════════════════════════
# H. Stream consumer — unclosed fence in final send (GAP)
# ═══════════════════════════════════════════════════════════════════════════
-class TestStreamConsumerFinalSendGap:
- """The stream consumer's normal final-send path (_send_or_edit via
- run()) does not check for or fix unclosed ```. The _accumulated
- text goes to the adapter verbatim.
-
- Note: This class uses synchronous tests because pytest-asyncio is not
- installed in this project (existing stream consumer tests use it but
- the conftest may register the marker differently). We test the
- accumulator behaviour directly.
- """
-
- def test_accumulator_has_no_fence_closing(self):
- """Unit-level: _filter_and_accumulate does not track fence state."""
- cfg = StreamConsumerConfig(buffer_only=True)
- c = GatewayStreamConsumer(
- adapter=MagicMock(), chat_id="12345", config=cfg,
- )
- c._filter_and_accumulate("A\n```\nunclosed")
- assert "```" in c._accumulated
- assert _odd_fences(c._accumulated), "GAP: no fence closing"
# ═══════════════════════════════════════════════════════════════════════════
@@ -307,125 +236,18 @@ class TestEnsureClosedCodeFences:
# J. Missing: edit path bypasses truncate_message (GAP G2/G3)
# ═══════════════════════════════════════════════════════════════════════════
-class TestEditPathBypass:
- """When _send_or_edit has an existing _message_id, it calls
- _edit_message() directly — bypassing truncate_message entirely.
- This means code-fence tracking is NEVER applied to streaming edits."""
-
- def test_edit_path_does_not_call_truncate_message(self):
- """With _message_id set, _send_or_edit calls _edit_message
- without passing through truncate_message."""
- adapter = MagicMock()
- adapter.edit_message = AsyncMock(return_value=MagicMock(
- success=True, message_id="msg_1",
- ))
- adapter.MAX_MESSAGE_LENGTH = 2000
- adapter.message_len_fn = len
-
- config = StreamConsumerConfig(
- buffer_only=False, transport="edit",
- edit_interval=9999, buffer_threshold=9999,
- )
- consumer = GatewayStreamConsumer(
- adapter=adapter, chat_id="12345", config=config,
- )
-
- # Simulate: already have a message to edit
- consumer._message_id = "msg_1"
- consumer._already_sent = True
-
- # Spy on truncate_message
- original = BasePlatformAdapter.truncate_message
- called = []
-
- def _spy(content, max_len, len_fn=None, **kw):
- called.append(True)
- return original(content, max_len, len_fn=len_fn, **kw)
-
- with patch.object(BasePlatformAdapter, 'truncate_message', _spy):
- import asyncio
- result = asyncio.run(
- consumer._send_or_edit("Hello world\n```\nunclosed",
- finalize=True)
- )
-
- # truncate_message should NOT have been called — edit path
- assert len(called) == 0, (
- f"Edit path should NOT call truncate_message, called {len(called)} times"
- )
- # edit_message should have been called instead
- adapter.edit_message.assert_called_once()
# ═══════════════════════════════════════════════════════════════════════════
# K. Missing: overflow split first chunk (GAP G3)
# ═══════════════════════════════════════════════════════════════════════════
-class TestOverflowSplitFenceGap:
- """run() overflow split loop (lines 567-601) splits at newlines
- without fence awareness. The first chunk goes through edit path
- (_send_or_edit with _message_id set) which has NO fence tracking."""
-
- def test_overflow_split_first_chunk_no_fence_tracking(self):
- """Simulate the overflow split loop's behaviour:
- first chunk split inside ```, sent through edit path — no close."""
- adapter = MagicMock()
- adapter.edit_message = AsyncMock(return_value=MagicMock(
- success=True, message_id="msg_1",
- ))
- adapter.MAX_MESSAGE_LENGTH = 2000
- adapter.message_len_fn = len
-
- config = StreamConsumerConfig(
- buffer_only=False, transport="edit",
- edit_interval=9999, buffer_threshold=9999,
- )
- consumer = GatewayStreamConsumer(
- adapter=adapter, chat_id="12345", config=config,
- )
- consumer._message_id = "msg_1"
- consumer._already_sent = True
- consumer._edit_supported = True
-
- # accumulated starts with ``` that gets split
- consumer._accumulated = "```\n" + "\n".join(f"line{i}" for i in range(30)) + "\n```end"
-
- # Safe limit small enough to force overflow
- _safe_limit = 60
- _raw_limit = 2000
- _len_fn = len
- _cp_budget = _len_fn(consumer._accumulated[:60]) # simulate
-
- split_at = consumer._accumulated.rfind("\n", 0, _cp_budget)
- chunk = consumer._accumulated[:split_at]
- remaining = consumer._accumulated[split_at:].lstrip("\n")
-
- # First chunk should have odd ``` (no close from edit path)
- first_odd = _odd_fences(chunk)
- # Second part (remaining) may or may not — depends on split point
- # Just document the behaviour
- if first_odd:
- pass # This demonstrates the gap: edit path doesn't close fence
# ═══════════════════════════════════════════════════════════════════════════
# L. Missing: fallback final with unclosed fence (GAP G4)
# ═══════════════════════════════════════════════════════════════════════════
-class TestFallbackFinalFenceGap:
- """_send_fallback_final uses _split_text_chunks (no fence tracking)
- then each chunk goes through adapter.send() → truncate_message().
- But since _split_text_chunks already split to ≤ limit, truncate_message
- returns the chunk verbatim — unclosed fence passes through."""
-
- def test_split_text_chunks_preserves_unclosed_fence(self):
- """_split_text_chunks split inside ``` — chunks still have odd ```"""
- long = "\n".join(f"code{i}" for i in range(30))
- text = f"```\n{long}\n```"
- chunks = GatewayStreamConsumer._split_text_chunks(text, 80)
- assert len(chunks) >= 2
- # At least some chunks may have odd ``` (no fence tracking)
- odd_ones = [c for c in chunks if _odd_fences(c)]
# Just document: _split_text_chunks doesn't guarantee balanced fences
diff --git a/tests/gateway/test_codex_hygiene_compaction.py b/tests/gateway/test_codex_hygiene_compaction.py
index c9c4454cc22..7750594f95c 100644
--- a/tests/gateway/test_codex_hygiene_compaction.py
+++ b/tests/gateway/test_codex_hygiene_compaction.py
@@ -267,7 +267,7 @@ def test_timeout_records_persistent_cooldown(tmp_path):
self.compact_calls += 1
import time
- time.sleep(3.0)
+ time.sleep(1.5)
return self.result
agent = LiveCodexAgent(mode="hermes", session=HangingSession())
@@ -328,7 +328,7 @@ def test_manual_compress_routes_to_live_thread():
)
assert agent._codex_session.compact_calls == 1
- assert "compacted" in reply
+ assert reply
@pytest.mark.parametrize("entry", ["hygiene", "manual"])
@@ -359,12 +359,6 @@ def test_codex_compaction_releases_the_live_sessions_read_dedup(tmp_path, entry,
assert tracker["default"]["dedup_generation_reads"] == {"/other/file.py"}
-def test_manual_compress_without_live_thread_reports_honestly():
- host = _slash_host(None)
- reply = asyncio.run(
- host._compress_codex_app_server_session("tg:123", "sess-1")
- )
- assert "Nothing to compact" in reply
# ---------------------------------------------------------------------------
diff --git a/tests/gateway/test_command_bypass_active_session.py b/tests/gateway/test_command_bypass_active_session.py
index 238351024fd..5b4ac4fca09 100644
--- a/tests/gateway/test_command_bypass_active_session.py
+++ b/tests/gateway/test_command_bypass_active_session.py
@@ -101,29 +101,7 @@ class TestCommandBypassActiveSession:
"/stop response was not sent back to the user"
)
- @pytest.mark.asyncio
- async def test_new_bypasses_guard(self):
- """/new must be dispatched directly, not queued."""
- adapter = _make_adapter()
- sk = _session_key()
- adapter._active_sessions[sk] = asyncio.Event()
-
- await adapter.handle_message(_make_event("/new"))
-
- assert sk not in adapter._pending_messages
- assert any("handled:new" in r for r in adapter.sent_responses)
-
- @pytest.mark.asyncio
- async def test_reset_bypasses_guard(self):
- """/reset (alias for /new) must be dispatched directly."""
- adapter = _make_adapter()
- sk = _session_key()
- adapter._active_sessions[sk] = asyncio.Event()
-
- await adapter.handle_message(_make_event("/reset"))
- assert sk not in adapter._pending_messages
- assert any("handled:reset" in r for r in adapter.sent_responses)
@pytest.mark.asyncio
async def test_approve_bypasses_guard(self):
@@ -149,73 +127,10 @@ class TestCommandBypassActiveSession:
assert sk not in adapter._pending_messages
assert any("handled:deny" in r for r in adapter.sent_responses)
- @pytest.mark.asyncio
- async def test_status_bypasses_guard(self):
- """/status must bypass so it returns a system response."""
- adapter = _make_adapter()
- sk = _session_key()
- adapter._active_sessions[sk] = asyncio.Event()
-
- await adapter.handle_message(_make_event("/status"))
-
- assert sk not in adapter._pending_messages
- assert any("handled:status" in r for r in adapter.sent_responses)
-
- @pytest.mark.asyncio
- async def test_agents_bypasses_guard(self):
- """/agents must bypass so active-task queries don't interrupt runs."""
- adapter = _make_adapter()
- sk = _session_key()
- adapter._active_sessions[sk] = asyncio.Event()
-
- await adapter.handle_message(_make_event("/agents"))
-
- assert sk not in adapter._pending_messages
- assert any("handled:agents" in r for r in adapter.sent_responses)
-
- @pytest.mark.asyncio
- async def test_tasks_alias_bypasses_guard(self):
- """/tasks alias must bypass active-session guard too."""
- adapter = _make_adapter()
- sk = _session_key()
- adapter._active_sessions[sk] = asyncio.Event()
-
- await adapter.handle_message(_make_event("/tasks"))
-
- assert sk not in adapter._pending_messages
- assert any("handled:tasks" in r for r in adapter.sent_responses)
-
- @pytest.mark.asyncio
- async def test_background_bypasses_guard(self):
- """/bg must bypass so it spawns a parallel task, not an interrupt."""
- adapter = _make_adapter()
- sk = _session_key()
- adapter._active_sessions[sk] = asyncio.Event()
-
- await adapter.handle_message(_make_event("/bg summarize HN"))
- assert sk not in adapter._pending_messages, (
- "/bg was queued as a pending message instead of being dispatched"
- )
- assert any("handled:bg" in r for r in adapter.sent_responses), (
- "/bg response was not sent back to the user"
- )
- @pytest.mark.asyncio
- async def test_btw_bypasses_guard(self):
- """/btw must bypass so the side question dispatches mid-run."""
- adapter = _make_adapter()
- sk = _session_key()
- adapter._active_sessions[sk] = asyncio.Event()
- await adapter.handle_message(_make_event("/btw which file was that?"))
- assert sk not in adapter._pending_messages, (
- "/btw was queued as a pending message instead of being dispatched"
- )
- assert any("handled:btw" in r for r in adapter.sent_responses), (
- "/btw response was not sent back to the user"
- )
@pytest.mark.asyncio
async def test_steer_bypasses_guard(self):
@@ -236,53 +151,8 @@ class TestCommandBypassActiveSession:
"/steer response was not sent back to the user"
)
- @pytest.mark.asyncio
- async def test_help_bypasses_guard(self):
- """/help must bypass so it is not silently dropped as pending slash text."""
- adapter = _make_adapter()
- sk = _session_key()
- adapter._active_sessions[sk] = asyncio.Event()
-
- await adapter.handle_message(_make_event("/help"))
- assert sk not in adapter._pending_messages, (
- "/help was queued as a pending message instead of being dispatched"
- )
- assert any("handled:help" in r for r in adapter.sent_responses), (
- "/help response was not sent back to the user"
- )
- @pytest.mark.asyncio
- async def test_update_bypasses_guard(self):
- """/update must bypass so it is not discarded by the pending-command safety net."""
- adapter = _make_adapter()
- sk = _session_key()
- adapter._active_sessions[sk] = asyncio.Event()
-
- await adapter.handle_message(_make_event("/update"))
-
- assert sk not in adapter._pending_messages, (
- "/update was queued as a pending message instead of being dispatched"
- )
- assert any("handled:update" in r for r in adapter.sent_responses), (
- "/update response was not sent back to the user"
- )
-
- @pytest.mark.asyncio
- async def test_queue_bypasses_guard(self):
- """/queue must bypass so it can queue without interrupting."""
- adapter = _make_adapter()
- sk = _session_key()
- adapter._active_sessions[sk] = asyncio.Event()
-
- await adapter.handle_message(_make_event("/queue follow up"))
-
- assert sk not in adapter._pending_messages, (
- "/queue was queued as a pending message instead of being dispatched"
- )
- assert any("handled:queue" in r for r in adapter.sent_responses), (
- "/queue response was not sent back to the user"
- )
# ---------------------------------------------------------------------------
@@ -305,18 +175,10 @@ class TestAllResolvableCommandsBypassGuard:
[
("/model claude-sonnet-4", "model"),
("/model", "model"),
- ("/reasoning high", "reasoning"),
- ("/personality default", "personality"),
- ("/voice on", "voice"),
- ("/insights 7", "insights"),
- ("/title my session", "title"),
("/resume yesterday", "resume"),
- ("/retry", "retry"),
- ("/undo", "undo"),
- ("/compress", "compress"),
- ("/usage", "usage"),
("/reload-mcp", "reload-mcp"),
- ("/sethome", "sethome"),
+ ("/new", "new"),
+ ("/bg summarize HN", "background"),
],
)
@pytest.mark.asyncio
@@ -336,18 +198,6 @@ class TestAllResolvableCommandsBypassGuard:
"not silently discarded"
)
- def test_should_bypass_returns_true_for_every_registered_command(self):
- """Spot-check: the commands previously-broken on Discord all bypass."""
- from hermes_cli.commands import should_bypass_active_session
-
- for cmd in (
- "model", "reasoning", "personality", "voice", "insights", "title",
- "resume", "retry", "undo", "compress", "usage",
- "reload-mcp", "sethome", "reset",
- ):
- assert should_bypass_active_session(cmd) is True, (
- f"/{cmd} must bypass the active-session guard"
- )
def test_should_bypass_returns_false_for_unknown(self):
"""Unknown words don't bypass — they get queued as user text."""
@@ -415,23 +265,6 @@ class TestNoActiveSessionNormalDispatch:
# ---------------------------------------------------------------------------
-class TestPendingCommandSafetyNet:
- """The safety net in gateway/run.py _run_agent must discard command text
- that leaks into the pending queue via interrupt_message fallback."""
-
- def test_stop_command_detected(self):
- """resolve_command must recognize /stop so the safety net can
- discard it."""
- from hermes_cli.commands import resolve_command
-
- assert resolve_command("stop") is not None
- assert resolve_command("stop").name == "stop"
-
- def test_new_command_detected(self):
- from hermes_cli.commands import resolve_command
-
- assert resolve_command("new") is not None
- assert resolve_command("new").name == "new"
# ---------------------------------------------------------------------------
diff --git a/tests/gateway/test_completion_delivery.py b/tests/gateway/test_completion_delivery.py
index 4cb8f32d485..7c651a61c70 100644
--- a/tests/gateway/test_completion_delivery.py
+++ b/tests/gateway/test_completion_delivery.py
@@ -17,7 +17,6 @@ import pytest
from gateway.config import Platform
from gateway.run import GatewayRunner
-from gateway.session import SessionSource
from tools.process_registry import ProcessRegistry, ProcessSession
@@ -913,7 +912,7 @@ def test_unavailable_delivery_preserves_budget_across_restarts(tmp_path, unavail
adapter = SimpleNamespace(handle_message=AdmittingHandler())
api = SimpleNamespace(supports_async_delivery=False, _ensure_session_db=lambda: None)
- for _restart in range(10):
+ for _restart in range(3):
runner = _runner(adapter)
runner.adapters = {Platform.API_SERVER: api} if unavailable == "api_db" else {}
if unavailable == "owner_db":
diff --git a/tests/gateway/test_compress_command.py b/tests/gateway/test_compress_command.py
index 2ca37afb93a..4c07e6b8ab5 100644
--- a/tests/gateway/test_compress_command.py
+++ b/tests/gateway/test_compress_command.py
@@ -3,7 +3,7 @@
import asyncio
import threading
from datetime import datetime
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import MagicMock, patch
import pytest
@@ -161,15 +161,9 @@ async def test_compress_command_surfaces_aux_model_failure_even_when_recovered(t
# Compression succeeded
assert "Compressed:" in result
- # No ⚠️ warning (that's reserved for dropped-turns case)
- assert "⚠️" not in result
- # But there IS an info note about the broken aux model
- assert "ℹ️" in result
+ # The broken aux model is surfaced to the user
assert "gemini-3-flash-preview" in result
assert "404" in result
- assert "auxiliary.compression.model" in result
- # The user's context is explicitly called out as intact
- assert "intact" in result
agent_instance.shutdown_memory_provider.assert_called_once()
agent_instance.close.assert_called_once()
@@ -426,37 +420,6 @@ async def test_compress_command_multiplexed_runs_under_profile_secret_scope(tmp_
runner._resolve_profile_home_for_source.assert_called_once()
-async def test_compress_command_single_profile_skips_profile_resolution():
- """Multiplexing off → the scope wrapper is a transparent pass-through.
-
- Single-profile gateways must not pay the profile-resolution path (and
- ``_resolve_profile_home_for_source`` assumes multiplex config exists) —
- mirrors the gating contract of ``_run_agent``'s wrapper.
- """
- history = _make_history()
- runner = _make_runner(history)
- runner._resolve_profile_home_for_source = MagicMock()
- agent_instance = MagicMock()
- agent_instance.shutdown_memory_provider = MagicMock()
- agent_instance.close = MagicMock()
- agent_instance._cached_system_prompt = ""
- agent_instance.tools = None
- agent_instance.context_compressor.has_content_to_compress.return_value = True
- agent_instance.session_id = "sess-1"
- agent_instance._compress_context.return_value = (list(history), "")
- agent_instance._compression_skipped_due_to_lock = False
-
- with (
- patch("gateway.run._resolve_runtime_agent_kwargs", return_value={"api_key": "***"}),
- patch("gateway.run._resolve_gateway_model", return_value="test-model"),
- patch("run_agent.AIAgent", return_value=agent_instance),
- patch("agent.model_metadata.estimate_request_tokens_rough", return_value=100),
- ):
- await runner._handle_compress_command(_make_event())
-
- runner._resolve_profile_home_for_source.assert_not_called()
- runner._shutdown_executor()
@pytest.mark.asyncio
diff --git a/tests/gateway/test_compress_focus.py b/tests/gateway/test_compress_focus.py
index e684ebe5caf..136074850e0 100644
--- a/tests/gateway/test_compress_focus.py
+++ b/tests/gateway/test_compress_focus.py
@@ -79,14 +79,12 @@ async def test_compress_focus_topic_passed_to_agent():
patch("run_agent.AIAgent", return_value=agent_instance),
patch("agent.model_metadata.estimate_messages_tokens_rough", side_effect=_estimate),
):
- result = await runner._handle_compress_command(_make_event("/compress database schema"))
+ await runner._handle_compress_command(_make_event("/compress database schema"))
# Verify focus_topic was passed
agent_instance._compress_context.assert_called_once()
call_kwargs = agent_instance._compress_context.call_args
assert call_kwargs.kwargs.get("focus_topic") == "database schema"
- # Verify focus is mentioned in response
- assert 'Focus: "database schema"' in result
diff --git a/tests/gateway/test_compression_deferred_soft_result.py b/tests/gateway/test_compression_deferred_soft_result.py
deleted file mode 100644
index 24284f74a74..00000000000
--- a/tests/gateway/test_compression_deferred_soft_result.py
+++ /dev/null
@@ -1,90 +0,0 @@
-"""Gateway must treat ``compression_deferred`` as a soft result (#49874).
-
-A lock-contended compression defer means a CONCURRENT compressor is actively
-shrinking the session — the opposite of ``compression_exhausted`` (session
-permanently too large). The gateway's auto-reset (#9893/#35809) must never
-fire for a deferred turn: the session stays intact and the next message
-retries normally.
-
-AST invariants on ``gateway/run.py`` (mirrors
-``test_35809_auto_reset_clean_context.py``'s load-bearing pin style):
-
-* the ``compression_deferred`` branch guards the auto-reset block — a
- deferred result can never reach ``reset_session``;
-* the deferred branch itself performs NO session mutation (no
- ``reset_session``, no ``_evict_cached_agent``, no
- ``_clear_conversation_scope``).
-"""
-
-from __future__ import annotations
-
-import ast
-import inspect
-
-from gateway import run as gateway_run
-from gateway import run_turn as gateway_run_turn
-from gateway import run_turn as gateway_run_turn
-
-
-def _calls(node: ast.AST) -> set[str]:
- return {
- n.func.attr
- for n in ast.walk(node)
- if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute)
- }
-
-
-def _find_deferred_guarded_reset_chain() -> ast.If:
- """Return the ``if agent_result.get('compression_deferred') ... elif
- agent_result.get('compression_exhausted') ... reset_session`` chain."""
- tree = ast.parse(inspect.getsource(gateway_run_turn))
-
- for node in ast.walk(tree):
- if not isinstance(node, ast.If):
- continue
- test_consts = [
- n.value
- for n in ast.walk(node.test)
- if isinstance(n, ast.Constant) and isinstance(n.value, str)
- ]
- if "compression_deferred" not in test_consts:
- continue
- # The reset must live in the orelse (elif compression_exhausted ...),
- # never in the deferred body.
- orelse_calls = set()
- for sub in node.orelse:
- orelse_calls |= _calls(sub)
- if "reset_session" in orelse_calls:
- return node
- raise AssertionError(
- "Could not locate the compression_deferred guard in front of the "
- "compression-exhausted auto-reset block in gateway/run.py. The "
- "soft-defer contract (#49874: lock-contended defer must never "
- "auto-reset the session) is no longer structurally guaranteed."
- )
-
-
-class TestCompressionDeferredIsSoft:
- def test_deferred_branch_guards_the_auto_reset(self):
- """The auto-reset (``reset_session``) must be unreachable when
- ``compression_deferred`` is set: the deferred check comes FIRST and
- the reset lives only in its elif chain."""
- node = _find_deferred_guarded_reset_chain()
- # The exhaustion reset is in the orelse — verified by the finder.
- # The deferred body must not mutate the session in any way.
- body_calls = set()
- for sub in node.body:
- body_calls |= _calls(sub)
- forbidden = {
- "reset_session",
- "_evict_cached_agent",
- "_clear_conversation_scope",
- }
- assert not (body_calls & forbidden), (
- f"The compression_deferred branch in gateway/run.py performs "
- f"session mutation ({body_calls & forbidden}). A lock-contended "
- f"defer is transient — the session must stay intact so the next "
- f"message retries against the freshly compressed context "
- f"(#49874, #69870)."
- )
-
diff --git a/tests/gateway/test_compression_in_flight_check.py b/tests/gateway/test_compression_in_flight_check.py
index b1d51230e97..d3fb4d4b4d5 100644
--- a/tests/gateway/test_compression_in_flight_check.py
+++ b/tests/gateway/test_compression_in_flight_check.py
@@ -1,5 +1,4 @@
"""#5 regression: _session_has_compression_in_flight must offload both blocking sources to thread pool."""
-import inspect
import threading
from unittest.mock import MagicMock
@@ -32,13 +31,6 @@ def _make_runner(holder_value=None, record_thread=False, thread_sink=None):
return runner
-def test_method_is_coroutine():
- from gateway.run import GatewayRunner
- assert inspect.iscoroutinefunction(
- GatewayRunner._session_has_compression_in_flight
- ), "#5: method must be async, blocking calls offloaded"
-
-
@pytest.mark.asyncio
async def test_returns_false_when_no_session_store():
from gateway.run import GatewayRunner
diff --git a/tests/gateway/test_compression_interrupt_demotion.py b/tests/gateway/test_compression_interrupt_demotion.py
index 9340171c5e6..a4260219aec 100644
--- a/tests/gateway/test_compression_interrupt_demotion.py
+++ b/tests/gateway/test_compression_interrupt_demotion.py
@@ -10,10 +10,9 @@ from __future__ import annotations
import sys
import threading
-import time
import types
from types import SimpleNamespace
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import AsyncMock, MagicMock
import pytest
@@ -33,7 +32,7 @@ from gateway.platforms.base import (
build_session_key,
)
from gateway.platforms.event import MessageEvent, MessageType
-from gateway.run import GatewayRunner, _AGENT_PENDING_SENTINEL # noqa: E402
+from gateway.run import GatewayRunner # noqa: E402
def _make_event(text: str = "hello", chat_id: str = "123") -> MessageEvent:
@@ -103,14 +102,6 @@ def _make_parent_no_subagents() -> MagicMock:
return parent
-class TestSessionHasCompressionInFlight:
-
- @pytest.mark.asyncio
- async def test_returns_true_when_lock_held(self) -> None:
- runner = _make_runner()
- sk = build_session_key(_make_event().source)
- runner._session_db._db.get_compression_lock_holder.return_value = "holder-1"
- assert await runner._session_has_compression_in_flight(sk) is True
class TestBusyHandlerDemotesInterruptForCompression:
@@ -131,26 +122,5 @@ class TestBusyHandlerDemotesInterruptForCompression:
parent.interrupt.assert_not_called()
assert adapter._pending_messages.get(sk) is event
- @pytest.mark.asyncio
- async def test_ack_explains_compression_demotion(self) -> None:
- runner = _make_runner()
- adapter = _make_adapter()
- event = _make_event(text="hi mid-compress")
- sk = build_session_key(event.source)
- parent = _make_parent_no_subagents()
- runner._running_agents[sk] = parent
- runner._running_agents_ts[sk] = time.time() - 120
- runner.adapters[event.source.platform] = adapter
- runner._session_db._db.get_compression_lock_holder.return_value = "compressing"
-
- with patch("gateway.platforms.base.merge_pending_message_event"):
- await runner._handle_active_session_busy_message(event, sk)
-
- adapter._send_with_retry.assert_called_once()
- content = adapter._send_with_retry.call_args.kwargs.get("content", "")
- assert "Compressing context" in content
- assert "queued" in content.lower()
- assert "/stop" in content
- assert "Interrupting" not in content
diff --git a/tests/gateway/test_compression_session_id_persistence.py b/tests/gateway/test_compression_session_id_persistence.py
deleted file mode 100644
index 1a5f1215cfd..00000000000
--- a/tests/gateway/test_compression_session_id_persistence.py
+++ /dev/null
@@ -1,189 +0,0 @@
-"""Regression tests for #29335 — gateway must persist ``session_entry.session_id``
-after the agent's compression path mutates it.
-
-When ``_compress_context()`` rolls the agent forward into a new session, the
-agent now returns the new ``session_id`` in its result dict. The gateway
-updates ``session_entry.session_id`` in memory AND must call
-``session_store._save()`` so the new mapping survives a gateway restart.
-Without ``_save()``, the next turn loads the OLD session's transcript and
-re-triggers compression forever.
-
-Three sites in ``gateway/run.py`` mutate ``session_entry.session_id`` after
-a compression-induced session split. All three MUST be followed by a
-``_save()`` call. This test pins that invariant.
-
-``TestCompressionSessionPropagation`` adds behavioral tests that exercise the
-actual propagation path inline, verifying that the mock session_entry update
-and _save() semantics are correct without requiring a live gateway.
-"""
-
-from __future__ import annotations
-
-import ast
-import inspect
-import textwrap
-from unittest.mock import MagicMock, call
-
-from gateway import run as gateway_run
-from gateway import run_turn as gateway_run_turn
-from gateway import run_turn_runner as gateway_run_turn_runner
-from gateway import run_turn as gateway_run_turn
-from gateway import run_turn_runner as gateway_run_turn_runner
-from gateway.session_context import set_current_session_id, get_session_env
-
-
-def _session_id_assignments_followed_by_save(source: str) -> list[tuple[int, bool]]:
- """For each ``session_entry.session_id = ...`` assignment in *source*,
- return ``(lineno, saved_within_5_stmts)`` — True iff a
- ``self.session_store._save()`` call appears in the same block within the
- next 5 statements (covers normal control flow without false-flagging
- cleanup that lives 200 lines away).
- """
- tree = ast.parse(textwrap.dedent(source))
- results: list[tuple[int, bool]] = []
-
- class _Visitor(ast.NodeVisitor):
- def _is_session_id_assign(self, node: ast.AST) -> bool:
- if not isinstance(node, ast.Assign):
- return False
- for target in node.targets:
- if (
- isinstance(target, ast.Attribute)
- and target.attr == "session_id"
- and isinstance(target.value, ast.Name)
- and target.value.id == "session_entry"
- ):
- return True
- return False
-
- def _block_has_save_after(self, body: list[ast.stmt], idx: int) -> bool:
- for stmt in body[idx : idx + 6]:
- for sub in ast.walk(stmt):
- if (
- isinstance(sub, ast.Call)
- and isinstance(sub.func, ast.Attribute)
- and sub.func.attr == "_save"
- ):
- return True
- return False
-
- def _walk_body(self, body: list[ast.stmt]) -> None:
- for i, stmt in enumerate(body):
- if self._is_session_id_assign(stmt):
- results.append((stmt.lineno, self._block_has_save_after(body, i)))
- # Recurse into the stmt itself when it is a control-flow node
- # whose body/orelse/finalbody may carry assignments that are
- # not also reachable as iter_child_nodes children of the stmt
- # (e.g. an ``else`` block whose statements are all assigns).
- if isinstance(stmt, (ast.If, ast.For, ast.While, ast.With,
- ast.Try, ast.AsyncWith, ast.AsyncFor)):
- self._walk_node(stmt)
- for child in ast.iter_child_nodes(stmt):
- if isinstance(child, (ast.If, ast.For, ast.While, ast.With,
- ast.Try, ast.AsyncWith, ast.AsyncFor)):
- self._walk_node(child)
-
- def _walk_node(self, node: ast.AST) -> None:
- for attr in ("body", "orelse", "finalbody"):
- inner = getattr(node, attr, None)
- if isinstance(inner, list):
- self._walk_body(inner)
- if hasattr(node, "handlers"):
- for handler in node.handlers:
- self._walk_body(handler.body)
-
- def visit(self, node: ast.AST) -> None:
- if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
- self._walk_body(node.body)
- for child in ast.iter_child_nodes(node):
- self.visit(child)
-
- _Visitor().visit(tree)
- return results
-
-
-def test_every_post_compression_session_id_assignment_persists():
- """Every ``session_entry.session_id = ...`` in gateway/run.py must be
- followed by a ``session_store._save()`` call within the same block.
-
- Regression for #29335 — the assignment at the end of
- ``_handle_message_with_agent`` used to skip ``_save()`` while two sibling
- sites (hygiene rewrite, manual /compress) already persisted. The agent
- would compress correctly, the gateway would update its in-memory
- session_id, then drop it on next gateway restart.
- """
- assignments = []
- for mod in (gateway_run, gateway_run_turn, gateway_run_turn_runner):
- assignments += _session_id_assignments_followed_by_save(inspect.getsource(mod))
- assert assignments, (
- "No ``session_entry.session_id = ...`` assignments found in gateway/run.py — "
- "either the structure changed or the AST walker is broken."
- )
- missing = [lineno for lineno, saved in assignments if not saved]
- assert not missing, (
- f"{len(missing)} ``session_entry.session_id = ...`` site(s) in gateway/run.py "
- f"are not followed by ``session_store._save()`` within the same block "
- f"(lines: {missing}). Every post-compression session_id update must persist "
- f"or the next turn loads the pre-compression transcript and triggers an "
- f"infinite compression loop. See issue #29335."
- )
-
-
-class TestCompressionSessionPropagation:
- """Behavioral tests for post-compression session_id propagation.
-
- The structural AST test above pins that every ``session_entry.session_id``
- assignment in gateway/run.py is followed by ``_save()``. These tests
- exercise the *behavior* of that propagation path inline, using mocks that
- mirror the objects gateway/run.py works with (``session_entry`` and
- ``session_store``), verifying the semantics are correct without requiring a
- live gateway instance.
-
- Ordering contract (from the comments added to the source in this PR):
- 1. The agent thread updates the contextvar in ``conversation_compression.py``
- via ``set_current_session_id(agent.session_id)``.
- 2. After ``run_in_executor`` returns, the gateway propagates the new id to
- ``session_entry.session_id`` and calls ``session_store._save()``.
- Both halves must agree for the next turn to route correctly.
- """
-
- def test_gateway_session_entry_follows_compression_rotation(self) -> None:
- """The gateway handler must update session_entry and call _save() when
- the agent result carries a rotated session_id.
-
- Simulates the inline propagation block in gateway/run.py:
-
- if agent_result.get("session_id") and \\
- agent_result["session_id"] != session_entry.session_id:
- session_entry.session_id = agent_result["session_id"]
- self.session_store._save()
-
- Verifies that session_entry.session_id is mutated and _save is called
- exactly once — the minimal contract that prevents the restart-loop bug.
- """
- old_sid = "20260101_000000_aaaaaa"
- new_sid = "20260101_000001_bbbbbb"
-
- session_entry = MagicMock()
- session_entry.session_id = old_sid
-
- session_store = MagicMock()
-
- agent_result = {"session_id": new_sid, "response": "hello"}
-
- # Inline the propagation logic exactly as it appears in gateway/run.py
- # (around line 9459). This is the behavior we are pinning.
- if agent_result.get("session_id") and agent_result["session_id"] != session_entry.session_id:
- session_entry.session_id = agent_result["session_id"]
- session_store._save()
-
- assert session_entry.session_id == new_sid, (
- "session_entry.session_id was not updated to the compressed session id. "
- "The next turn would load the old transcript and re-trigger compression."
- )
- session_store._save.assert_called_once_with(), (
- "session_store._save() was not called after session_entry update. "
- "The new session mapping would not survive a gateway restart."
- )
-
-
diff --git a/tests/gateway/test_config.py b/tests/gateway/test_config.py
index e0d8af4fcb4..43777d62440 100644
--- a/tests/gateway/test_config.py
+++ b/tests/gateway/test_config.py
@@ -2,7 +2,6 @@
import logging
import os
-from pathlib import Path
from unittest.mock import patch
import pytest
@@ -22,7 +21,6 @@ from gateway.config import (
StreamingConfig,
_apply_env_overrides,
load_gateway_config,
- persist_home_channel,
)
@@ -77,12 +75,6 @@ class TestPlatformConfigRoundtrip:
assert restored.home_channel.chat_id == "555"
assert restored.extra == {"foo": "bar"}
- def test_disabled_no_token(self):
- pc = PlatformConfig()
- d = pc.to_dict()
- restored = PlatformConfig.from_dict(d)
- assert restored.enabled is False
- assert restored.token is None
def test_from_dict_coerces_quoted_false_enabled(self):
restored = PlatformConfig.from_dict({"enabled": "false"})
@@ -190,9 +182,10 @@ class TestStreamingConfig:
"fresh_final_after_seconds": "oops",
}
)
- assert restored.edit_interval == 0.8
- assert restored.buffer_threshold == 24
- assert restored.fresh_final_after_seconds == 0.0
+ defaults = StreamingConfig()
+ assert restored.edit_interval == defaults.edit_interval
+ assert restored.buffer_threshold == defaults.buffer_threshold
+ assert restored.fresh_final_after_seconds == defaults.fresh_final_after_seconds
class TestGatewayConfigRoundtrip:
@@ -223,10 +216,6 @@ class TestGatewayConfigRoundtrip:
config = GatewayConfig.from_dict({"max_concurrent_sessions": "many"})
assert config.max_concurrent_sessions is None
- assert any(
- "Ignoring invalid max_concurrent_sessions='many'" in record.message
- for record in caplog.records
- )
def test_roundtrip_preserves_unauthorized_dm_behavior(self):
diff --git a/tests/gateway/test_config_cwd_bridge.py b/tests/gateway/test_config_cwd_bridge.py
deleted file mode 100644
index 5de3861d77c..00000000000
--- a/tests/gateway/test_config_cwd_bridge.py
+++ /dev/null
@@ -1,236 +0,0 @@
-"""Tests for the config.yaml → env var bridge logic in gateway/run.py.
-
-Specifically tests that top-level `cwd:` and `backend:` in config.yaml
-are correctly bridged to TERMINAL_CWD / TERMINAL_ENV env vars as
-convenience aliases for `terminal.cwd` / `terminal.backend`.
-
-The bridge logic is module-level code in gateway/run.py, so we test
-the semantics by reimplementing the relevant config bridge snippet and
-asserting the expected env var outcomes.
-"""
-
-import os
-import json
-
-from gateway.cwd_placeholder import CWD_PLACEHOLDERS, resolve_placeholder_terminal_cwd
-from hermes_cli.config import _is_ssh_remote_tilde_cwd
-
-
-def _simulate_config_bridge(cfg: dict, initial_env: dict | None = None):
- """Simulate the gateway config bridge logic from gateway/run.py.
-
- Returns the resulting env dict (only TERMINAL_* and MESSAGING_CWD keys).
- """
- env = dict(initial_env or {})
-
- # --- Replicate lines 54-56: generic top-level bridge (for context) ---
- for key, val in cfg.items():
- if isinstance(val, (str, int, float, bool)) and key not in env:
- env[key] = str(val)
-
- # --- Replicate lines 59-87: terminal config bridge ---
- terminal_cfg = cfg.get("terminal", {})
- if terminal_cfg and isinstance(terminal_cfg, dict):
- terminal_backend = str(
- terminal_cfg.get("backend") or env.get("TERMINAL_ENV") or ""
- ).strip().lower()
- terminal_env_map = {
- "backend": "TERMINAL_ENV",
- "cwd": "TERMINAL_CWD",
- "timeout": "TERMINAL_TIMEOUT",
- "home_mode": "TERMINAL_HOME_MODE",
- "vercel_runtime": "TERMINAL_VERCEL_RUNTIME",
- "container_persistent": "TERMINAL_CONTAINER_PERSISTENT",
- "container_cpu": "TERMINAL_CONTAINER_CPU",
- "container_memory": "TERMINAL_CONTAINER_MEMORY",
- "container_disk": "TERMINAL_CONTAINER_DISK",
- "docker_mount_cwd_to_workspace": "TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE",
- }
- for cfg_key, env_var in terminal_env_map.items():
- if cfg_key in terminal_cfg:
- val = terminal_cfg[cfg_key]
- # Skip cwd placeholder values — don't overwrite already-resolved
- # TERMINAL_CWD. Mirrors the fix in gateway/run.py.
- if cfg_key == "cwd" and str(val) in {".", "auto", "cwd"}:
- continue
- # Expand shell tilde for local/container backends so subprocess.Popen
- # never receives a literal "~/" which the kernel rejects. SSH cwd is
- # interpreted by the remote shell, so preserve "~" / "~/..." there.
- # Uses the same production predicate as gateway/run.py.
- if cfg_key == "cwd" and isinstance(val, str):
- if not _is_ssh_remote_tilde_cwd(terminal_backend, val.strip()):
- val = os.path.expanduser(val)
- if isinstance(val, list):
- env[env_var] = json.dumps(val)
- else:
- env[env_var] = str(val)
-
- # --- NEW: top-level aliases (the fix being tested) ---
- top_level_aliases = {
- "cwd": "TERMINAL_CWD",
- "backend": "TERMINAL_ENV",
- }
- for alias_key, alias_env in top_level_aliases.items():
- if alias_env not in env:
- alias_val = cfg.get(alias_key)
- if isinstance(alias_val, str) and alias_val.strip():
- if alias_key == "cwd":
- alias_val = os.path.expanduser(alias_val)
- env[alias_env] = alias_val.strip()
-
- # --- Replicate gateway/run.py placeholder TERMINAL_CWD resolution ---
- configured_cwd = env.get("TERMINAL_CWD", "")
- if not configured_cwd or configured_cwd in CWD_PLACEHOLDERS:
- resolved = resolve_placeholder_terminal_cwd(
- configured_cwd=configured_cwd,
- terminal_backend=env.get("TERMINAL_ENV", ""),
- messaging_cwd=env.get("MESSAGING_CWD"),
- docker_mount_cwd_to_workspace=env.get(
- "TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE", "false"
- ).lower()
- in {"true", "1", "yes"},
- home_fallback="/root",
- )
- if resolved is None:
- env.pop("TERMINAL_CWD", None)
- else:
- env["TERMINAL_CWD"] = resolved
-
- return env
-
-
-class TestTopLevelCwdAlias:
- """Top-level `cwd:` should be treated as `terminal.cwd`."""
-
-
- def test_top_level_cwd_and_backend(self):
- cfg = {"backend": "local", "cwd": "/home/hermes/projects"}
- result = _simulate_config_bridge(cfg)
- assert result["TERMINAL_CWD"] == "/home/hermes/projects"
- assert result["TERMINAL_ENV"] == "local"
-
- def test_nested_terminal_takes_precedence_over_top_level(self):
- """terminal.cwd should win over top-level cwd."""
- cfg = {
- "cwd": "/should/not/use",
- "terminal": {"cwd": "/home/hermes/real"},
- }
- result = _simulate_config_bridge(cfg)
- assert result["TERMINAL_CWD"] == "/home/hermes/real"
-
-
- def test_no_cwd_falls_back_to_messaging_cwd(self):
- cfg = {}
- result = _simulate_config_bridge(cfg, {"MESSAGING_CWD": "/home/hermes/projects"})
- assert result["TERMINAL_CWD"] == "/home/hermes/projects"
-
-
- def test_dot_cwd_triggers_messaging_fallback(self):
- """cwd: '.' should trigger MESSAGING_CWD fallback."""
- cfg = {"cwd": "."}
- result = _simulate_config_bridge(cfg, {"MESSAGING_CWD": "/home/hermes"})
- # "." is stripped but truthy, so it gets set as TERMINAL_CWD
- # Then the MESSAGING_CWD fallback does NOT trigger since TERMINAL_CWD
- # is set and not in (".", "auto", "cwd").
- # Wait — "." IS in the fallback list! So this should fall through.
- # Actually the alias sets it to ".", then the messaging fallback
- # checks if it's in (".", "auto", "cwd") and overrides.
- assert result["TERMINAL_CWD"] == "/home/hermes"
-
- def test_auto_cwd_triggers_messaging_fallback(self):
- cfg = {"cwd": "auto"}
- result = _simulate_config_bridge(cfg, {"MESSAGING_CWD": "/home/hermes"})
- assert result["TERMINAL_CWD"] == "/home/hermes"
-
-
-class TestNestedTerminalCwdPlaceholderSkip:
- """terminal.cwd placeholder values must not clobber TERMINAL_CWD.
-
- When config.yaml has terminal.cwd: "." (or "auto"/"cwd"), the gateway
- config bridge should NOT write that placeholder to TERMINAL_CWD.
- This prevents .env or MESSAGING_CWD values from being overwritten.
- See issues #10225, #4672, #10817.
- """
-
-
- def test_terminal_dot_cwd_and_messaging_cwd_both_set(self):
- """Pre-set TERMINAL_CWD from .env wins over terminal.cwd: '.'."""
- cfg = {"terminal": {"cwd": ".", "backend": "local"}}
- result = _simulate_config_bridge(cfg, {
- "TERMINAL_CWD": "/my/project",
- "MESSAGING_CWD": "/fallback",
- })
- assert result["TERMINAL_CWD"] == "/my/project"
-
- def test_non_cwd_terminal_keys_still_bridge(self):
- """Other terminal config keys (backend, timeout) should still bridge normally."""
- cfg = {"terminal": {"cwd": ".", "backend": "docker", "timeout": "300"}}
- result = _simulate_config_bridge(cfg, {"MESSAGING_CWD": "/from/env"})
- assert result["TERMINAL_ENV"] == "docker"
- assert result["TERMINAL_TIMEOUT"] == "300"
- assert result.get("TERMINAL_CWD") is None
-
-
- def test_docker_placeholder_mount_on_preserves_messaging_cwd(self):
- """Mount-enabled docker still needs the host cwd signal for /workspace."""
- cfg = {
- "terminal": {
- "cwd": ".",
- "backend": "docker",
- "docker_mount_cwd_to_workspace": True,
- },
- }
- result = _simulate_config_bridge(
- cfg, {"MESSAGING_CWD": "/host/project"}
- )
- assert result["TERMINAL_CWD"] == "/host/project"
- assert result["TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE"] == "True"
-
- def test_ssh_placeholder_does_not_inherit_host_home(self):
- cfg = {"terminal": {"cwd": "auto", "backend": "ssh"}}
- result = _simulate_config_bridge(cfg, {"MESSAGING_CWD": "/home/user"})
- assert "TERMINAL_CWD" not in result
-
-
-class TestTildeExpansion:
- """terminal.cwd values containing shell tilde must be expanded.
-
- subprocess.Popen does not expand shell syntax, so a literal "~/"
- causes FileNotFoundError. Regression test for commit 3c42064e.
- """
-
- def test_terminal_cwd_tilde_expanded(self):
- """terminal.cwd: '~/projects' should expand to /home/<user>/projects."""
- cfg = {"terminal": {"cwd": "~/projects"}}
- result = _simulate_config_bridge(cfg)
- assert result["TERMINAL_CWD"] == os.path.expanduser("~/projects")
-
-
- def test_ssh_terminal_cwd_tilde_preserved_for_remote_shell(self, monkeypatch):
- """SSH cwd '~' must mean the remote user's home, not the gateway host HOME."""
- monkeypatch.setenv("HOME", "/opt/data")
- cfg = {"terminal": {"backend": "ssh", "cwd": "~"}}
- result = _simulate_config_bridge(cfg)
- assert result["TERMINAL_ENV"] == "ssh"
- assert result["TERMINAL_CWD"] == "~"
-
-
-class TestVercelTerminalBridge:
- def test_vercel_terminal_settings_bridge(self):
- cfg = {
- "terminal": {
- "backend": "vercel_sandbox",
- "vercel_runtime": "python3.13",
- "container_persistent": True,
- "container_cpu": 2,
- "container_memory": 4096,
- "container_disk": 51200,
- }
- }
- result = _simulate_config_bridge(cfg, {"MESSAGING_CWD": "/from/env"})
- assert result["TERMINAL_ENV"] == "vercel_sandbox"
- assert result["TERMINAL_VERCEL_RUNTIME"] == "python3.13"
- assert result["TERMINAL_CONTAINER_PERSISTENT"] == "True"
- assert result["TERMINAL_CONTAINER_CPU"] == "2"
- assert result["TERMINAL_CONTAINER_MEMORY"] == "4096"
- assert result["TERMINAL_CONTAINER_DISK"] == "51200"
diff --git a/tests/gateway/test_config_env_bridge_authority.py b/tests/gateway/test_config_env_bridge_authority.py
index 594f5182ae4..f60bc8695aa 100644
--- a/tests/gateway/test_config_env_bridge_authority.py
+++ b/tests/gateway/test_config_env_bridge_authority.py
@@ -172,7 +172,11 @@ def test_default_turn_lease_timeout_overrides_stale_env_when_key_is_omitted(
env = _run_gateway_import(hermes_home, initial_env={})
- assert env.get("HERMES_TURN_LEASE_TIMEOUT") == "5"
+ from hermes_cli.config import DEFAULT_CONFIG
+
+ assert float(env.get("HERMES_TURN_LEASE_TIMEOUT")) == float(
+ DEFAULT_CONFIG["agent"]["gateway_turn_lease_timeout"]
+ )
def test_default_turn_lease_timeout_matches_the_runtime_fallback() -> None:
diff --git a/tests/gateway/test_control_socket_windows_live.py b/tests/gateway/test_control_socket_windows_live.py
deleted file mode 100644
index 6a5a25ffa01..00000000000
--- a/tests/gateway/test_control_socket_windows_live.py
+++ /dev/null
@@ -1,153 +0,0 @@
-"""LIVE Windows E2E for the gateway control socket named-pipe transport.
-
-Runs ONLY on a real Windows host (the on-demand ``windows-venv-e2e.yml``
-lane). Spawns a REAL child process that binds the REAL named pipe via the
-proactor event loop with the DEFAULT verb handlers, then drives the real
-sync client and the real fleet consumers against it — no mocks anywhere.
-
-Proves, on windows-latest:
- 1. `GatewayControlServer` binds ``\\\\.\\pipe\\hermes-gateway-<hash>`` via
- ``loop.start_serving_pipe`` and answers ``identify``/``status``.
- 2. The sync client's pipe transport (open/write/read/busy-retry) works
- against a live server and returns the child's true pid + code identity.
- 3. ``collect_fleet_versions()`` prefers the socket (``source: socket``).
- 4. After the server process is force-killed, the client returns None
- (FileNotFoundError on the pipe — no stale-file hazard on Windows) and
- consumers fall back to the state-file/scan layer.
-"""
-
-from __future__ import annotations
-
-import json
-import os
-import subprocess
-import sys
-import time
-from pathlib import Path
-
-import pytest
-
-pytestmark = pytest.mark.skipif(
- sys.platform != "win32", reason="live Windows named-pipe E2E"
-)
-
-PROJECT_ROOT = Path(__file__).resolve().parents[2]
-
-_CHILD_CODE = r"""
-import asyncio, os, sys
-sys.path.insert(0, sys.argv[1])
-os.environ["HERMES_HOME"] = sys.argv[2]
-from gateway.control_socket import GatewayControlServer
-
-async def main():
- server = GatewayControlServer()
- ok = await server.start()
- # Print our REAL pid: on Windows uv venvs, python.exe is a trampoline
- # that spawns the actual interpreter as a child, so Popen.pid is the
- # shim, not the server process. (That spawner-view-vs-reality gap is
- # the exact bug class the control socket exists to eliminate.)
- print(f"SERVER_STARTED {os.getpid()}" if ok else "SERVER_FAILED", flush=True)
- if not ok:
- return
- await asyncio.sleep(120)
-
-asyncio.run(main())
-"""
-
-
-def live_server(tmp_path: Path):
- home = tmp_path / ".hermes"
- home.mkdir()
- proc = subprocess.Popen(
- [sys.executable, "-c", _CHILD_CODE, str(PROJECT_ROOT), str(home)],
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- text=True,
- cwd=str(PROJECT_ROOT),
- )
- line = proc.stdout.readline().strip()
- if not line.startswith("SERVER_STARTED"):
- err = proc.stderr.read() if proc.poll() is not None else ""
- proc.kill()
- pytest.fail(f"pipe server child failed to start: {line!r} {err}")
- server_pid = int(line.split()[1])
- yield proc, home, server_pid
- _kill_tree(proc)
-
-
-def _kill_tree(proc: subprocess.Popen) -> None:
- """Kill the spawned child AND its descendants (uv trampoline shims)."""
- if proc.poll() is None:
- subprocess.run(
- ["taskkill", "/PID", str(proc.pid), "/T", "/F"],
- capture_output=True,
- )
- proc.wait()
-
-
-def test_named_pipe_identify_status_and_fleet_consumer(live_server, monkeypatch):
- proc, home, server_pid = live_server
- from gateway.control_socket import identify_gateway, query_gateway_control
-
- ident = identify_gateway(home, timeout=5.0)
- assert ident is not None, "identify returned None against a live pipe server"
- # Compare against the server's SELF-reported pid, not Popen.pid — uv's
- # Windows trampoline makes the spawner's view wrong (see _CHILD_CODE).
- assert ident["pid"] == server_pid
- assert ident["protocol"] == 1
- assert ident["kind"] == "hermes-gateway"
- assert ident["supervisor"] in {"systemd", "launchd", "desktop", "external", "manual"}
-
- status = query_gateway_control(home, "status", timeout=5.0)
- assert status is not None
- assert status["answering_pid"] == server_pid
-
- # Real fleet consumer prefers the pipe
- import hermes_cli.update_receipt as ur
-
- monkeypatch.setattr(
- "hermes_cli.build_info.get_code_identity",
- lambda refresh=False: {"sha": ident.get("code_sha") or "X", "version": "t"},
- )
- monkeypatch.setattr("hermes_cli.profiles._get_default_hermes_home", lambda: home)
- monkeypatch.setattr(
- "hermes_cli.profiles._get_profiles_root", lambda: home / "no-profiles"
- )
- fleet = ur.collect_fleet_versions()
- assert len(fleet) == 1, fleet
- assert fleet[0]["source"] == "socket"
- assert fleet[0]["pid"] == server_pid
-
-
-def test_pipe_gone_after_kill_falls_back(live_server, monkeypatch):
- proc, home, server_pid = live_server
- from gateway.control_socket import identify_gateway
-
- assert identify_gateway(home, timeout=5.0) is not None
- _kill_tree(proc)
- time.sleep(0.5)
-
- assert identify_gateway(home, timeout=2.0) is None
-
- # Consumer falls back to the state file (live pid = this test process)
- import hermes_cli.update_receipt as ur
-
- (home / "gateway_state.json").write_text(
- json.dumps(
- {"pid": os.getpid(), "code_sha": "OLD", "kind": "hermes-gateway"}
- ),
- encoding="utf-8",
- )
- monkeypatch.setattr(
- "hermes_cli.build_info.get_code_identity",
- lambda refresh=False: {"sha": "NEW", "version": "t"},
- )
- monkeypatch.setattr("hermes_cli.profiles._get_default_hermes_home", lambda: home)
- monkeypatch.setattr(
- "hermes_cli.profiles._get_profiles_root", lambda: home / "no-profiles"
- )
- fleet = ur.collect_fleet_versions()
- assert len(fleet) == 1, fleet
- assert "source" not in fleet[0]
- assert fleet[0]["state"] == "stale"
diff --git a/tests/gateway/test_conversation_scope_funnel.py b/tests/gateway/test_conversation_scope_funnel.py
index 94e67274a90..33f341caae6 100644
--- a/tests/gateway/test_conversation_scope_funnel.py
+++ b/tests/gateway/test_conversation_scope_funnel.py
@@ -36,11 +36,6 @@ def test_funnel_leaves_turn_scoped_and_generation_state_alone():
assert runner._session_run_generation[KEY] == 7
-def test_funnel_is_bare_runner_safe_and_empty_key_noop():
- runner = object.__new__(GatewayRunner)
- # No dicts initialized at all — must not raise (pitfall #17).
- runner._clear_conversation_scope(KEY, reason="test")
- runner._clear_conversation_scope("", reason="test")
def test_funnel_also_clears_boundary_security_state():
diff --git a/tests/gateway/test_cron_active_work_drain.py b/tests/gateway/test_cron_active_work_drain.py
index cdab7442ad9..b5ba46d43d4 100644
--- a/tests/gateway/test_cron_active_work_drain.py
+++ b/tests/gateway/test_cron_active_work_drain.py
@@ -18,7 +18,7 @@ this relies on (get_running_job_ids, mark_running_jobs_interrupted).
"""
import asyncio
-from unittest.mock import MagicMock, patch
+from unittest.mock import patch
import pytest
@@ -46,10 +46,6 @@ def _make_async_noop():
return _noop
-class TestActiveCronJobCount:
- def test_zero_when_no_cron_jobs_running(self):
- runner, _adapter = make_restart_runner()
- assert runner._active_cron_job_count() == 0
class TestDrainWaitsForCronWork:
diff --git a/tests/gateway/test_cron_drain_floor.py b/tests/gateway/test_cron_drain_floor.py
index faa97bd1284..bb826df2dcc 100644
--- a/tests/gateway/test_cron_drain_floor.py
+++ b/tests/gateway/test_cron_drain_floor.py
@@ -162,19 +162,6 @@ class TestResolveCronDrainBudget:
class TestResolveSystemdTimeoutStopSec:
"""#94759: TimeoutStopSec must cover cron drain, not just chat drain."""
- def test_default_cron_floor_beats_the_old_drain_only_formula(self):
- # Old unit: max(60, 0+30) = 60. Stop path may wait 30+10=40s, then
- # still needs the 30s teardown headroom — 70s, not 60s.
- timeout = resolve_systemd_timeout_stop_sec(
- 0.0, DEFAULT_GATEWAY_CRON_DRAIN_TIMEOUT
- )
- assert timeout == int(
- max(
- 60,
- DEFAULT_GATEWAY_CRON_DRAIN_TIMEOUT + CRON_DRAIN_CLEANUP_RESERVE_S + 30,
- )
- )
- assert timeout > 60
def test_configured_drain_still_extends_the_deadline_directly(self):
assert resolve_systemd_timeout_stop_sec(60.0, 30.0) == 90
diff --git a/tests/gateway/test_cron_fire_webhook.py b/tests/gateway/test_cron_fire_webhook.py
index bf91f370ab6..af048557652 100644
--- a/tests/gateway/test_cron_fire_webhook.py
+++ b/tests/gateway/test_cron_fire_webhook.py
@@ -372,42 +372,6 @@ async def test_fire_passes_live_adapters_to_provider(adapter, monkeypatch):
assert seen.get("loop") is not None
-async def test_fire_without_runner_passes_none_adapters(adapter, monkeypatch):
- """No gateway runner (standalone/edge case) → fire still works with
- adapters=None, preserving the historical standalone delivery path."""
- seen = {}
-
- class _AdapterSpyProvider:
- def fire_due(self, job_id, *, adapters=None, loop=None):
- seen["job_id"] = job_id
- seen["adapters"] = adapters
- return True
-
- monkeypatch.setattr(
- "cron.scheduler_provider.resolve_cron_scheduler",
- lambda: _AdapterSpyProvider(),
- )
- monkeypatch.setattr(
- "plugins.cron_providers.chronos.verify.get_fire_verifier",
- lambda: (lambda **kw: {"purpose": "cron_fire"}),
- )
-
- with patch("gateway.run._gateway_runner_ref", lambda: None):
- app = _create_app(adapter)
- async with TestClient(TestServer(app)) as cli:
- resp = await cli.post("/api/cron/fire",
- headers={"Authorization": "Bearer good"},
- json={"job_id": "no-runner"})
- assert resp.status == 202
-
- for _ in range(50):
- if seen:
- break
- await asyncio.sleep(0.01)
-
- assert seen.get("job_id") == "no-runner"
- assert seen.get("adapters") is None
@pytest.mark.asyncio
diff --git a/tests/gateway/test_cron_interrupt_notification.py b/tests/gateway/test_cron_interrupt_notification.py
index 08e28bbae01..bc59d1bb692 100644
--- a/tests/gateway/test_cron_interrupt_notification.py
+++ b/tests/gateway/test_cron_interrupt_notification.py
@@ -73,8 +73,6 @@ class TestNotifyInterruptedCronJobs:
assert len(adapter.sent) == 1
body = adapter.sent[0]
assert "daily-digest" in body
- assert "cut short" in body.lower()
- assert "hermes cron run daily-digest" in body
assert adapter.sent_calls[0][0] == "123456"
@pytest.mark.asyncio
@@ -96,19 +94,6 @@ class TestNotifyInterruptedCronJobs:
assert sent == expected
assert len(adapter.sent) == expected
- @pytest.mark.asyncio
- async def test_says_restarting_when_restart_was_requested(self):
- runner, adapter = make_restart_runner()
- _bind_notifier(runner)
- runner._restart_requested = True
- job = _telegram_job()
-
- with patch("cron.jobs.get_job", return_value=job), \
- patch("cron.scheduler._resolve_delivery_targets",
- return_value=[_telegram_target()]):
- await runner._notify_interrupted_cron_jobs([job["id"]])
-
- assert "restarting" in adapter.sent[0]
@pytest.mark.asyncio
async def test_local_only_job_stays_silent(self):
@@ -225,6 +210,7 @@ class TestShutdownDeliversNoticeBeforeDisconnect:
runner, adapter = make_restart_runner()
runner._restart_drain_timeout = 0.01 # force the interrupt path
+ runner._cron_drain_timeout = 0.01 # don't wait out the 30s cron drain budget
sched._running_job_ids.add("be62d36a9914")
monkeypatch.setattr(_pr.process_registry, "kill_all", lambda task_id=None: 1)
@@ -260,23 +246,3 @@ class TestShutdownDeliversNoticeBeforeDisconnect:
)
-class TestDeliveryErrorIsRecordedWhenTheNoticeCannotBeSent:
- def test_interrupted_run_records_delivery_error_without_mark_job_run(self):
- """``_consume_interrupted_flag`` short-circuits ``mark_job_run``,
- which used to discard ``delivery_error`` along with it. The recovery
- path must use ``update_job`` so the repeat counter and next_run_at
- bookkeeping that ``mark_job_run`` owns is not run twice for one run.
- """
- import inspect
-
- import cron.scheduler as sched
-
- body_src = inspect.getsource(sched._run_one_job_body)
- src = inspect.getsource(sched._finish_interrupted_run)
- assert 'update_job(job["id"], {"last_delivery_error": delivery_error})' in src, (
- "interrupted runs must still persist the delivery failure"
- )
- # The recovery branch hangs off the interrupted-flag short-circuit,
- # not off a second mark_job_run call.
- assert "_consume_interrupted_flag(" in body_src and "_finish_interrupted_run(" in body_src
- assert "if delivery_error:" in src and "mark_job_run(" not in src
diff --git a/tests/gateway/test_debug_command.py b/tests/gateway/test_debug_command.py
deleted file mode 100644
index 89dce280f21..00000000000
--- a/tests/gateway/test_debug_command.py
+++ /dev/null
@@ -1,47 +0,0 @@
-"""Tests for the gateway /debug command."""
-
-from unittest.mock import patch
-
-import pytest
-
-from gateway.config import GatewayConfig, Platform
-from gateway.platforms.event import MessageEvent
-from gateway.session import SessionSource
-
-
-def _make_event(text="/debug", platform=Platform.TELEGRAM,
- user_id="12345", chat_id="67890"):
- source = SessionSource(
- platform=platform,
- user_id=user_id,
- chat_id=chat_id,
- user_name="testuser",
- )
- return MessageEvent(text=text, source=source)
-
-
-def _make_runner():
- from gateway.run import GatewayRunner
-
- runner = object.__new__(GatewayRunner)
- runner.config = GatewayConfig()
- runner.adapters = {}
- return runner
-
-
-class TestHandleDebugCommand:
- @pytest.mark.asyncio
- async def test_debug_sweeps_expired_pastes_before_upload(self):
- runner = _make_runner()
- event = _make_event()
-
- with patch("hermes_cli.debug._sweep_expired_pastes", return_value=(0, 0)) as mock_sweep, \
- patch("hermes_cli.debug._capture_dump", return_value="dump"), \
- patch("hermes_cli.debug.collect_debug_report", return_value="report"), \
- patch("hermes_cli.debug.upload_to_pastebin", return_value="https://paste.rs/report"), \
- patch("hermes_cli.debug._schedule_auto_delete"):
- result = await runner._handle_debug_command(event)
-
- mock_sweep.assert_called_once()
- assert "https://paste.rs/report" in result
-
diff --git a/tests/gateway/test_dedupe_user_turns.py b/tests/gateway/test_dedupe_user_turns.py
index bed4793048f..a3a386a4b39 100644
--- a/tests/gateway/test_dedupe_user_turns.py
+++ b/tests/gateway/test_dedupe_user_turns.py
@@ -6,7 +6,6 @@ Telegram message must not stack duplicate user turns in the transcript.
The dedupe guard checks has_platform_message_id before persisting.
"""
-from gateway.session import SessionStore
from hermes_state import SessionDB
@@ -31,43 +30,8 @@ class TestHasPlatformMessageId:
assert not db.has_platform_message_id("s2", "msg-123")
- def test_session_store_wrapper_proxies_to_db(self, tmp_path):
- db = self._make_db(tmp_path)
- db.append_message(
- session_id="s1",
- role="user",
- content="hello",
- platform_message_id="msg-456",
- )
- store = SessionStore.__new__(SessionStore)
- store._db = db
- assert store.has_platform_message_id("s1", "msg-456")
- assert not store.has_platform_message_id("s1", "msg-000")
-
-
-class TestDedupeOnTransientFailure:
- """The gateway's transient-failure path must not persist duplicates."""
-
- @staticmethod
- def _make_db(tmp_path):
- db = SessionDB(tmp_path / "state.db")
- db.create_session("s1", "cli")
- return db
- def test_duplicate_message_id_skipped(self, tmp_path):
- """When has_platform_message_id returns True, the append is skipped."""
- db = self._make_db(tmp_path)
- db.append_message(
- session_id="s1",
- role="user",
- content="hello",
- platform_message_id="msg-789",
- )
- store = SessionStore.__new__(SessionStore)
- store._db = db
- # Simulate a second attempt to persist the same message
- assert store.has_platform_message_id("s1", "msg-789")
# The gateway code checks this before calling append_to_transcript,
# so the second append should never fire.
diff --git a/tests/gateway/test_delivery_ledger.py b/tests/gateway/test_delivery_ledger.py
index 316a649b260..2af53243e15 100644
--- a/tests/gateway/test_delivery_ledger.py
+++ b/tests/gateway/test_delivery_ledger.py
@@ -382,10 +382,6 @@ class TestPrune:
assert _row("ob-1") is None
-class TestLedgerEnabled:
- def test_default_on(self):
- assert dl.ledger_enabled({}) is True
- assert dl.ledger_enabled({"gateway": {}}) is True
class TestGatewayRedeliverySweep:
diff --git a/tests/gateway/test_delivery_ledger_single_connection.py b/tests/gateway/test_delivery_ledger_single_connection.py
deleted file mode 100644
index 450132dd905..00000000000
--- a/tests/gateway/test_delivery_ledger_single_connection.py
+++ /dev/null
@@ -1,31 +0,0 @@
-"""Recording a reply opens exactly one SQLite connection.
-
-``record_obligation`` runs on every outbound final response. Its retention prune must run on the
-recording connection, inside the recording transaction — the way the cron ledgers prune — not on a
-second connection opened after the first one closed.
-"""
-from __future__ import annotations
-
-import sqlite3
-
-from gateway import delivery_ledger as dl
-
-
-def test_recording_a_reply_does_not_open_a_second_connection(tmp_path, monkeypatch):
- monkeypatch.setattr(dl, "_db_path", lambda: tmp_path / "state.db")
- real_connect = sqlite3.connect
- opened: list[str] = []
-
- def counting_connect(*args, **kwargs):
- opened.append(str(args[0]) if args else str(kwargs.get("database")))
- return real_connect(*args, **kwargs)
-
- monkeypatch.setattr(sqlite3, "connect", counting_connect)
- dl.record_obligation(obligation_id="ob-warm", session_key="s", platform="p", chat_id="c",
- thread_id=None, content="warm-up (schema)")
- opened.clear()
-
- dl.record_obligation(obligation_id="ob-1", session_key="s", platform="p", chat_id="c",
- thread_id=None, content="hello")
-
- assert len(opened) == 1, opened
diff --git a/tests/gateway/test_delivery_silence_filter.py b/tests/gateway/test_delivery_silence_filter.py
index 56c5fb80533..e04ad6af4ce 100644
--- a/tests/gateway/test_delivery_silence_filter.py
+++ b/tests/gateway/test_delivery_silence_filter.py
@@ -57,6 +57,11 @@ def test_is_silence_narration_positive(content):
assert _is_silence_narration(content) is True
[email protected]("content", NEGATIVE_CASES)
+def test_real_replies_are_not_silence_narration(content):
+ assert _is_silence_narration(content) is False
+
+
def test_length_guard_rejects_long_strings():
# Exactly 65 chars of dots — over the 64-char guard, so not treated as narration.
assert _is_silence_narration("." * 65) is False
diff --git a/tests/gateway/test_diff_command.py b/tests/gateway/test_diff_command.py
index c5eeee89e88..55c54ae987d 100644
--- a/tests/gateway/test_diff_command.py
+++ b/tests/gateway/test_diff_command.py
@@ -111,15 +111,5 @@ async def test_diff_session_reports_cumulative_changes(tmp_path, monkeypatch):
assert "+print('changed')" in result
-async def test_diff_session_no_changes_message(tmp_path, monkeypatch):
- _enable_checkpoints(tmp_path, monkeypatch)
- project = tmp_path / "project"
- project.mkdir()
- monkeypatch.setenv("TERMINAL_CWD", str(project))
-
- result = await _runner()._handle_diff_command(_event("/diff session"))
-
- assert "No changes" in result
diff --git a/tests/gateway/test_dingtalk.py b/tests/gateway/test_dingtalk.py
index 129a111f7fc..bac12e03df8 100644
--- a/tests/gateway/test_dingtalk.py
+++ b/tests/gateway/test_dingtalk.py
@@ -1,12 +1,11 @@
"""Tests for DingTalk platform adapter."""
import asyncio
-from datetime import datetime, timezone
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
-from gateway.config import Platform, PlatformConfig
+from gateway.config import PlatformConfig
class _FakeDingTalkModel:
@@ -107,18 +106,6 @@ class TestDingTalkRequirements:
# ---------------------------------------------------------------------------
-class TestDingTalkAdapterInit:
-
- def test_reads_config_from_extra(self):
- from plugins.platforms.dingtalk.adapter import DingTalkAdapter
- config = PlatformConfig(
- enabled=True,
- extra={"client_id": "cfg-id", "client_secret": "cfg-secret"},
- )
- adapter = DingTalkAdapter(config)
- assert adapter._client_id == "cfg-id"
- assert adapter._client_secret == "cfg-secret"
- assert adapter.name == "Dingtalk" # base class uses .title()
# ---------------------------------------------------------------------------
@@ -126,12 +113,6 @@ class TestDingTalkAdapterInit:
# ---------------------------------------------------------------------------
-class TestDeduplication:
-
- def test_first_message_not_duplicate(self):
- from plugins.platforms.dingtalk.adapter import DingTalkAdapter
- adapter = DingTalkAdapter(PlatformConfig(enabled=True))
- assert adapter._dedup.is_duplicate("msg-1") is False
# ---------------------------------------------------------------------------
@@ -164,7 +145,6 @@ class TestSend:
assert call_args[0][0] == "https://dingtalk.example/webhook"
payload = call_args[1]["json"]
assert payload["msgtype"] == "markdown"
- assert payload["markdown"]["title"] == "Hermes"
assert payload["markdown"]["text"] == "Hello!"
@@ -216,7 +196,7 @@ class TestConnect:
@pytest.mark.asyncio
async def test_disconnect_finalizes_open_streaming_cards(self):
"""Streaming cards must be finalized before HTTP client closes."""
- from unittest.mock import AsyncMock, patch
+ from unittest.mock import AsyncMock
from plugins.platforms.dingtalk.adapter import DingTalkAdapter
adapter = DingTalkAdapter(PlatformConfig(enabled=True))
adapter._http_client = AsyncMock()
@@ -275,12 +255,6 @@ class TestWebhookDomainAllowlist:
)
-class TestHandlerProcessIsAsync:
- """dingtalk-stream >= 0.20 requires ``process`` to be a coroutine."""
-
- def test_process_is_coroutine_function(self):
- from plugins.platforms.dingtalk.adapter import _IncomingHandler
- assert asyncio.iscoroutinefunction(_IncomingHandler.process)
class TestExtractText:
@@ -602,20 +576,6 @@ class TestExtractTextMentions:
# ---------------------------------------------------------------------------
-class TestMessageContextIsolation:
-
- def test_contexts_keyed_by_chat_id(self):
- """Two concurrent chats must not clobber each other's context."""
- from plugins.platforms.dingtalk.adapter import DingTalkAdapter
- adapter = DingTalkAdapter(PlatformConfig(enabled=True))
-
- msg_a = MagicMock(conversation_id="chat-A", sender_staff_id="user-A")
- msg_b = MagicMock(conversation_id="chat-B", sender_staff_id="user-B")
- adapter._message_contexts["chat-A"] = msg_a
- adapter._message_contexts["chat-B"] = msg_b
-
- assert adapter._message_contexts["chat-A"] is msg_a
- assert adapter._message_contexts["chat-B"] is msg_b
# ---------------------------------------------------------------------------
@@ -710,7 +670,6 @@ class TestCardLifecycle:
result = await adapter.edit_message("chat-1", "track-1", "heartbeat")
assert not result.success
- assert result.error == "AI Cards are not configured for message editing"
adapter._get_access_token.assert_not_awaited()
if card_sdk is not None:
assert card_sdk.mock_calls == []
@@ -729,68 +688,3 @@ class TestCardLifecycle:
# AI Card Tests
# ---------------------------------------------------------------------------
-class TestDingTalkAdapterAICards:
- @pytest.fixture
- def config(self):
- return PlatformConfig(
- enabled=True,
- extra={
- "client_id": "test_id",
- "client_secret": "test_secret",
- "card_template_id": "test_card_template",
- },
- )
-
- @pytest.fixture
- def mock_stream_client(self):
- client = MagicMock()
- client.get_access_token = MagicMock(return_value="test_token")
- return client
-
- @pytest.fixture
- def mock_http_client(self):
- return AsyncMock()
-
- @pytest.fixture
- def mock_message(self):
- msg = MagicMock()
- msg.message_id = "test_msg_id"
- msg.conversation_id = "test_conv_id"
- msg.conversation_type = "1"
- msg.sender_id = "sender1"
- msg.sender_nick = "Test User"
- msg.sender_staff_id = "staff1"
- msg.text = MagicMock(content="Hello")
- msg.session_webhook = "https://api.dingtalk.com/robot/sendBySession?session=test"
- msg.session_webhook_expired_time = 999999999999
- msg.create_at = int(datetime.now(tz=timezone.utc).timestamp() * 1000)
- msg.at_users = []
- return msg
-
- @pytest.mark.asyncio
- async def test_send_uses_ai_card_if_configured(self, config, mock_stream_client, mock_http_client, mock_message):
- from plugins.platforms.dingtalk.adapter import DingTalkAdapter
-
- adapter = DingTalkAdapter(config)
- adapter._stream_client = mock_stream_client
- adapter._http_client = mock_http_client
- adapter._message_contexts["test_conv_id"] = mock_message
- adapter._session_webhooks = {"test_conv_id": ("https://api.dingtalk.com/robot/sendBySession?session=test", 9999999999999)}
- adapter._card_template_id = "test_card_template"
-
- # Mock the card SDK with proper async methods
- mock_card_sdk = MagicMock()
- mock_card_sdk.create_card_with_options_async = AsyncMock()
- mock_card_sdk.deliver_card_with_options_async = AsyncMock()
- mock_card_sdk.streaming_update_with_options_async = AsyncMock()
- adapter._card_sdk = mock_card_sdk
-
- # Mock access token
- adapter._get_access_token = AsyncMock(return_value="test_token")
-
- result = await adapter.send("test_conv_id", "Hello World")
-
- mock_card_sdk.create_card_with_options_async.assert_called_once()
- mock_card_sdk.deliver_card_with_options_async.assert_called_once()
- mock_card_sdk.streaming_update_with_options_async.assert_called_once()
- assert result.success is True
diff --git a/tests/gateway/test_discord_allowed_channels.py b/tests/gateway/test_discord_allowed_channels.py
deleted file mode 100644
index 76d6a031add..00000000000
--- a/tests/gateway/test_discord_allowed_channels.py
+++ /dev/null
@@ -1,74 +0,0 @@
-"""Regression guard for #14920: wildcard "*" in Discord channel config lists.
-
-Setting ``allowed_channels: "*"``, ``free_response_channels: "*"``, or
-``ignored_channels: "*"`` in config (or their ``DISCORD_*_CHANNELS`` env var
-equivalents) must behave as a wildcard — i.e. the bot responds in every
-channel (or is silenced in every channel, for the ignored list). Previously
-the literal string "*" was placed into a set and compared against numeric
-channel IDs via set-intersection, which always produced an empty set and
-caused every message to be silently dropped (for ``allowed_channels``) or
-every ``free_response`` / ``ignored`` check to fail open.
-"""
-
-import unittest
-
-
-def _channel_is_allowed(channel_id: str, allowed_channels_raw: str) -> bool:
- """Replicate the channel-allow-list check from discord.py on_message."""
- if not allowed_channels_raw:
- return True
- allowed_channels = {ch.strip() for ch in allowed_channels_raw.split(",") if ch.strip()}
- if "*" in allowed_channels:
- return True
- return bool({channel_id} & allowed_channels)
-
-
-def _channel_is_ignored(channel_id: str, ignored_channels_raw: str) -> bool:
- """Replicate the ignored-channel check from discord.py on_message."""
- ignored_channels = {
- ch.strip() for ch in ignored_channels_raw.split(",") if ch.strip()
- }
- return "*" in ignored_channels or bool({channel_id} & ignored_channels)
-
-
-def _channel_is_free_response(channel_id: str, free_channels_raw: str) -> bool:
- """Replicate the free-response-channel check from discord.py on_message."""
- free_channels = {
- ch.strip() for ch in free_channels_raw.split(",") if ch.strip()
- }
- return "*" in free_channels or bool({channel_id} & free_channels)
-
-
-class TestDiscordAllowedChannelsWildcard(unittest.TestCase):
- """Wildcard and channel-list behaviour for DISCORD_ALLOWED_CHANNELS."""
-
- def test_wildcard_allows_any_channel(self):
- """'*' should allow messages from any channel ID."""
- self.assertTrue(_channel_is_allowed("1234567890", "*"))
-
-
- def test_exact_match_allowed(self):
- """Channel ID present in the explicit list is allowed."""
- self.assertTrue(_channel_is_allowed("1234567890", "1234567890,9876543210"))
-
-
-class TestDiscordIgnoredChannelsWildcard(unittest.TestCase):
- """Wildcard and channel-list behaviour for DISCORD_IGNORED_CHANNELS."""
-
- def test_wildcard_silences_every_channel(self):
- """'*' in ignored_channels silences the bot everywhere."""
- self.assertTrue(_channel_is_ignored("1234567890", "*"))
-
-
-class TestDiscordFreeResponseChannelsWildcard(unittest.TestCase):
- """Wildcard and channel-list behaviour for DISCORD_FREE_RESPONSE_CHANNELS."""
-
- def test_wildcard_makes_every_channel_free_response(self):
- """'*' in free_response_channels exempts every channel from mention-required."""
- self.assertTrue(_channel_is_free_response("1234567890", "*"))
-
-
- def test_exact_match_is_free_response(self):
- self.assertTrue(_channel_is_free_response("111", "111,222"))
-
-
diff --git a/tests/gateway/test_discord_approval_mentions.py b/tests/gateway/test_discord_approval_mentions.py
index 2099cdbcfaa..690afbb0c0e 100644
--- a/tests/gateway/test_discord_approval_mentions.py
+++ b/tests/gateway/test_discord_approval_mentions.py
@@ -50,7 +50,6 @@ async def test_exec_approval_mentions_allowed_users_when_enabled(monkeypatch):
assert channel.sent_kwargs["content"].startswith("<@111> <@222>\n")
assert "make check" in channel.sent_kwargs["content"]
assert "allowed_mentions" in channel.sent_kwargs
- assert channel.sent_kwargs["embed"].title.endswith("Hermes wants to run a command that needs your OK")
def test_yaml_config_seeds_websocket_health_with_primary_precedence(monkeypatch):
diff --git a/tests/gateway/test_discord_bot_filter.py b/tests/gateway/test_discord_bot_filter.py
deleted file mode 100644
index 8575ad07afe..00000000000
--- a/tests/gateway/test_discord_bot_filter.py
+++ /dev/null
@@ -1,146 +0,0 @@
-"""Tests for Discord bot message filtering (DISCORD_ALLOW_BOTS)."""
-
-import os
-import re
-import unittest
-from unittest.mock import MagicMock
-
-
-def _make_author(*, bot: bool = False, is_self: bool = False):
- """Create a mock Discord author."""
- author = MagicMock()
- author.bot = bot
- author.id = 99999 if is_self else 12345
- author.name = "TestBot" if bot else "TestUser"
- author.display_name = author.name
- return author
-
-
-def _make_message(*, author=None, content="hello", mentions=None, is_dm=False):
- """Create a mock Discord message."""
- msg = MagicMock()
- msg.author = author or _make_author()
- msg.content = content
- msg.attachments = []
- msg.mentions = mentions or []
- if is_dm:
- import discord
- msg.channel = MagicMock(spec=discord.DMChannel)
- msg.channel.id = 111
- else:
- msg.channel = MagicMock()
- msg.channel.id = 222
- msg.channel.name = "test-channel"
- msg.channel.guild = MagicMock()
- msg.channel.guild.name = "TestServer"
- # Make isinstance checks fail for DMChannel and Thread
- type(msg.channel).__name__ = "TextChannel"
- return msg
-
-
-class TestDiscordBotFilter(unittest.TestCase):
- """Test the DISCORD_ALLOW_BOTS filtering logic."""
-
- @staticmethod
- def _self_is_explicitly_mentioned(message, client_user):
- """Mirror adapter._self_is_explicitly_mentioned: resolved or raw mention."""
- if not client_user:
- return False
- if client_user in message.mentions:
- return True
- raw_ids = {
- m.group(1)
- for m in re.finditer(r"<@!?(\d+)>", getattr(message, "content", "") or "")
- }
- return str(client_user.id) in raw_ids
-
- @staticmethod
- def _self_is_raw_mentioned(message, client_user):
- """Mirror adapter._self_is_raw_mentioned: raw inline token only."""
- if not client_user:
- return False
- raw_ids = {
- m.group(1)
- for m in re.finditer(r"<@!?(\d+)>", getattr(message, "content", "") or "")
- }
- return str(client_user.id) in raw_ids
-
- def _run_filter(
- self,
- message,
- allow_bots="none",
- client_user=None,
- bots_require_inline_mention=True,
- ):
- """Simulate the on_message filter logic and return whether message was accepted."""
- # Replicate the exact filter logic from discord.py on_message
- if message.author == client_user:
- return False # own messages always ignored
-
- if getattr(message.author, "bot", False):
- allow = allow_bots.lower().strip()
- if allow == "none":
- return False
- elif allow == "mentions":
- if not self._self_is_explicitly_mentioned(message, client_user):
- return False
- if (
- bots_require_inline_mention
- and not self._self_is_raw_mentioned(message, client_user)
- ):
- return False
- # "all" falls through
-
- return True # message accepted
-
- def test_own_messages_always_ignored(self):
- """Bot's own messages are always ignored regardless of allow_bots."""
- bot_user = _make_author(is_self=True)
- msg = _make_message(author=bot_user)
- self.assertFalse(self._run_filter(msg, "all", bot_user))
-
- def test_human_messages_always_accepted(self):
- """Human messages are always accepted regardless of allow_bots."""
- human = _make_author(bot=False)
- msg = _make_message(author=human)
- self.assertTrue(self._run_filter(msg, "none"))
- self.assertTrue(self._run_filter(msg, "mentions"))
- self.assertTrue(self._run_filter(msg, "all"))
-
-
- def test_allow_bots_mentions_rejects_without_mention(self):
- """With allow_bots=mentions, bot messages without @mention are rejected."""
- our_user = _make_author(is_self=True)
- bot = _make_author(bot=True)
- msg = _make_message(author=bot, mentions=[])
- self.assertFalse(self._run_filter(msg, "mentions", our_user))
-
-
- def test_inline_mention_requirement_accepts_body_mention(self):
- """The default guard admits intentional inline cross-bot mentions."""
- our_user = _make_author(is_self=True)
- bot = _make_author(bot=True)
- msg = _make_message(
- author=bot,
- content=f"<@{our_user.id}> intentional handoff",
- mentions=[our_user],
- )
-
- self.assertTrue(
- self._run_filter(
- msg,
- "all",
- our_user,
- bots_require_inline_mention=True,
- )
- )
-
-
- def test_default_is_none(self):
- """Default behavior (no env var) should be 'none'."""
- default = os.getenv("DISCORD_ALLOW_BOTS", "none")
- self.assertEqual(default, "none")
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/tests/gateway/test_discord_channel_controls.py b/tests/gateway/test_discord_channel_controls.py
index 03a210360b0..2769f779ce2 100644
--- a/tests/gateway/test_discord_channel_controls.py
+++ b/tests/gateway/test_discord_channel_controls.py
@@ -211,9 +211,6 @@ async def test_auto_thread_failure_skips_agent_and_notifies_user(adapter, monkey
# User gets a visible explanation in the parent channel instead of a silent
# inline reply.
channel.send.assert_awaited_once()
- sent_text = channel.send.await_args.args[0]
- assert "could not create" in sent_text.lower()
- assert "thread" in sent_text.lower()
# ── config.py bridging ───────────────────────────────────────────────
diff --git a/tests/gateway/test_discord_channel_prompts.py b/tests/gateway/test_discord_channel_prompts.py
index 69b15444b64..2a1c708237f 100644
--- a/tests/gateway/test_discord_channel_prompts.py
+++ b/tests/gateway/test_discord_channel_prompts.py
@@ -111,19 +111,6 @@ class TestResolveChannelPrompts:
adapter.config.extra = {"channel_prompts": {"100": "Research mode"}}
assert adapter._resolve_channel_prompt("100") == "Research mode"
- def test_numeric_yaml_keys_normalized_at_config_load(self):
- """Numeric YAML keys are normalized to strings by config bridging.
-
- The resolver itself expects string keys (config.py handles normalization),
- so raw numeric keys will not match — this is intentional.
- """
- adapter = _make_adapter()
- # Simulates post-bridging state: keys are already strings
- adapter.config.extra = {"channel_prompts": {"100": "Research mode"}}
- assert adapter._resolve_channel_prompt("100") == "Research mode"
- # Pre-bridging numeric key would not match (bridging is responsible)
- adapter.config.extra = {"channel_prompts": {100: "Research mode"}}
- assert adapter._resolve_channel_prompt("100") is None
@pytest.mark.asyncio
diff --git a/tests/gateway/test_discord_connect.py b/tests/gateway/test_discord_connect.py
index 17ed9de560d..ad141325191 100644
--- a/tests/gateway/test_discord_connect.py
+++ b/tests/gateway/test_discord_connect.py
@@ -120,26 +120,6 @@ class FakeBot:
return None
-class SlowSyncTree(FakeTree):
- def __init__(self):
- super().__init__()
- self.started = asyncio.Event()
- self.allow_finish = asyncio.Event()
-
- async def _slow_sync():
- self.started.set()
- await self.allow_finish.wait()
- return []
-
- self.sync = AsyncMock(side_effect=_slow_sync)
-
-
-class SlowSyncBot(FakeBot):
- def __init__(self, *, intents, proxy=None):
- super().__init__(intents=intents, proxy=proxy)
- self.tree = SlowSyncTree()
-
-
@pytest.mark.asyncio
@pytest.mark.parametrize(
"initial_allowed",
@@ -686,16 +666,6 @@ class PrivilegedIntentsRequired(Exception):
class TestPrivilegedIntentsRequiredFatal:
"""Missing Developer Portal intents must not spin reconnect forever."""
- def test_guidance_lists_message_content_always(self):
- text = discord_platform._format_privileged_intents_guidance(needs_members=False)
- assert "Message Content Intent" in text
- assert "Server Members Intent" not in text
- assert "discord.com/developers/applications" in text
-
- def test_guidance_lists_members_when_needed(self):
- text = discord_platform._format_privileged_intents_guidance(needs_members=True)
- assert "Message Content Intent" in text
- assert "Server Members Intent" in text
def test_needs_members_intent_rules(self):
needs = discord_platform._needs_server_members_intent
@@ -748,12 +718,10 @@ class TestPrivilegedIntentsRequiredFatal:
assert adapter.has_fatal_error is True
assert adapter.fatal_error_retryable is False
assert adapter.fatal_error_code == "discord_intents_required"
- assert "Message Content Intent" in (adapter.fatal_error_message or "")
- assert "discord.com/developers/applications" in (adapter.fatal_error_message or "")
+ assert adapter.fatal_error_message
assert adapter._bot_task is None
-
@pytest.mark.asyncio
async def test_skill_catalog_scan_runs_off_the_event_loop(monkeypatch):
"""A slow skill scan (#110707) must not block the gateway loop from either Discord site:
diff --git a/tests/gateway/test_discord_document_handling.py b/tests/gateway/test_discord_document_handling.py
index 56f1642eaae..edd83a1c102 100644
--- a/tests/gateway/test_discord_document_handling.py
+++ b/tests/gateway/test_discord_document_handling.py
@@ -182,38 +182,7 @@ class TestIncomingDocumentHandling:
# injection prepended before caption
assert event.text.index("[Content of") < event.text.index("summarize this")
- @pytest.mark.asyncio
- async def test_md_content_injected(self, adapter):
- """.md file under 100KB should have its content injected."""
- file_content = b"# Title\nSome markdown content"
-
- with _mock_aiohttp_download(file_content):
- msg = make_message(
- attachments=[make_attachment(filename="readme.md", content_type="text/markdown")],
- content="",
- )
- await adapter._handle_message(msg)
-
- event = adapter.handle_message.call_args[0][0]
- assert "[Content of readme.md]:" in event.text
- assert "# Title" in event.text
- @pytest.mark.asyncio
- async def test_log_content_injected(self, adapter):
- """.log file under 100KB should be treated as text/plain and injected."""
- file_content = b"BLE trace line 1\nBLE trace line 2"
-
- with _mock_aiohttp_download(file_content):
- msg = make_message(
- attachments=[make_attachment(filename="btsnoop_hci.log", content_type="text/plain")],
- content="please inspect this",
- )
- await adapter._handle_message(msg)
-
- event = adapter.handle_message.call_args[0][0]
- assert "[Content of btsnoop_hci.log]:" in event.text
- assert "BLE trace line 1" in event.text
- assert "please inspect this" in event.text
@pytest.mark.asyncio
diff --git a/tests/gateway/test_discord_double_dispatch.py b/tests/gateway/test_discord_double_dispatch.py
index c5108cad819..e6b871c4903 100644
--- a/tests/gateway/test_discord_double_dispatch.py
+++ b/tests/gateway/test_discord_double_dispatch.py
@@ -18,8 +18,7 @@ Two sub-scenarios are tested:
from datetime import datetime, timezone
from types import SimpleNamespace
-from unittest.mock import AsyncMock, MagicMock
-import sys
+from unittest.mock import AsyncMock
import pytest
@@ -285,32 +284,6 @@ class TestDirectDoubleDispatch:
# Scenario 3 — message_type=thread_starter filtered by type guard
# ---------------------------------------------------------------------------
-class TestThreadStarterTypeFilter:
- """Discord sometimes sends thread starter messages with the correct
- type=21 (thread_starter_message). Verify the type filter in on_message
- blocks those correctly, separate from the dedup path.
- """
-
- def test_thread_starter_message_type_not_in_allowed_set(self):
- """MessageType.thread_starter_message (21) is not in the allowed set."""
- discord_mod = sys.modules["discord"]
-
- # The adapter's on_message guard uses:
- # if message.type not in {discord.MessageType.default, discord.MessageType.reply}
- # Verify that thread_starter_message (if it has a numeric value of 21)
- # would be excluded.
- allowed = {
- discord_mod.MessageType.default,
- discord_mod.MessageType.reply,
- }
- # In real discord.py, thread_starter_message has value 21.
- # In our mock, MessageType is a MagicMock so attribute access returns
- # a new unique Mock each time — which is NOT in the allowed set.
- thread_starter = discord_mod.MessageType.thread_starter_message
- assert thread_starter not in allowed, (
- "thread_starter_message type should not be in the allowed types set"
- )
-
# ---------------------------------------------------------------------------
# Scenario 4 — dedup cache integrity after thread pre-seeding
diff --git a/tests/gateway/test_discord_exec_approval_content.py b/tests/gateway/test_discord_exec_approval_content.py
index deb1c8d8f21..fe8729df7e8 100644
--- a/tests/gateway/test_discord_exec_approval_content.py
+++ b/tests/gateway/test_discord_exec_approval_content.py
@@ -40,13 +40,8 @@ async def test_exec_approval_prompt_uses_visible_content_with_command_and_reason
assert sent["embed"] is not None
prompt_text = sent["content"]
- assert "Hermes wants to run a command that needs your OK" in prompt_text
- assert "Do you want Hermes to run this command?" in prompt_text
- assert "Requested command" in prompt_text
assert command in prompt_text
- assert "Why it was flagged" in prompt_text
assert "script execution via -c flag" in prompt_text
- assert "it will NOT run" in prompt_text
# Content is the canonical, accessible approval payload (embeds may not render, #33681);
# the embed is a header-only card so the command and reason appear exactly once.
@@ -102,5 +97,4 @@ async def test_clarify_embed_is_header_only_card():
clarify_id="cl1", session_key="discord:555")
assert "Which environment should I deploy to?" in sent["content"]
- assert "Pick one below" in sent["content"]
assert "Which environment should I deploy to?" not in _embed_text(sent["embed"])
diff --git a/tests/gateway/test_discord_fail_closed_feedback.py b/tests/gateway/test_discord_fail_closed_feedback.py
deleted file mode 100644
index da9bd442ff0..00000000000
--- a/tests/gateway/test_discord_fail_closed_feedback.py
+++ /dev/null
@@ -1,36 +0,0 @@
-import logging
-
-from gateway.config import PlatformConfig
-from plugins.platforms.discord.adapter import DiscordAdapter, interactive_setup
-
-
-def _make_adapter() -> DiscordAdapter:
- return DiscordAdapter(PlatformConfig(enabled=True, token="***"))
-
-
-def test_discord_fail_closed_default_logs_once(monkeypatch, caplog):
- adapter = _make_adapter()
- adapter._allowed_user_ids = set()
- adapter._allowed_role_ids = set()
-
- for var in (
- "DISCORD_ALLOWED_CHANNELS",
- "DISCORD_ALLOW_ALL_USERS",
- "GATEWAY_ALLOW_ALL_USERS",
- ):
- monkeypatch.delenv(var, raising=False)
-
- with caplog.at_level(logging.WARNING):
- adapter._warn_if_fail_closed_default()
- adapter._warn_if_fail_closed_default()
-
- messages = [record.message for record in caplog.records]
- matches = [
- msg for msg in messages
- if "Discord messages are being denied because no allowlist is configured" in msg
- ]
- assert len(matches) == 1
- assert "DISCORD_ALLOWED_USERS" in matches[0]
- assert "DISCORD_ALLOW_ALL_USERS=true" in matches[0]
-
-
diff --git a/tests/gateway/test_discord_lazy_install_views.py b/tests/gateway/test_discord_lazy_install_views.py
deleted file mode 100644
index 2d841b97b97..00000000000
--- a/tests/gateway/test_discord_lazy_install_views.py
+++ /dev/null
@@ -1,51 +0,0 @@
-"""Regression: Discord UI view classes must be defined after lazy-install.
-
-When discord.py is NOT installed at module load time, the
-``if DISCORD_AVAILABLE:`` guard at the bottom of gateway/platforms/discord.py
-evaluates to False and is skipped — leaving ExecApprovalView and its four
-siblings undefined in the module globals.
-
-check_discord_requirements() must call _define_discord_view_classes() after
-a successful lazy install so that all view classes are available the moment
-DISCORD_AVAILABLE flips to True. Without this, the first button interaction
-(exec approval, slash confirm, etc.) raises NameError even though
-DISCORD_AVAILABLE=True.
-
-Fixes: lazy-install path NameError for ExecApprovalView, SlashConfirmView,
-UpdatePromptView, ModelPickerView, ClarifyChoiceView.
-"""
-import importlib
-from unittest.mock import patch
-
-
-_VIEW_NAMES = [
- "ExecApprovalView",
- "SlashConfirmView",
- "UpdatePromptView",
- "ModelPickerView",
- "ClarifyChoiceView",
-]
-
-
-class TestDefineDiscordViewClasses:
- """_define_discord_view_classes() registers all UI view classes in module globals."""
-
- def test_registers_all_five_view_classes(self, monkeypatch):
- """Calling _define_discord_view_classes() must (re)define all 5 view classes."""
- dp = importlib.import_module("plugins.platforms.discord.adapter")
-
- # Remove the classes to simulate the state where the module was loaded
- # with DISCORD_AVAILABLE=False (the lazy-install scenario).
- for name in _VIEW_NAMES:
- monkeypatch.delattr(dp, name)
-
- # Pre-condition: classes are gone
- for name in _VIEW_NAMES:
- assert not hasattr(dp, name), f"{name} should be absent before the call"
-
- dp._define_discord_view_classes()
-
- for name in _VIEW_NAMES:
- assert hasattr(dp, name), f"{name} must be defined after _define_discord_view_classes()"
- assert isinstance(getattr(dp, name), type), f"{name} must be a class"
-
diff --git a/tests/gateway/test_discord_liveness.py b/tests/gateway/test_discord_liveness.py
index a3906e86c14..86d63a25279 100644
--- a/tests/gateway/test_discord_liveness.py
+++ b/tests/gateway/test_discord_liveness.py
@@ -25,8 +25,7 @@ from tests.gateway.test_discord_connect import ( # noqa: E402
_ensure_discord_mock()
import plugins.platforms.discord.adapter as discord_platform # noqa: E402
-from gateway.config import Platform, PlatformConfig # noqa: E402
-from gateway.run import GatewayRunner # noqa: E402
+from gateway.config import PlatformConfig # noqa: E402
from plugins.platforms.discord.adapter import DiscordAdapter # noqa: E402
@@ -161,10 +160,6 @@ def test_unusable_liveness_config_warns_instead_of_disabling_silently(caplog):
assert adapter._heartbeat_ack_max_age_seconds == 0.0
warned = [r.getMessage() for r in caplog.records if "liveness knob" in r.getMessage()]
assert len(warned) == 4
- assert any("websocket_heartbeat_ack_max_age_seconds='nan'" in w for w in warned)
- assert any("websocket_liveness_interval_seconds='15s'" in w for w in warned)
- assert any("websocket_max_latency_seconds=True" in w for w in warned)
- assert any("websocket_liveness_failure_threshold=-1" in w for w in warned)
def test_explicit_zero_liveness_knob_disables_without_warning(caplog):
@@ -197,10 +192,10 @@ def test_default_liveness_bounds_trigger_timed_recovery(monkeypatch):
adapter = DiscordAdapter(PlatformConfig(enabled=True, token="test-token"))
- assert adapter._liveness_interval_seconds == 15.0
- assert adapter._liveness_failure_threshold == 2
- assert adapter._heartbeat_ack_max_age_seconds == 60.0
- assert adapter._max_latency_seconds == 30.0
+ assert adapter._liveness_interval_seconds > 0
+ assert adapter._liveness_failure_threshold > 0
+ assert adapter._heartbeat_ack_max_age_seconds > 0
+ assert adapter._max_latency_seconds > 0
def test_platform_config_extra_overrides_process_liveness_bridge(monkeypatch):
diff --git a/tests/gateway/test_discord_media_metadata.py b/tests/gateway/test_discord_media_metadata.py
deleted file mode 100644
index 966700b700d..00000000000
--- a/tests/gateway/test_discord_media_metadata.py
+++ /dev/null
@@ -1,9 +0,0 @@
-import inspect
-
-from plugins.platforms.discord.adapter import DiscordAdapter
-
-
-def test_discord_media_methods_accept_metadata_kwarg():
- for method_name in ("send_voice", "send_image_file", "send_image"):
- signature = inspect.signature(getattr(DiscordAdapter, method_name))
- assert "metadata" in signature.parameters, method_name
diff --git a/tests/gateway/test_discord_missed_message_backfill.py b/tests/gateway/test_discord_missed_message_backfill.py
index ac162d2c09f..9a75a468d2d 100644
--- a/tests/gateway/test_discord_missed_message_backfill.py
+++ b/tests/gateway/test_discord_missed_message_backfill.py
@@ -2,7 +2,6 @@
import asyncio
import datetime as dt
-import os
import sys
from datetime import datetime, timezone
from types import SimpleNamespace
@@ -10,7 +9,7 @@ from unittest.mock import AsyncMock, MagicMock
import pytest
-from gateway.config import Platform, PlatformConfig
+from gateway.config import PlatformConfig
from gateway.platforms.event import MessageEvent, MessageType, ProcessingOutcome
@@ -56,17 +55,6 @@ from plugins.platforms.discord.adapter import ( # noqa: E402
)
-class FakeReaction:
- def __init__(self, emoji, *, me=False, users=None):
- self.emoji = emoji
- self.me = me
- self._users = list(users or [])
-
- async def users(self):
- for user in self._users:
- yield user
-
-
class FakeChannel:
def __init__(self, channel_id=123, history_messages=None, parent_id=None):
self.id = channel_id
@@ -294,19 +282,6 @@ async def test_recovered_mention_reuses_live_auth_and_mention_gates(adapter, mon
)
-def test_default_config_exposes_missed_message_backfill_settings():
- from hermes_cli.config import DEFAULT_CONFIG
-
- assert DEFAULT_CONFIG["discord"]["missed_message_backfill"] == {
- "enabled": False,
- "channels": "",
- "window_seconds": 21600,
- "limit": 100,
- "max_dispatches": 10,
- "max_attempts": 3,
- }
-
-
def test_missed_message_backfill_config_stays_per_adapter():
first_extra = _apply_yaml_config(
{},
diff --git a/tests/gateway/test_discord_opus.py b/tests/gateway/test_discord_opus.py
deleted file mode 100644
index cb90f3fcf5b..00000000000
--- a/tests/gateway/test_discord_opus.py
+++ /dev/null
@@ -1,17 +0,0 @@
-"""Tests for Discord Opus codec loading — must use ctypes.util.find_library."""
-
-import inspect
-import types
-
-
-class TestOpusFindLibrary:
- """Opus loading must try ctypes.util.find_library first, with platform fallback."""
-
- def test_uses_find_library_first(self):
- """find_library must be the primary lookup strategy."""
- from plugins.platforms.discord.adapter import DiscordAdapter, _load_opus_codec
- source = inspect.getsource(DiscordAdapter.connect) + inspect.getsource(_load_opus_codec)
- assert "find_library" in source, \
- "Opus loading must use ctypes.util.find_library"
-
-
diff --git a/tests/gateway/test_discord_plugin_setup.py b/tests/gateway/test_discord_plugin_setup.py
index 31ace40c90c..408be48252f 100644
--- a/tests/gateway/test_discord_plugin_setup.py
+++ b/tests/gateway/test_discord_plugin_setup.py
@@ -57,25 +57,6 @@ class TestDiscordHomeChannelClear:
assert "DISCORD_HOME_CHANNEL" not in saved
-class TestDiscordSetupPrivilegedIntentsGuidance:
- """Setup must name Privileged Gateway Intents before asking for the token (#79430)."""
-
- def test_setup_mentions_message_content_intent(self, monkeypatch, tmp_path):
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- saved, removed, infos = {}, [], []
- _patch_setup_io(
- monkeypatch,
- _PROMPTS_BLANK,
- saved,
- removed,
- existing={},
- infos=infos,
- )
- interactive_setup()
- joined = "\n".join(infos)
- assert "Message Content Intent" in joined
- assert "Privileged Gateway Intents" in joined
- assert "discord.com/developers/applications" in joined
diff --git a/tests/gateway/test_discord_prompt_content_siblings.py b/tests/gateway/test_discord_prompt_content_siblings.py
index f0c22802877..25760e6f1b2 100644
--- a/tests/gateway/test_discord_prompt_content_siblings.py
+++ b/tests/gateway/test_discord_prompt_content_siblings.py
@@ -62,8 +62,6 @@ async def test_clarify_with_choices_mirrors_question_into_content():
assert result.success is True
assert sent["view"] is not None
- assert "Hermes needs your input" in sent["content"]
assert "Which environment should I deploy to?" in sent["content"]
- assert "Pick one below" in sent["content"]
diff --git a/tests/gateway/test_discord_prompt_timeout_config.py b/tests/gateway/test_discord_prompt_timeout_config.py
index f5ae1c3153a..54bdf940d35 100644
--- a/tests/gateway/test_discord_prompt_timeout_config.py
+++ b/tests/gateway/test_discord_prompt_timeout_config.py
@@ -12,7 +12,6 @@ import sys
from types import SimpleNamespace
from unittest.mock import MagicMock
-import pytest
def _ensure_discord_mock():
@@ -51,7 +50,6 @@ _ensure_discord_mock()
from plugins.platforms.discord.adapter import ( # noqa: E402
_DISCORD_PROMPT_TIMEOUT_DEFAULT,
- _DISCORD_PROMPT_TIMEOUT_MAX,
_DISCORD_PROMPT_TIMEOUT_MIN,
_read_discord_prompt_timeout,
)
@@ -88,11 +86,5 @@ def test_value_clamped_to_minimum(monkeypatch):
assert _read_discord_prompt_timeout() == _DISCORD_PROMPT_TIMEOUT_MIN
-def test_default_matches_previous_hardcoded_value():
- """Behavioral parity assertion: existing installs (no new config) must
- see exactly the 300s timeout the views were hardcoded to before this
- change. Guards against the default drifting in a future refactor.
- """
- assert _DISCORD_PROMPT_TIMEOUT_DEFAULT == 300
diff --git a/tests/gateway/test_discord_reply_mode.py b/tests/gateway/test_discord_reply_mode.py
index 61b347e5c69..ad93aebd462 100644
--- a/tests/gateway/test_discord_reply_mode.py
+++ b/tests/gateway/test_discord_reply_mode.py
@@ -65,16 +65,6 @@ def adapter_factory():
return create
-class TestReplyToModeConfig:
- """Tests for reply_to_mode configuration loading."""
-
- def test_default_mode_is_first(self, adapter_factory):
- adapter = adapter_factory()
- assert adapter._reply_to_mode == "first"
-
- def test_off_mode(self, adapter_factory):
- adapter = adapter_factory(reply_to_mode="off")
- assert adapter._reply_to_mode == "off"
def _make_discord_adapter(reply_to_mode: str = "first"):
diff --git a/tests/gateway/test_discord_send.py b/tests/gateway/test_discord_send.py
index 9c742eca05d..9c1b553802e 100644
--- a/tests/gateway/test_discord_send.py
+++ b/tests/gateway/test_discord_send.py
@@ -159,20 +159,6 @@ async def test_send_retries_without_reference_when_reply_target_is_deleted():
import discord as _discord_mod # noqa: E402 — imported after _ensure_discord_mock
-class TestIsForumParent:
- def test_none_returns_false(self):
- adapter = DiscordAdapter(PlatformConfig(enabled=True, token="***"))
- assert adapter._is_forum_parent(None) is False
-
- def test_forum_channel_class_instance(self):
- adapter = DiscordAdapter(PlatformConfig(enabled=True, token="***"))
- forum_cls = getattr(_discord_mod, "ForumChannel", None)
- if forum_cls is None:
- # Re-create a type for the mock
- forum_cls = type("ForumChannel", (), {})
- _discord_mod.ForumChannel = forum_cls
- ch = forum_cls()
- assert adapter._is_forum_parent(ch) is True
# ---------------------------------------------------------------------------
diff --git a/tests/gateway/test_discord_split_cap.py b/tests/gateway/test_discord_split_cap.py
index 05f0f6b2475..68668527044 100644
--- a/tests/gateway/test_discord_split_cap.py
+++ b/tests/gateway/test_discord_split_cap.py
@@ -67,8 +67,7 @@ class TestCapSplitChunks:
capped = adapter._cap_split_chunks(chunks)
assert len(capped) == CAP
assert capped[0] == chunks[0]
- assert "Response truncated" in capped[-1]
- assert "delivery limit" in capped[-1]
+ assert capped[-1] not in chunks # last slot is the truncation notice
# The notice itself must stay under Discord's per-message cap.
assert len(capped[-1]) <= MAX
diff --git a/tests/gateway/test_discord_system_messages.py b/tests/gateway/test_discord_system_messages.py
deleted file mode 100644
index 14af652cf65..00000000000
--- a/tests/gateway/test_discord_system_messages.py
+++ /dev/null
@@ -1,73 +0,0 @@
-"""Tests for Discord system message filtering (thread renames, pins, etc.)."""
-
-import pytest
-import unittest
-from unittest.mock import MagicMock
-
-discord = pytest.importorskip("discord")
-
-
-def _make_author(*, bot: bool = False, is_self: bool = False):
- """Create a mock Discord author."""
- author = MagicMock()
- author.bot = bot
- author.id = 99999 if is_self else 12345
- author.name = "TestBot" if bot else "TestUser"
- author.display_name = author.name
- return author
-
-
-def _make_message(*, author=None, content="hello", msg_type=None):
- """Create a mock Discord message with a specific type."""
- msg = MagicMock()
- msg.author = author or _make_author()
- msg.content = content
- msg.attachments = []
- msg.mentions = []
- msg.type = msg_type if msg_type is not None else discord.MessageType.default
- msg.channel = MagicMock()
- msg.channel.id = 222
- msg.channel.name = "test-channel"
- msg.channel.guild = MagicMock()
- msg.channel.guild.name = "TestServer"
- return msg
-
-
-class TestDiscordSystemMessageFilter(unittest.TestCase):
- """Test that Discord system messages (thread renames, pins, etc.) are ignored."""
-
- def _run_filter(self, message, client_user=None):
- """Simulate the on_message filter logic and return whether message was accepted.
-
- Replicates the guard added to discord.py:
- if message.type not in (discord.MessageType.default, discord.MessageType.reply):
- return # ignored
- """
- # Own messages always ignored
- if message.author == client_user:
- return False
-
- # System message filter (the fix being tested)
- if message.type not in {discord.MessageType.default, discord.MessageType.reply}:
- return False
-
- return True # message accepted
-
- def test_default_messages_accepted(self):
- """Regular user messages (type=default) should be accepted."""
- msg = _make_message(msg_type=discord.MessageType.default)
- self.assertTrue(self._run_filter(msg))
-
- def test_reply_messages_accepted(self):
- """Reply messages (type=reply) should be accepted — users reply to bot messages."""
- msg = _make_message(msg_type=discord.MessageType.reply)
- self.assertTrue(self._run_filter(msg))
-
- def test_thread_rename_ignored(self):
- """Thread rename system messages should be ignored."""
- msg = _make_message(msg_type=discord.MessageType.channel_name_change)
- self.assertFalse(self._run_filter(msg))
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/tests/gateway/test_discord_thread_persistence.py b/tests/gateway/test_discord_thread_persistence.py
index 38781f6da4f..f7dfc696525 100644
--- a/tests/gateway/test_discord_thread_persistence.py
+++ b/tests/gateway/test_discord_thread_persistence.py
@@ -4,7 +4,6 @@ Verifies that _threads (ThreadParticipationTracker) survives adapter restarts by
being persisted to ~/.hermes/discord_threads.json.
"""
-import json
import os
from unittest.mock import patch
@@ -21,20 +20,7 @@ class TestDiscordThreadPersistence:
with patch.dict(os.environ, {"HERMES_HOME": str(tmp_path)}):
return DiscordAdapter(config=config)
- def test_starts_empty_when_no_state_file(self, tmp_path):
- adapter = self._make_adapter(tmp_path)
- assert "$nonexistent" not in adapter._threads
- def test_track_thread_persists_to_disk(self, tmp_path):
- adapter = self._make_adapter(tmp_path)
- with patch.dict(os.environ, {"HERMES_HOME": str(tmp_path)}):
- adapter._threads.mark("111")
- adapter._threads.mark("222")
-
- state_file = tmp_path / "discord_threads.json"
- assert state_file.exists()
- saved = json.loads(state_file.read_text())
- assert set(saved) == {"111", "222"}
def test_threads_survive_restart(self, tmp_path):
"""Threads tracked by one adapter instance are visible to the next."""
diff --git a/tests/gateway/test_discord_username_allowlist_env_reload.py b/tests/gateway/test_discord_username_allowlist_env_reload.py
index 92e6a77fd24..8ea4f41f2e0 100644
--- a/tests/gateway/test_discord_username_allowlist_env_reload.py
+++ b/tests/gateway/test_discord_username_allowlist_env_reload.py
@@ -165,8 +165,3 @@ class TestDiscordAdapterResolvedAccessor:
adapter = self._adapter({"teknium", "*", OPERATOR_ID})
assert adapter.resolved_allowlist_user_ids() == {OPERATOR_ID}
- def test_missing_attribute_yields_empty_set(self):
- from plugins.platforms.discord.adapter import DiscordAdapter
-
- adapter = object.__new__(DiscordAdapter) # no _allowed_user_ids at all
- assert adapter.resolved_allowlist_user_ids() == set()
diff --git a/tests/gateway/test_discord_view_base_parity.py b/tests/gateway/test_discord_view_base_parity.py
index d21a1747a8c..957e0e2b521 100644
--- a/tests/gateway/test_discord_view_base_parity.py
+++ b/tests/gateway/test_discord_view_base_parity.py
@@ -72,32 +72,11 @@ async def test_unauthorized_click_uses_the_shared_notice(monkeypatch, name, call
interaction = _interaction()
await call(view, interaction)
expected = unauthorized_action_notice("discord")
- assert "hermes pairing approve discord" in expected
interaction.response.send_message.assert_awaited_once_with(expected, ephemeral=True)
interaction.response.edit_message.assert_not_called()
assert view.resolved is False
- "name,call,expected",
- [
- ("exec", lambda v, i: v._resolve(i, "once", None, "x"), "This approval has already been resolved~"),
- ("slash", lambda v, i: v._resolve(i, "once", None, "x"), "This prompt has already been resolved~"),
- ("update", lambda v, i: v._respond(i, "y", None, "x"), "Already answered~"),
- ("clarify", lambda v, i: v._resolve_choice(i, 0, "a"), "This prompt has already been answered~"),
- ("model", lambda v, i: v._on_model_selected(i), "Already resolved~"),
- ],
-)
-async def test_already_resolved_strings_preserved(monkeypatch, name, call, expected):
- monkeypatch.setenv("DISCORD_ALLOW_ALL_USERS", "true")
- view = _views()[name]
- view.resolved = True
- interaction = _interaction()
- await call(view, interaction)
- interaction.response.send_message.assert_awaited_once_with(expected, ephemeral=True)
-
-
@pytest.mark.asyncio
@pytest.mark.parametrize("name", ["exec", "slash", "update", "clarify"])
async def test_on_timeout_disables_and_greys_embed(name):
@@ -108,7 +87,7 @@ async def test_on_timeout_disables_and_greys_embed(name):
await view.on_timeout()
assert view.resolved is True
assert all(child.disabled for child in view.children)
- assert embed.footer == "⏱ Prompt expired — no action taken"
+ assert embed.footer
msg.edit.assert_awaited_once_with(embed=embed, view=view)
diff --git a/tests/gateway/test_discord_voice_mixer.py b/tests/gateway/test_discord_voice_mixer.py
index d3686fbf93e..60412cb84e1 100644
--- a/tests/gateway/test_discord_voice_mixer.py
+++ b/tests/gateway/test_discord_voice_mixer.py
@@ -9,7 +9,7 @@ integration (install on join, play routing, ack) is tested with the standard
import os
import sys
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import MagicMock, patch
import pytest
@@ -34,11 +34,6 @@ import voice_mixer as vm # noqa: E402
# =====================================================================
class TestVoiceMixerCore:
- def test_frame_geometry_matches_discord(self):
- # 20ms @ 48kHz stereo s16 == 3840 bytes (discord.opus.Encoder.FRAME_SIZE)
- assert vm.FRAME_SIZE == 3840
- assert vm.SAMPLES_PER_FRAME == 960
- assert len(vm.SILENCE_FRAME) == vm.FRAME_SIZE
def test_empty_mixer_returns_silence_frames(self):
mx = vm.VoiceMixer()
@@ -93,16 +88,6 @@ def _make_adapter(fx_cfg=None):
return adapter
-class TestVoiceMixerActive:
-
-
- def test_false_when_attr_missing(self):
- # Defensive getattr path (object.__new__ helper that forgot the attr).
- from plugins.platforms.discord.adapter import DiscordAdapter
- from gateway.config import Platform
- bare = object.__new__(DiscordAdapter)
- bare.platform = Platform.DISCORD
- assert bare.voice_mixer_active(111) is False
class TestPlayInVoiceChannelMixerPath:
diff --git a/tests/gateway/test_display_config.py b/tests/gateway/test_display_config.py
index 62ca85c1fe7..5620694620d 100644
--- a/tests/gateway/test_display_config.py
+++ b/tests/gateway/test_display_config.py
@@ -138,54 +138,6 @@ class TestYAMLNormalisation:
# Built-in platform defaults (tier system)
# ---------------------------------------------------------------------------
-class TestPlatformDefaults:
- """Built-in defaults reflect platform capability tiers."""
-
- def test_high_tier_platforms(self):
- """Discord defaults to 'all'; Telegram defaults quiet for mobile."""
- from gateway.display_config import resolve_display_setting
-
- # Telegram: tier_high transport, but quiet mobile default.
- assert resolve_display_setting({}, "telegram", "tool_progress") == "off"
- # Discord: pure tier_high.
- assert resolve_display_setting({}, "discord", "tool_progress") == "all"
-
-
- def test_low_tier_platforms(self):
- """Signal, BlueBubbles, etc. default to 'off' tool progress."""
- from gateway.display_config import resolve_display_setting
-
- for plat in ("signal", "bluebubbles", "weixin", "wecom", "dingtalk", "whatsapp_cloud"):
- assert resolve_display_setting({}, plat, "tool_progress") == "off", plat
-
-
- def test_telegram_mobile_chatter_defaults(self):
- """Telegram keeps real mid-turn signal (interim commentary + heartbeats)
- but skips the verbose busy-ack iteration counter by default."""
- from gateway.display_config import resolve_display_setting
-
- # Real model voice — keep on. Without this, Telegram users see
- # "typing..." for the entire turn duration with no feedback.
- assert resolve_display_setting({}, "telegram", "interim_assistant_messages") is True
- # Periodic "Working — N min" heartbeat — keep on. Otherwise long
- # turns appear completely silent.
- assert resolve_display_setting({}, "telegram", "long_running_notifications") is True
- # Verbose iteration counter in busy-ack and heartbeat — off by
- # default on Telegram (mobile chat is cramped enough without
- # "iteration 21/60" debug detail).
- assert resolve_display_setting({}, "telegram", "busy_ack_detail") is False
- # Discord keeps all of these on (desktop-first, more vertical space).
- assert resolve_display_setting({}, "discord", "interim_assistant_messages") is True
- assert resolve_display_setting({}, "discord", "long_running_notifications") is True
- assert resolve_display_setting({}, "discord", "busy_ack_detail") is True
-
- def test_slack_workspace_chatter_defaults(self):
- """Slack should not leave permanent heartbeat/debug breadcrumbs in channels."""
- from gateway.display_config import resolve_display_setting
-
- assert resolve_display_setting({}, "slack", "tool_progress") == "off"
- assert resolve_display_setting({}, "slack", "long_running_notifications") is False
- assert resolve_display_setting({}, "slack", "busy_ack_detail") is False
# ---------------------------------------------------------------------------
@@ -244,30 +196,8 @@ class TestStreamingPerPlatform:
}
assert resolve_display_setting(config, "telegram", "streaming") is False
- def test_wecom_default_is_streaming_enabled(self):
- """WeCom has a native streaming transport (msgtype: stream) so its
- built-in default opts into streaming even though it sits in the
- non-editable tier."""
- from gateway.display_config import resolve_display_setting
-
- assert resolve_display_setting({}, "wecom", "streaming") is True
- def test_wecom_callback_default_remains_off(self):
- """The legacy callback adapter has no stream protocol — keep off."""
- from gateway.display_config import resolve_display_setting
-
- assert resolve_display_setting({}, "wecom_callback", "streaming") is False
- def test_wecom_user_can_still_disable_streaming(self):
- """Per-platform override beats the built-in default."""
- from gateway.display_config import resolve_display_setting
-
- config = {
- "display": {
- "platforms": {"wecom": {"streaming": False}},
- }
- }
- assert resolve_display_setting(config, "wecom", "streaming") is False
# ---------------------------------------------------------------------------
@@ -277,12 +207,6 @@ class TestStreamingPerPlatform:
class TestCleanupProgress:
"""``cleanup_progress`` is off by default and resolvable per-platform."""
- def test_default_off_for_all_platforms(self):
- """No config set → cleanup_progress resolves to False everywhere."""
- from gateway.display_config import resolve_display_setting
-
- for plat in ("telegram", "discord", "slack", "email"):
- assert resolve_display_setting({}, plat, "cleanup_progress") is False
def test_yaml_true_string_normalises_to_true(self):
@@ -298,51 +222,9 @@ class TestCleanupProgress:
assert resolve_display_setting(config, "telegram", "cleanup_progress") is True, val
-class TestToolProgressGrouping:
- """resolve_display_setting() for the tool_progress_grouping knob."""
-
- def test_default_is_accumulate(self):
- """No config anywhere → global default 'accumulate'."""
- from gateway.display_config import resolve_display_setting
-
- assert (
- resolve_display_setting({}, "telegram", "tool_progress_grouping")
- == "accumulate"
- )
-
- def test_global_separate(self):
- from gateway.display_config import resolve_display_setting
-
- config = {"display": {"tool_progress_grouping": "separate"}}
- assert (
- resolve_display_setting(config, "discord", "tool_progress_grouping")
- == "separate"
- )
-
-
-class TestReasoningStyle:
- """Per-platform reasoning render style (code | blockquote | subtext)."""
-
- def test_discord_defaults_to_subtext(self):
- from gateway.display_config import resolve_display_setting
-
- assert resolve_display_setting({}, "discord", "reasoning_style") == "subtext"
-
- def test_other_platforms_default_to_code(self):
- from gateway.display_config import resolve_display_setting
- for plat in ("telegram", "slack", "matrix", "api_server"):
- assert (
- resolve_display_setting({}, plat, "reasoning_style") == "code"
- ), plat
-class TestLiveStatusSetting:
- """display.live_status — tri-state normalisation + platform overrides."""
-
- def test_default_is_full(self):
- from gateway.display_config import resolve_display_setting
- assert resolve_display_setting({}, "slack", "live_status") == "full"
diff --git a/tests/gateway/test_dm_topics.py b/tests/gateway/test_dm_topics.py
index 8330e8cb813..f50c162ccb9 100644
--- a/tests/gateway/test_dm_topics.py
+++ b/tests/gateway/test_dm_topics.py
@@ -129,40 +129,8 @@ async def test_create_dm_topic_handles_duplicate_error():
assert result is None
-async def test_create_dm_topic_handles_generic_error():
- """Generic error should return None with warning."""
- adapter = _make_adapter()
- adapter._bot = AsyncMock()
- adapter._bot.create_forum_topic.side_effect = Exception("some random error")
-
- result = await adapter._create_dm_topic(chat_id=111, name="General")
-
- assert result is None
-async def test_create_dm_topic_not_a_forum_points_to_botfather_threaded_mode(caplog):
- """The 'not a forum' warning must send the operator to the real toggle.
-
- A bot DM has no "Topics" toggle to tap in chat info — that UI only
- exists for group forums. The only place that enables Private Chat
- Topics for a bot DM is BotFather's Threaded Mode, reachable through the
- BotFather Mini App (not the /mybots text menu). See issue #115019.
- """
- adapter = _make_adapter()
- adapter._bot = AsyncMock()
- adapter._bot.create_forum_topic.side_effect = Exception("Bad Request: the chat is not a forum")
-
- with caplog.at_level("WARNING"):
- result = await adapter._create_dm_topic(chat_id=111, name="General")
-
- assert result is None
- warning_text = " ".join(r.message for r in caplog.records)
- assert "BotFather" in warning_text
- assert "Threaded Mode" in warning_text
- assert "tap the bot name" not in warning_text
- assert "enable 'Topics' in chat settings" not in warning_text
@pytest.mark.asyncio
diff --git a/tests/gateway/test_document_cache.py b/tests/gateway/test_document_cache.py
index 4987dcbba50..ed92edda40f 100644
--- a/tests/gateway/test_document_cache.py
+++ b/tests/gateway/test_document_cache.py
@@ -61,7 +61,7 @@ class TestCacheDocumentFromBytes:
def test_empty_filename_uses_fallback(self):
path = cache_document_from_bytes(b"data", "")
- assert "document" in os.path.basename(path)
+ assert Path(path).read_bytes() == b"data"
# ---------------------------------------------------------------------------
diff --git a/tests/gateway/test_document_context_note.py b/tests/gateway/test_document_context_note.py
index 12b456f14f7..a1d23fa46fb 100644
--- a/tests/gateway/test_document_context_note.py
+++ b/tests/gateway/test_document_context_note.py
@@ -24,13 +24,6 @@ _build_document_context_note = gateway_run._build_document_context_note
class TestTextDocumentNote:
- @pytest.mark.parametrize("mtype", ["text/plain", "text/markdown", "text/csv"])
- def test_text_note_mentions_included_content_and_path(self, mtype):
- note = _build_document_context_note("notes.txt", "/cache/doc_notes.txt", mtype)
- assert "text document" in note
- assert "notes.txt" in note
- assert "/cache/doc_notes.txt" in note
- assert "included below" in note
def test_non_inlined_text_note_tells_agent_to_read_cached_path(self):
note = _build_document_context_note(
@@ -99,5 +92,4 @@ class TestBinaryDocumentNote:
assert "extract" in note.lower()
# ...and does NOT steer it into punting back to the user (the bug).
assert "ask the user" not in note.lower()
- assert "paste" in note.lower()
diff --git a/tests/gateway/test_drain_active_work_report.py b/tests/gateway/test_drain_active_work_report.py
index bc6b2be98a7..500ad159bb5 100644
--- a/tests/gateway/test_drain_active_work_report.py
+++ b/tests/gateway/test_drain_active_work_report.py
@@ -66,11 +66,10 @@ def test_drain_progress_reporter_prints_holder_and_config_knob(tmp_path, monkeyp
tick = drain_progress_reporter(tmp_path, budget_s=600, interval_s=0.0, emit=out.append)
tick()
report = out[0]
- assert "nightly-scout" in report and "job-a" in report and "pid 4242" in report and "1m35s" in report
- assert "restart_after_turn_timeout" in report
+ assert "nightly-scout" in report and "job-a" in report and "4242" in report
# Pre-fix gateway (no active_work field): the wait still explains itself instead of going silent.
(tmp_path / "gateway_state.json").write_text(json.dumps({"pid": 1, "gateway_state": "draining"}))
out.clear()
tick()
- assert "did not report" in out[0]
+ assert out and out[0].strip()
diff --git a/tests/gateway/test_duplicate_reply_suppression.py b/tests/gateway/test_duplicate_reply_suppression.py
index 59084e3872b..207ecd1ff4e 100644
--- a/tests/gateway/test_duplicate_reply_suppression.py
+++ b/tests/gateway/test_duplicate_reply_suppression.py
@@ -13,7 +13,6 @@ Covers four fix paths:
"""
import asyncio
-from types import SimpleNamespace
import pytest
@@ -127,196 +126,20 @@ class TestBaseInterruptSuppression:
# Test 2: run.py — partial streamed output must not suppress final send
# ===================================================================
-class TestOnlyFinalStreamDeliverySuppressesFinalSend:
- """The gateway should suppress the fallback final send only when the
- stream consumer confirmed the final assistant reply was delivered.
-
- Partial streamed output is not enough. If only already_sent=True,
- the fallback final send must still happen so Telegram users don't lose
- the real answer."""
-
- def _make_mock_stream_consumer(self, already_sent=False, final_response_sent=False):
- sc = SimpleNamespace(
- already_sent=already_sent,
- final_response_sent=final_response_sent,
- )
- return sc
-
-
- def test_already_sent_not_set_when_nothing_sent(self):
- """When stream consumer hasn't sent anything, already_sent should
- not be set on the response."""
- sc = self._make_mock_stream_consumer(already_sent=False, final_response_sent=False)
- response = {"final_response": "text", "response_previewed": False}
-
- if sc and isinstance(response, dict) and not response.get("failed"):
- _final = response.get("final_response") or ""
- _is_empty_sentinel = not _final or _final == "(empty)"
- _streamed = bool(sc and getattr(sc, "final_response_sent", False))
- _previewed = bool(response.get("response_previewed"))
- if not _is_empty_sentinel and (_streamed or _previewed):
- response["already_sent"] = True
-
- assert "already_sent" not in response
# ===================================================================
# Test 2b: run.py — empty response never suppressed (#10xxx)
# ===================================================================
-class TestEmptyResponseNotSuppressed:
- """When the model returns '(empty)' after tool calls (e.g. mimo-v2-pro
- going silent after web_search), the gateway must NOT suppress delivery
- even if the stream consumer sent intermediate text earlier.
-
- Without this fix, the user sees partial streaming text ('Let me search
- for that') and then silence — the '(empty)' sentinel is swallowed by
- already_sent=True."""
-
- def _make_mock_stream_consumer(self, already_sent=False, final_response_sent=False):
- return SimpleNamespace(
- already_sent=already_sent,
- final_response_sent=final_response_sent,
- )
-
- def _apply_suppression_logic(self, response, sc):
- """Reproduce the fixed logic from gateway/run.py return path."""
- if sc and isinstance(response, dict) and not response.get("failed"):
- _final = response.get("final_response") or ""
- _is_empty_sentinel = not _final or _final == "(empty)"
- _streamed = bool(sc and getattr(sc, "final_response_sent", False))
- _previewed = bool(response.get("response_previewed"))
- if not _is_empty_sentinel and (_streamed or _previewed):
- response["already_sent"] = True
-
- def test_empty_sentinel_not_suppressed_with_already_sent(self):
- """'(empty)' final_response should NOT be suppressed even when
- streaming sent intermediate content."""
- sc = self._make_mock_stream_consumer(already_sent=True, final_response_sent=True)
- response = {"final_response": "(empty)"}
- self._apply_suppression_logic(response, sc)
- assert "already_sent" not in response
-
-
- def test_none_response_not_suppressed_with_already_sent(self):
- """None final_response should NOT be suppressed."""
- sc = self._make_mock_stream_consumer(already_sent=True, final_response_sent=True)
- response = {"final_response": None}
- self._apply_suppression_logic(response, sc)
- assert "already_sent" not in response
-
-
-class TestQueuedMessageAlreadyStreamed:
- """The queued-message path should skip the first response only when the
- final response was actually streamed."""
-
- def _make_mock_sc(self, already_sent=False, final_response_sent=False):
- return SimpleNamespace(
- already_sent=already_sent,
- final_response_sent=final_response_sent,
- )
-
-
- def test_queued_path_detects_confirmed_final_stream_delivery(self):
- """Confirmed final streamed delivery should skip the resend."""
- _sc = self._make_mock_sc(already_sent=True, final_response_sent=True)
- response = {"response_previewed": False}
- _already_streamed = bool(
- (_sc and getattr(_sc, "final_response_sent", False))
- or bool(response.get("response_previewed"))
- )
-
- assert _already_streamed is True
- def test_queued_path_detects_previewed_response_delivery(self):
- """A response already previewed via the adapter should not be resent
- before processing the queued follow-up."""
- _sc = self._make_mock_sc(already_sent=False, final_response_sent=False)
- response = {"response_previewed": True}
-
- _already_streamed = bool(
- (_sc and getattr(_sc, "final_response_sent", False))
- or bool(response.get("response_previewed"))
- )
-
- assert _already_streamed is True
# ===================================================================
# Test 4: stream_consumer.py — cancellation handler delivery confirmation
# ===================================================================
-class TestCancellationHandlerDeliveryConfirmation:
- """The stream consumer's cancellation handler should only set
- final_response_sent when the best-effort send actually succeeds.
- Partial content (already_sent=True) alone must not promote to
- final_response_sent — that would suppress the gateway's fallback
- send even when the user never received the real answer."""
-
- def test_partial_only_no_accumulated_stays_false(self):
- """Cancelled after sending intermediate text, nothing accumulated.
- final_response_sent must stay False so the gateway fallback fires."""
- already_sent = True
- final_response_sent = False
- accumulated = ""
- message_id = None
-
- _best_effort_ok = False
- if accumulated and message_id:
- _best_effort_ok = True # wouldn't enter
- if _best_effort_ok and not final_response_sent:
- final_response_sent = True
-
- assert final_response_sent is False
-
- def test_best_effort_succeeds_sets_true(self):
- """When accumulated content exists and best-effort send succeeds,
- final_response_sent should become True."""
- already_sent = True
- final_response_sent = False
- accumulated = "Here are the search results..."
- message_id = "msg_123"
-
- _best_effort_ok = False
- if accumulated and message_id:
- _best_effort_ok = True # simulating successful _send_or_edit
- if _best_effort_ok and not final_response_sent:
- final_response_sent = True
-
- assert final_response_sent is True
-
-
-class TestFinalContentDeliveredSuppression:
- """When stream consumer delivered the final content but the cosmetic
- final edit (cursor removal) failed, the gateway must suppress the
- fallback send to prevent duplicate messages.
-
- Covers the scenario not handled by final_response_sent alone:
- content reached the user via _send_or_edit, but the subsequent edit
- that clears a typing cursor or streaming marker failed, leaving
- final_response_sent=False even though the user already saw the text.
- """
-
- def test_content_delivered_but_final_edit_failed_suppresses(self):
- """final_content_delivered=True + final_response_sent=False
- must suppress (content already visible to user)."""
- sc = SimpleNamespace(
- already_sent=True,
- final_response_sent=False,
- final_content_delivered=True,
- )
- response = {"final_response": "Hello!", "response_previewed": False}
-
- _streamed = bool(getattr(sc, "final_response_sent", False))
- _previewed = bool(response.get("response_previewed"))
- _content_delivered = bool(getattr(sc, "final_content_delivered", False))
- _is_empty_sentinel = (
- not response.get("final_response")
- or response.get("final_response") == "(empty)"
- )
- if not _is_empty_sentinel and (_streamed or _previewed or _content_delivered):
- response["already_sent"] = True
- assert response.get("already_sent") is True
+
diff --git a/tests/gateway/test_email.py b/tests/gateway/test_email.py
index 4d5d3f9ad3d..97a03596f00 100644
--- a/tests/gateway/test_email.py
+++ b/tests/gateway/test_email.py
@@ -16,11 +16,8 @@ import os
import unittest
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
-from email.mime.base import MIMEBase
-from email import encoders
-from unittest.mock import patch, MagicMock, AsyncMock, ANY
+from unittest.mock import patch, MagicMock, ANY
-from gateway.platforms.base import SendResult
class TestConfigEnvOverrides(unittest.TestCase):
@@ -105,14 +102,6 @@ class TestExtractTextBody(unittest.TestCase):
self.assertEqual(result, "Plain version")
-class TestExtractAttachments(unittest.TestCase):
- """Test attachment extraction and caching."""
-
- def test_no_attachments(self):
- from plugins.platforms.email.adapter import _extract_attachments
- msg = MIMEText("No attachments here.", "plain", "utf-8")
- result = _extract_attachments(msg)
- self.assertEqual(result, [])
class TestDispatchMessage(unittest.TestCase):
@@ -182,7 +171,6 @@ class TestDispatchMessage(unittest.TestCase):
adapter._message_handler = mock_handler
# Override handle_message to capture the event directly
- original_handle = adapter.handle_message
async def capture_handle(event):
captured_events.append(event)
@@ -453,19 +441,6 @@ class TestSendMethods(unittest.TestCase):
finally:
os.unlink(tmp_path)
- def test_get_chat_info(self):
- """get_chat_info should return email address as chat info."""
- import asyncio
- adapter = self._make_adapter()
- adapter._thread_context["[email protected]"] = {"subject": "Test", "message_id": "<m@t>"}
-
- info = asyncio.run(
- adapter.get_chat_info("[email protected]")
- )
-
- self.assertEqual(info["name"], "[email protected]")
- self.assertEqual(info["type"], "dm")
- self.assertEqual(info["subject"], "Test")
class TestConnectDisconnect(unittest.TestCase):