hermes-agent/tests/hermes_cli/test_resolve_last_session.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

135 lines
4.8 KiB
Python

"""Verify `hermes -c` picks the session the user most recently used."""
from __future__ import annotations
from hermes_cli.main import _resolve_last_session
class _FakeDB:
def __init__(self, rows):
self._rows = rows
self.closed = False
def search_sessions(self, source=None, limit=20, **_kw):
rows = [r for r in self._rows if r.get("source") == source] if source else list(self._rows)
rows.sort(
key=lambda r: float(r.get("last_active") or r.get("started_at") or 0),
reverse=True,
)
return rows[:limit]
def close(self):
self.closed = True
def test_search_sessions_exposes_last_active_column(tmp_path, monkeypatch):
# End-to-end: SessionDB must surface last_active and order by MRU.
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
import hermes_state
from pathlib import Path
db = hermes_state.SessionDB(db_path=Path(tmp_path / "state.db"))
try:
db.create_session("s_started_later", source="cli")
db.create_session("s_active_later", source="cli")
# Force started_at ordering so the test is deterministic regardless
# of how quickly the two inserts land.
with db._lock:
db._conn.execute("UPDATE sessions SET started_at=? WHERE id=?", (2000.0, "s_started_later"))
db._conn.execute("UPDATE sessions SET started_at=? WHERE id=?", (1000.0, "s_active_later"))
db._conn.commit()
db.append_message("s_active_later", role="user", content="hi")
with db._lock:
db._conn.execute(
"UPDATE messages SET timestamp=? WHERE session_id=?",
(3000.0, "s_active_later"),
)
db._conn.commit()
rows = db.search_sessions(source="cli", limit=5)
ids = {r["id"]: r.get("last_active") for r in rows}
assert ids["s_started_later"] == 2000.0
assert ids["s_active_later"] == 3000.0
assert rows[0]["id"] == "s_active_later"
finally:
db.close()
# ---------------------------------------------------------------------------
# cwd-scoped resume: -c prefers the last session in the current workspace.
# ---------------------------------------------------------------------------
class _WorkspaceAwareDB:
"""Fake SessionDB whose ``search_sessions`` honors ``workspace_key`` the
same way the real ``_workspace_key_clause`` does: a row matches the key
when its ``git_repo_root`` equals it, or (no repo root recorded) when its
``cwd`` is at or under it."""
def __init__(self, rows):
self._rows = rows
self.closed = False
def search_sessions(self, source=None, limit=20, workspace_key=None, **_kw):
rows = [r for r in self._rows if r.get("source") == source] if source else list(self._rows)
if workspace_key:
key = workspace_key.rstrip("/")
def _in_ws(r):
grr = (r.get("git_repo_root") or "").rstrip("/")
if grr:
return grr == key
cwd = (r.get("cwd") or "").rstrip("/")
return cwd == key or cwd.startswith(key + "/")
rows = [r for r in rows if _in_ws(r)]
rows.sort(
key=lambda r: float(r.get("last_active") or r.get("started_at") or 0),
reverse=True,
)
return rows[:limit]
def close(self):
self.closed = True
def test_resolve_last_session_real_db_prefers_workspace(monkeypatch, tmp_path):
# End-to-end through the real SessionDB + _resolve_last_session: -c from
# repo A picks repo A's session even though repo B is globally newer.
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
import hermes_state
from pathlib import Path
repo_a = tmp_path / "repo-a"
repo_a.mkdir()
state_db = Path(tmp_path / "state.db")
real_db = hermes_state.SessionDB
db = real_db(db_path=state_db)
try:
db.create_session("repo_a", source="cli", cwd=str(repo_a), git_repo_root=str(repo_a))
db.create_session("repo_b", source="cli", cwd="/other/repo-b", git_repo_root="/other/repo-b")
with db._lock:
db._conn.execute("UPDATE sessions SET started_at=? WHERE id=?", (100.0, "repo_a"))
db._conn.execute("UPDATE sessions SET started_at=? WHERE id=?", (9000.0, "repo_b"))
db._conn.commit()
finally:
db.close()
monkeypatch.chdir(repo_a)
monkeypatch.setattr(
"hermes_cli.main.subprocess.run",
lambda cmd, **kw: __import__("subprocess").CompletedProcess(
cmd, 0, stdout=str(repo_a), stderr=""
),
)
monkeypatch.setattr("hermes_state.SessionDB", lambda: real_db(db_path=state_db))
assert _resolve_last_session("cli") == "repo_a"