hermes-agent/tests/hermes_cli/test_session_handoff.py
Teknium 39975613b1
test: prune wave 2 + speed fixes — 28,106 → 19,757 test functions, suite wall 315s → 294s
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.
2026-07-29 13:39:40 -07:00

127 lines
4.2 KiB
Python

"""Tests for session handoff (CLI to gateway platform).
The handoff state machine lives on the ``sessions`` table:
None → "pending""running" → ("completed" | "failed")
CLI side calls ``request_handoff`` and poll-waits on ``get_handoff_state``.
Gateway side iterates ``list_pending_handoffs``, calls ``claim_handoff`` to
flip pending → running, and finishes with ``complete_handoff`` or
``fail_handoff``.
"""
from __future__ import annotations
import time
import pytest
from hermes_state import SessionDB
class TestHandoffStateDB:
"""Test the handoff schema + helper methods on SessionDB."""
@pytest.fixture
def db(self, tmp_path, monkeypatch):
home = tmp_path / ".hermes"
home.mkdir()
monkeypatch.setenv("HERMES_HOME", str(home))
return SessionDB(db_path=home / "state.db")
def _make_session(self, db, session_id, source="cli", title=None):
"""Insert a session row directly for testing."""
def _do(conn):
conn.execute(
"INSERT OR IGNORE INTO sessions (id, source, title, started_at) "
"VALUES (?, ?, ?, ?)",
(session_id, source, title, time.time()),
)
db._execute_write(_do)
def test_list_pending_handoffs_excludes_running_and_terminal(self, db):
a, b, c, d = "sess-a", "sess-b", "sess-c", "sess-d"
for sid in (a, b, c, d):
self._make_session(db, sid)
db.request_handoff(a, "telegram")
db.request_handoff(b, "discord")
db.request_handoff(c, "telegram")
db.claim_handoff(c) # c is now running, not pending
db.request_handoff(d, "slack")
db.claim_handoff(d)
db.complete_handoff(d) # d is terminal
pending = db.list_pending_handoffs()
ids = [r["id"] for r in pending]
assert set(ids) == {a, b}
def test_complete_handoff_clears_error(self, db):
sid = "sess-complete"
self._make_session(db, sid)
db.request_handoff(sid, "telegram")
db.claim_handoff(sid)
db.fail_handoff(sid, "transient")
# User retries; mock the watcher path
db.request_handoff(sid, "telegram")
db.claim_handoff(sid)
db.complete_handoff(sid)
state = db.get_handoff_state(sid)
assert state["state"] == "completed"
assert state["error"] is None
def test_full_pending_to_completed_flow(self, db):
"""End-to-end sequence the CLI + gateway watcher follow."""
sid = "sess-flow"
self._make_session(db, sid, title="my session")
db.append_message(sid, "user", "Hello")
db.append_message(sid, "assistant", "Hi there!")
# CLI: request handoff
assert db.request_handoff(sid, "telegram") is True
assert db.get_handoff_state(sid)["state"] == "pending"
# Gateway watcher: discover + claim
pending = db.list_pending_handoffs()
assert len(pending) == 1
assert pending[0]["id"] == sid
assert db.claim_handoff(sid) is True
assert db.get_handoff_state(sid)["state"] == "running"
# Gateway uses get_messages to load the transcript (real flow uses
# session_store.switch_session which reads the same table).
messages = db.get_messages(sid)
assert [m["role"] for m in messages] == ["user", "assistant"]
# Gateway: mark completed
db.complete_handoff(sid)
assert db.get_handoff_state(sid)["state"] == "completed"
assert db.list_pending_handoffs() == []
class TestHandoffCommandRegistration:
"""Slash-command surface checks."""
def test_command_registered(self):
from hermes_cli.commands import resolve_command
cmd = resolve_command("handoff")
assert cmd is not None
assert cmd.name == "handoff"
assert cmd.category == "Session"
def test_command_is_cli_only(self):
"""`/handoff` is initiated from the CLI; gateway shouldn't expose it."""
from hermes_cli.commands import resolve_command, GATEWAY_KNOWN_COMMANDS
cmd = resolve_command("handoff")
assert cmd is not None
assert cmd.cli_only is True
assert "handoff" not in GATEWAY_KNOWN_COMMANDS