mirror of
https://github.com/NousResearch/hermes-agent.git
synced 2026-07-31 19:16:29 +00:00
Second, deeper pass over tools/gateway/hermes_cli plus first pass over the trees wave 1 missed (acp, acp_adapter, skills, computer_use, docker, dashboard, conformance, monitoring, secret_sources, hermes_state, providers). Same rubric as wave 1 (AGENTS.md test policy); security, alternation/caching invariants, issue-number regressions, and E2E kept. Real test-quality fixes found and rooted out along the way: - tests/tools/test_command_guards.py made real auxiliary-LLM HTTPS calls (DEFAULT_CONFIG smart-approval leaked in) — pinned approval mode=manual via autouse fixture: 17.4s → 0.4s. - test_model_switch_custom_providers.py / test_user_providers_model_switch.py silently probed live provider catalogs (~2s/test) — stubbed cached_provider_model_ids/provider_model_ids/fetch_api_models. - test_telegram_noise_filter.py: 15-platform copy-paste matrix over shared gateway.run logic → 3 representative platforms (55s → 3.9s). - test_gateway_shutdown.py: stop()'s 5s interrupt-deadline loop spun on MagicMock agents — interrupt.side_effect now clears _running_agents (22s → 1.0s). - test_gateway_inactivity_timeout.py poll-harness timings shrunk 3-5x (24s → 1.1s); test_mcp_stability.py backoff/SIGTERM-grace sleeps patched (15.4s → 2.5s); test_async_delegation.py negative-drain wait 5s → 0.5s. - test_telegram_init_deadline.py: loop-block margin restored to 1.0s with rationale comment — the watchdog-dump assertion needs the loop blocked well past deadline+grace under parallel load (flaked once in the 40-worker verification run at a 0.2s margin). Verification: full hermetic suite via scripts/run_tests.sh — 2,438 files, 21,718 tests passed, 0 failed, 293.9s wall. Suite totals vs original baseline: 46,820 → 19,757 test functions (−57.8%), wall 583.5s → 293.9s (−50%), subprocess CPU 13,564s → 11,623s.
127 lines
3.8 KiB
Python
127 lines
3.8 KiB
Python
"""Tests for gateway/wake.py — background wake delivery.
|
|
|
|
Two strategies:
|
|
* push-capable adapters keep the synthetic MessageEvent / handle_message path;
|
|
* the stateless API server (supports_async_delivery=False) self-POSTs
|
|
/v1/chat/completions with the RAW session id in X-Hermes-Session-Id, so the
|
|
wake turn resumes the REAL session instead of a parallel invisible one
|
|
keyed by build_session_key().
|
|
"""
|
|
|
|
import asyncio
|
|
|
|
import pytest
|
|
|
|
from gateway.config import Platform
|
|
from gateway.session import SessionSource
|
|
from gateway.wake import deliver_wake, adapter_supports_push
|
|
|
|
|
|
class PushAdapter:
|
|
"""Default adapter shape — no supports_async_delivery attribute."""
|
|
|
|
def __init__(self):
|
|
self.handled = []
|
|
|
|
async def handle_message(self, event):
|
|
self.handled.append(event)
|
|
|
|
|
|
class ApiServerLikeAdapter:
|
|
supports_async_delivery = False
|
|
|
|
def __init__(self, host="0.0.0.0", port=0, key="test-key", model="hermes"):
|
|
self._host = host
|
|
self._port = port
|
|
self._api_key = key
|
|
self._model_name = model
|
|
|
|
async def handle_message(self, event): # pragma: no cover — must NOT be hit
|
|
raise AssertionError("non-push adapter must not receive handle_message wakes")
|
|
|
|
|
|
def _source():
|
|
return SessionSource(
|
|
platform=Platform.TELEGRAM,
|
|
chat_id="chat-1",
|
|
chat_type="group",
|
|
)
|
|
|
|
|
|
def test_adapter_supports_push_default_true():
|
|
assert adapter_supports_push(PushAdapter()) is True
|
|
assert adapter_supports_push(ApiServerLikeAdapter()) is False
|
|
|
|
|
|
async def _serve(handler):
|
|
"""Spin an in-process aiohttp server on an ephemeral loopback port."""
|
|
from aiohttp import web
|
|
|
|
app = web.Application()
|
|
app.router.add_post("/v1/chat/completions", handler)
|
|
runner = web.AppRunner(app)
|
|
await runner.setup()
|
|
site = web.TCPSite(runner, "127.0.0.1", 0)
|
|
await site.start()
|
|
port = site._server.sockets[0].getsockname()[1]
|
|
return runner, port
|
|
|
|
|
|
def test_deliver_wake_non_push_self_posts_raw_session_id(monkeypatch):
|
|
"""The self-post carries the RAW session id header + bearer auth and a
|
|
single user message with stream=false — the exact entry point real
|
|
gateway turns use."""
|
|
from aiohttp import web
|
|
|
|
seen = {}
|
|
|
|
async def handler(request):
|
|
seen["session_id"] = request.headers.get("X-Hermes-Session-Id")
|
|
seen["auth"] = request.headers.get("Authorization")
|
|
seen["body"] = await request.json()
|
|
return web.json_response({"choices": [{"message": {"content": "ok"}}]})
|
|
|
|
async def run():
|
|
runner, port = await _serve(handler)
|
|
try:
|
|
adapter = ApiServerLikeAdapter(host="0.0.0.0", port=port, key="sekrit")
|
|
await deliver_wake(adapter, text="task done — wake", session_id="raw-sid-42")
|
|
finally:
|
|
await runner.cleanup()
|
|
|
|
asyncio.run(run())
|
|
assert seen["session_id"] == "raw-sid-42"
|
|
assert seen["auth"] == "Bearer sekrit"
|
|
assert seen["body"]["stream"] is False
|
|
assert seen["body"]["messages"] == [
|
|
{"role": "user", "content": "task done — wake"}
|
|
]
|
|
|
|
|
|
def test_deliver_wake_retries_429_then_succeeds(monkeypatch):
|
|
"""HTTP 429 (max_concurrent_runs cap) is transient — retried with backoff."""
|
|
from aiohttp import web
|
|
|
|
import gateway.wake as wake_mod
|
|
|
|
monkeypatch.setattr(wake_mod, "_RETRY_DELAYS_SECONDS", (0.01, 0.01, 0.01))
|
|
calls = {"n": 0}
|
|
|
|
async def handler(request):
|
|
calls["n"] += 1
|
|
if calls["n"] == 1:
|
|
return web.json_response({"error": "busy"}, status=429)
|
|
return web.json_response({"choices": []})
|
|
|
|
async def run():
|
|
runner, port = await _serve(handler)
|
|
try:
|
|
adapter = ApiServerLikeAdapter(port=port)
|
|
await deliver_wake(adapter, text="x", session_id="sid")
|
|
finally:
|
|
await runner.cleanup()
|
|
|
|
asyncio.run(run())
|
|
assert calls["n"] == 2
|
|
|
|
|