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.
192 lines
7 KiB
Python
192 lines
7 KiB
Python
"""Regression test for the "@" context-reference-expansion block in
|
|
``GatewayRunner._prepare_inbound_message_text``.
|
|
|
|
Bug: the block read ``self._model`` / ``self._base_url`` to resolve the
|
|
model/base_url for ``get_model_context_length_async``. ``GatewayRunner``
|
|
never assigns either attribute (that pattern was copy-pasted from
|
|
``HermesCLI``, which does carry ``self.model``/``self.base_url`` — see
|
|
commit da44c196b). Every message containing "@" raised ``AttributeError``
|
|
inside the ``try`` block, which the surrounding ``except Exception`` silently
|
|
swallowed at debug level, so ``preprocess_context_references_async`` never
|
|
ran in the gateway and @-references (``@file:``, ``@folder:``, ``@diff``,
|
|
etc.) passed through to the model completely unexpanded.
|
|
|
|
These tests pin the fix: the block must resolve model/provider/base_url via
|
|
``self._resolve_session_agent_runtime`` (the same session-aware resolution
|
|
the hygiene-compression block already uses) and must actually reach
|
|
``preprocess_context_references_async`` with a real context length.
|
|
"""
|
|
import logging
|
|
import threading
|
|
from contextlib import contextmanager
|
|
|
|
import pytest
|
|
|
|
import gateway.run as gateway_run
|
|
from agent.context_references import ContextReferenceResult
|
|
from gateway.config import GatewayConfig, Platform, PlatformConfig
|
|
from gateway.platforms.base import MessageEvent
|
|
from gateway.run import GatewayRunner
|
|
from gateway.session import SessionSource
|
|
|
|
|
|
def _make_runner() -> GatewayRunner:
|
|
runner = object.__new__(GatewayRunner)
|
|
runner.config = GatewayConfig(
|
|
platforms={Platform.TELEGRAM: PlatformConfig(enabled=True, token="fake")},
|
|
)
|
|
runner.adapters = {}
|
|
# Attrs touched by _resolve_session_agent_runtime on a bare test runner
|
|
# (mirrors tests/gateway/test_empty_model_recovery.py).
|
|
runner._session_model_overrides = {}
|
|
runner._last_resolved_model = {}
|
|
runner._service_tier = None
|
|
runner._agent_cache = {}
|
|
runner._agent_cache_lock = threading.Lock()
|
|
return runner
|
|
|
|
|
|
def _source() -> SessionSource:
|
|
return SessionSource(
|
|
platform=Platform.TELEGRAM,
|
|
chat_id="123",
|
|
chat_name="DM",
|
|
chat_type="private",
|
|
user_name="Alice",
|
|
)
|
|
|
|
|
|
def _patch_runtime_resolution(monkeypatch) -> None:
|
|
"""Stub the module-level runtime resolution so the test never hits the
|
|
network — mirrors _patch_resolution() in test_empty_model_recovery.py."""
|
|
monkeypatch.setattr(
|
|
gateway_run, "_resolve_gateway_model", lambda cfg=None: "openai/gpt-4.1-mini"
|
|
)
|
|
monkeypatch.setattr(
|
|
gateway_run,
|
|
"_resolve_runtime_agent_kwargs",
|
|
lambda: {
|
|
"provider": "openai",
|
|
"api_key": "test-key",
|
|
"base_url": "https://api.openai.com/v1",
|
|
"api_mode": "chat_completions",
|
|
},
|
|
)
|
|
# config_context_length is int > 0, so get_model_context_length_async's
|
|
# config-override short-circuit (agent/model_metadata.py) fires and
|
|
# returns it directly — no network probe needed.
|
|
monkeypatch.setattr(
|
|
gateway_run,
|
|
"_load_gateway_config",
|
|
lambda: {"model": {"default": "openai/gpt-4.1-mini", "context_length": 128000}},
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_at_reference_reaches_preprocessor_with_real_context_length(
|
|
monkeypatch, caplog
|
|
):
|
|
"""A message containing "@" must reach preprocess_context_references_async
|
|
with a real (int > 0) context_length, and the except branch must not
|
|
fire. This fails on unfixed code with AttributeError:
|
|
'GatewayRunner' object has no attribute '_model' (swallowed as a debug
|
|
log, so pre-fix this assertion sees no expansion and no captured call)."""
|
|
runner = _make_runner()
|
|
source = _source()
|
|
_patch_runtime_resolution(monkeypatch)
|
|
|
|
captured: dict = {}
|
|
|
|
async def _fake_preprocess(message, *, cwd, context_length, url_fetcher=None, allowed_root=None):
|
|
captured["message"] = message
|
|
captured["cwd"] = cwd
|
|
captured["context_length"] = context_length
|
|
captured["allowed_root"] = allowed_root
|
|
return ContextReferenceResult(
|
|
message="[expanded body]",
|
|
original_message=message,
|
|
expanded=True,
|
|
)
|
|
|
|
import agent.context_references as ctx_mod
|
|
|
|
monkeypatch.setattr(ctx_mod, "preprocess_context_references_async", _fake_preprocess)
|
|
|
|
caplog.set_level(logging.DEBUG, logger="gateway.run")
|
|
|
|
event = MessageEvent(text="please look at @file:notes.txt", source=source)
|
|
|
|
result = await runner._prepare_inbound_message_text(
|
|
event=event,
|
|
source=source,
|
|
history=[],
|
|
)
|
|
|
|
# The except branch (AttributeError on self._model/self._base_url,
|
|
# pre-fix) must not have fired.
|
|
assert not any(
|
|
"@ context reference expansion failed" in record.getMessage()
|
|
for record in caplog.records
|
|
), "the except branch swallowed an exception instead of reaching the preprocessor"
|
|
|
|
# preprocess_context_references_async must actually have been called,
|
|
# with a real positive context length (not skipped by the AttributeError).
|
|
assert captured, "preprocess_context_references_async was never called"
|
|
assert isinstance(captured["context_length"], int)
|
|
assert captured["context_length"] > 0
|
|
assert captured["context_length"] == 128000
|
|
|
|
# The expanded result from the (stubbed) preprocessor must have been
|
|
# adopted as the final message text.
|
|
assert result == "[expanded body]"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_at_reference_ignores_global_context_for_runtime_route_override(monkeypatch):
|
|
"""Context expansion must not inherit a global pin from another route."""
|
|
runner = _make_runner()
|
|
source = _source()
|
|
captured = {}
|
|
|
|
monkeypatch.setattr(
|
|
gateway_run,
|
|
"_load_gateway_config",
|
|
lambda: {
|
|
"model": {
|
|
"default": "shared-model",
|
|
"provider": "custom",
|
|
"base_url": "https://large.example/v1",
|
|
"context_length": 1_048_576,
|
|
}
|
|
},
|
|
)
|
|
monkeypatch.setattr(
|
|
runner,
|
|
"_resolve_session_agent_runtime",
|
|
lambda **_kwargs: (
|
|
"shared-model",
|
|
{
|
|
"provider": "custom",
|
|
"api_key": "test",
|
|
"base_url": "https://small.example/v1",
|
|
},
|
|
),
|
|
)
|
|
|
|
import agent.context_references as ctx_mod
|
|
import agent.model_metadata as model_meta_mod
|
|
|
|
async def _fake_get_context(_model, **kwargs):
|
|
captured["config_context_length"] = kwargs["config_context_length"]
|
|
return 32_768
|
|
|
|
async def _passthrough(message, **_kwargs):
|
|
return ContextReferenceResult(message=message, original_message=message)
|
|
|
|
monkeypatch.setattr(model_meta_mod, "get_model_context_length_async", _fake_get_context)
|
|
monkeypatch.setattr(ctx_mod, "preprocess_context_references_async", _passthrough)
|
|
|
|
await runner._prepare_inbound_message_text(
|
|
event=MessageEvent(text="@file:note", source=source), source=source, history=[]
|
|
)
|
|
assert captured["config_context_length"] is None
|