The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): slow /handoff transfers no longer misreported as "gateway not running"
Tekniume05c91ac7161
diff --git a/hermes_cli/cli_commands_mixin.py b/hermes_cli/cli_commands_mixin.pyindex 1fe22230905..833317d17f2 100644--- a/hermes_cli/cli_commands_mixin.py+++ b/hermes_cli/cli_commands_mixin.py@@ -844,11 +844,14 @@ class CLICommandsMixin:2. Reject if the agent is currently running (the in-flight turnwould race with the gateway's switch_session).3. Write ``handoff_state='pending'`` on this session row.- 4. Block-poll ``state.db`` for terminal state (timeout 60s).+ 4. Block-poll ``state.db``: 60s for the gateway to CLAIM the row+ (pending), then up to 15 min for the claimed dispatch to reach a+ terminal state (running → completed/failed) with heartbeats.5. On ``completed`` → print resume hint and signal CLI exit byreturning False (the caller honors that like ``/quit``).- 6. On ``failed`` / timeout → print error and return True so the- user keeps their CLI session.+ 6. On ``failed`` / pending-timeout → print error and return True so+ the user keeps their CLI session. A running-timeout leaves the+ row untouched (the gateway owns it) and returns True.Returns:False to signal CLI exit, True to keep going.@@ -967,11 +970,34 @@ class CLICommandsMixin:_cprint(f" Queued handoff of '{session_title}' → {platform_name} (home: {home.name}).")_cprint(" Waiting for the gateway to pick it up...")- # Poll-block on terminal state. Tick every 0.5s; bail at ~60s.+ # Two-phase poll, tick every 0.5s.+ #+ # PENDING (nobody claimed the row): 60s deadline. A timeout here+ # genuinely means no gateway watcher is looking at this state.db —+ # "Is `hermes gateway` running?" is the correct diagnosis, and the+ # CAS fail (only_states=("pending",)) can't stomp a claim that lands+ # in the same instant.+ #+ # RUNNING (gateway claimed it): the gateway owns the row and is+ # replaying the full transcript through a synthetic agent turn —+ # routinely slower than 60s on long sessions with reasoning models.+ # Timing out here and failing the row is the bug this replaces: the+ # CLI printed "Is `hermes gateway` running?" while the gateway was+ # mid-delivery, then the watcher overwrote failed → completed+ # (split-brain; the session HAD been switched under the CLI). So in+ # this phase we wait with a much longer bound and a periodic+ # heartbeat, and on timeout we do NOT touch the row — the gateway+ # reaches its own terminal state (or the next gateway startup+ # reclaims a stranded 'running' row).import time as _time- deadline = _time.time() + 60.0+ _PENDING_TIMEOUT = 60.0+ _RUNNING_TIMEOUT = 900.0 # full synthetic agent turn + delivery+ _HEARTBEAT_EVERY = 30.0+ pending_deadline = _time.time() + _PENDING_TIMEOUT+ running_deadline = None+ next_heartbeat = Nonelast_state = "pending"- while _time.time() < deadline:+ while True:try:state_row = self._session_db.get_handoff_state(self.session_id)except Exception:@@ -980,6 +1006,8 @@ class CLICommandsMixin:if current != last_state:if current == "running":_cprint(" Gateway picked it up; transferring...")+ running_deadline = _time.time() + _RUNNING_TIMEOUT+ next_heartbeat = _time.time() + _HEARTBEAT_EVERYlast_state = currentif current == "completed":_cprint("")@@ -1002,11 +1030,41 @@ class CLICommandsMixin:_cprint(f" Handoff failed: {err}")_cprint(" Your CLI session is intact. Try /handoff again, or /resume on the platform manually.")return True+ now = _time.time()+ if current == "pending":+ if now >= pending_deadline:+ break+ else: # running+ if next_heartbeat is not None and now >= next_heartbeat:+ _cprint(" Still transferring (the agent is replaying your session on the destination)...")+ next_heartbeat = now + _HEARTBEAT_EVERY+ if running_deadline is not None and now >= running_deadline:+ # Do NOT fail the row: the gateway owns it and will record+ # its own terminal state (or startup reclaim handles a+ # dead gateway). Stomping it here is the split-brain bug.+ _cprint(" The gateway is taking unusually long to finish the transfer.")+ _cprint(f" Check {platform_name} — the session may still arrive there.")+ _cprint(" This CLI is no longer waiting. Avoid continuing this session here;")+ _cprint(" if nothing arrives, retry /handoff once the state settles.")+ return True_time.sleep(0.5)- # Timed out. Clear the pending flag so the user can retry.+ # Pending timed out: nothing ever claimed the row. Clear the pending+ # flag (CAS — a claim racing this exact moment wins and we just lose+ # the retry convenience, never the handoff) so the user can retry.try:- self._session_db.fail_handoff(self.session_id, "timed out waiting for gateway")+ self._session_db.fail_handoff(+ self.session_id,+ "timed out waiting for gateway",+ only_states=("pending",),+ )+ except TypeError:+ # Older SessionDB without only_states (downgrade/mixed installs):+ # fall back to the legacy unconditional fail.+ try:+ self._session_db.fail_handoff(self.session_id, "timed out waiting for gateway")+ except Exception:+ passexcept Exception:pass_cprint(" Timed out waiting for the gateway. Is `hermes gateway` running?")diff --git a/hermes_state.py b/hermes_state.pyindex 715cbe7a238..dac6fcd2af4 100644--- a/hermes_state.py+++ b/hermes_state.py@@ -15214,15 +15214,46 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin))self._execute_write(_do)- def fail_handoff(self, session_id: str, error: str) -> None:- """Mark a handoff as failed and record the reason."""+ def fail_handoff(+ self,+ session_id: str,+ error: str,+ *,+ only_states: Optional[Tuple[str, ...]] = None,+ ) -> bool:+ """Mark a handoff as failed and record the reason.++ ``only_states`` makes the write a compare-and-swap: the row is only+ failed when its current ``handoff_state`` is in the given tuple.+ Waiters that give up (CLI 60s poll, Desktop bounded poll) MUST pass+ ``only_states=("pending",)`` — once the gateway watcher has claimed+ the row (``running``) it owns the terminal state, and a waiter-side+ unconditional fail races the dispatch: the gateway later overwrites+ ``failed`` → ``completed`` while the user was already told the+ gateway is down (split-brain — the handoff actually delivered and+ ``switch_session`` re-pointed the session).++ The gateway watcher itself fails its OWN claimed row unconditionally+ (no ``only_states``) — it is the owner while the row is ``running``.++ Returns True when a row was transitioned to ``failed``.+ """def _do(conn):- conn.execute(- "UPDATE sessions SET handoff_state = 'failed', "- "handoff_error = ? WHERE id = ?",- (error[:500], session_id),- )- self._execute_write(_do)+ if only_states:+ placeholders = ", ".join("?" for _ in only_states)+ cur = conn.execute(+ "UPDATE sessions SET handoff_state = 'failed', "+ f"handoff_error = ? WHERE id = ? AND handoff_state IN ({placeholders})",+ (error[:500], session_id, *only_states),+ )+ else:+ cur = conn.execute(+ "UPDATE sessions SET handoff_state = 'failed', "+ "handoff_error = ? WHERE id = ?",+ (error[:500], session_id),+ )+ return cur.rowcount > 0+ return bool(self._execute_write(_do))def reclaim_stale_running_handoffs(self, error: str) -> List[str]:"""Fail every handoff stuck in ``running``. Returns the ids reclaimed.diff --git a/tests/cli/test_handoff_slow_dispatch_timeout.py b/tests/cli/test_handoff_slow_dispatch_timeout.pynew file mode 100644index 00000000000..fd64fda895b--- /dev/null+++ b/tests/cli/test_handoff_slow_dispatch_timeout.py@@ -0,0 +1,259 @@+"""Regression tests: a slow gateway handoff dispatch must not be misreported+as "gateway not running" — and no waiter may stomp a claimed (running) row.++Bug shape (live-reproduced on main @1c5ee5815f): /handoff poll-waited a flat+60s for a TERMINAL state. The gateway watcher claims within seconds, but the+dispatch is a FULL synthetic agent turn (whole transcript replay + delivery)+that routinely exceeds 60s. The CLI then printed "Timed out waiting for the+gateway. Is `hermes gateway` running?" (false diagnosis), called+fail_handoff() on the RUNNING row (stomping the gateway's claim), and claimed+"Your CLI session is intact" after switch_session had already re-pointed the+session. The gateway later overwrote failed -> completed: split-brain.++Fix under test:+ 1. SessionDB.fail_handoff(only_states=...) — CAS: waiters can only fail+ rows still in the given states.+ 2. CLI _handle_handoff_command: 60s deadline applies only to PENDING;+ a RUNNING row gets a long (15 min) wait and is never failed by the CLI.+ 3. tui_gateway handoff.fail: only pending rows can be failed by Desktop.+"""++from __future__ import annotations++import time+import types+from unittest.mock import MagicMock, patch++import pytest++from hermes_state import SessionDB+++def db(tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))+ d = SessionDB(db_path=tmp_path / "state.db")+ yield d+ d.close()+++# ---------------------------------------------------------------------------+# 1. State layer: fail_handoff CAS+# ---------------------------------------------------------------------------++class TestFailHandoffCAS:+ def test_cas_fails_pending_row(self, db):+ db.ensure_session("s1", "cli")+ assert db.request_handoff("s1", "discord")+ assert db.fail_handoff("s1", "timed out", only_states=("pending",)) is True+ assert db.get_handoff_state("s1")["state"] == "failed"++ def test_cas_refuses_running_row(self, db):+ """A waiter timeout must NOT stomp a row the gateway has claimed."""+ db.ensure_session("s2", "cli")+ assert db.request_handoff("s2", "discord")+ assert db.claim_handoff("s2") # gateway claimed: pending -> running+ assert db.fail_handoff("s2", "timed out", only_states=("pending",)) is False+ assert db.get_handoff_state("s2")["state"] == "running"+ # gateway still reaches its own terminal state+ db.complete_handoff("s2")+ assert db.get_handoff_state("s2")["state"] == "completed"++ def test_unconditional_fail_still_available_to_owner(self, db):+ """The gateway watcher (owner of a claimed row) fails unconditionally."""+ db.ensure_session("s3", "cli")+ assert db.request_handoff("s3", "discord")+ assert db.claim_handoff("s3")+ assert db.fail_handoff("s3", "dispatch raised") is True+ assert db.get_handoff_state("s3")["state"] == "failed"++ def test_cas_refuses_terminal_rows(self, db):+ db.ensure_session("s4", "cli")+ assert db.request_handoff("s4", "discord")+ assert db.claim_handoff("s4")+ db.complete_handoff("s4")+ assert db.fail_handoff("s4", "late timeout", only_states=("pending",)) is False+ assert db.get_handoff_state("s4")["state"] == "completed"+++# ---------------------------------------------------------------------------+# 2. CLI wait loop+# ---------------------------------------------------------------------------++def _run_handoff(db, session_id, monkeypatch, time_budget=30.0):+ """Drive the real _handle_handoff_command against a real SessionDB.++ Gateway config / platform plumbing is stubbed; the poll loop, state+ transitions, and fail semantics are exercised for real. time.sleep is+ compressed so a simulated 60s pending deadline elapses in well under a+ second of wall clock.+ """+ from hermes_cli.cli_commands_mixin import CLICommandsMixin++ printed: list[str] = []++ class Host(CLICommandsMixin):+ def __init__(self):+ self.session_id = session_id+ self._session_db = db+ self._agent_running = False+ self._should_exit = False++ host = Host.__new__(Host)+ Host.__init__(host)++ home = types.SimpleNamespace(chat_id="123", name="home", thread_id=None)+ gw_config = MagicMock()+ gw_config.platforms = {}+ gw_config.get_home_channel.return_value = home++ import gateway.config as gwc++ platform_obj = gwc.Platform("discord")+ pcfg = types.SimpleNamespace(enabled=True, extra={})+ gw_config.platforms = {platform_obj: pcfg}++ # Compress time: each sleep(0.5) advances a fake clock by 2.0s.+ clock = {"t": time.time()}++ def fake_time():+ return clock["t"]++ def fake_sleep(secs):+ clock["t"] += max(secs * 4, 2.0)++ import cli as cli_mod++ with patch.object(gwc, "load_gateway_config", return_value=gw_config), \+ patch("time.time", side_effect=fake_time), \+ patch("time.sleep", side_effect=fake_sleep), \+ patch.object(cli_mod, "_cprint", side_effect=lambda s="": printed.append(s)):+ keep_going = host._handle_handoff_command("/handoff discord")+ return keep_going, printed, host+++class TestCLIWaitLoop:+ def test_pending_timeout_still_reports_gateway_down(self, db, monkeypatch):+ """No watcher ever claims the row -> 60s pending timeout, row failed."""+ db.ensure_session("cli-sess-a", "cli")+ keep, printed, _ = _run_handoff(db, "cli-sess-a", monkeypatch)+ out = "\n".join(printed)+ assert keep is True+ assert "Timed out waiting for the gateway" in out+ assert db.get_handoff_state("cli-sess-a")["state"] == "failed"++ def test_running_row_is_never_failed_by_cli(self, db, monkeypatch):+ """Row claimed (running) and never finishing: CLI gives up eventually+ but must NOT fail the row and must NOT print the gateway-down line."""+ db.ensure_session("cli-sess-b", "cli")+ # Pre-claim: by the time the CLI polls, the gateway owns the row.+ # request_handoff happens inside the command; claim it from a fake+ # watcher the instant it lands via a get_handoff_state side hook.+ real_get = db.get_handoff_state++ def claiming_get(sid):+ row = real_get(sid)+ if row and row.get("state") == "pending":+ db.claim_handoff(sid)+ row = real_get(sid)+ return row++ db_proxy = MagicMock(wraps=db)+ db_proxy.get_handoff_state.side_effect = claiming_get+ db_proxy.request_handoff.side_effect = db.request_handoff+ db_proxy.fail_handoff.side_effect = db.fail_handoff++ keep, printed, _ = _run_handoff(db_proxy, "cli-sess-b", monkeypatch)+ out = "\n".join(printed)+ assert keep is True+ assert "Is `hermes gateway` running?" not in out+ assert "taking unusually long" in out+ # The row is still owned by the gateway — untouched by the CLI.+ assert db.get_handoff_state("cli-sess-b")["state"] == "running"+ # Late gateway completion wins cleanly (no split-brain).+ db.complete_handoff("cli-sess-b")+ assert db.get_handoff_state("cli-sess-b")["state"] == "completed"++ def test_slow_dispatch_beyond_60s_completes(self, db, monkeypatch):+ """The exact live-repro shape: claim @~5s, complete @~80s simulated.+ Old code timed out at 60s with the false 'gateway running?' message;+ new code waits through the running phase and exits on completed."""+ db.ensure_session("cli-sess-c", "cli")+ t0 = {"polls": 0}+ real_get = db.get_handoff_state++ def slow_gateway(sid):+ t0["polls"] += 1+ row = real_get(sid)+ state = (row or {}).get("state")+ if state == "pending" and t0["polls"] >= 2:+ db.claim_handoff(sid)+ # each poll ~2s simulated; complete after ~40 polls (~80s+)+ if state == "running" and t0["polls"] >= 45:+ db.complete_handoff(sid)+ return real_get(sid)++ db_proxy = MagicMock(wraps=db)+ db_proxy.get_handoff_state.side_effect = slow_gateway+ db_proxy.request_handoff.side_effect = db.request_handoff+ db_proxy.fail_handoff.side_effect = db.fail_handoff++ keep, printed, host = _run_handoff(db_proxy, "cli-sess-c", monkeypatch)+ out = "\n".join(printed)+ assert keep is False # completed -> CLI exits like /quit+ assert "Handoff complete" in out+ assert "Timed out waiting for the gateway" not in out+ assert host._should_exit is True+ assert db.get_handoff_state("cli-sess-c")["state"] == "completed"+++# ---------------------------------------------------------------------------+# 3. Desktop handoff.fail RPC+# ---------------------------------------------------------------------------++class TestDesktopHandoffFail:+ def _call(self, db, session_key):+ """Invoke the handoff.fail handler body with server-global stand-ins."""+ import contextlib++ from tui_gateway import methods_session as ms++ handler = None+ for name, fn in ms._registry._pending:+ if name == "handoff.fail":+ handler = fn+ break+ assert handler is not None, "handoff.fail handler not registered"++ session = {"session_key": session_key}++ @contextlib.contextmanager+ def fake_session_db(_s):+ yield db++ globs = dict(handler.__globals__)+ globs["_sess_nowait"] = lambda p, r: (session, None)+ globs["_session_db"] = fake_session_db+ globs["_ok"] = lambda rid, result: {"ok": True, **result}+ globs["_db_unavailable_error"] = lambda rid, code: {"error": code}+ rebound = types.FunctionType(+ handler.__code__, globs, handler.__name__,+ handler.__defaults__, handler.__closure__,+ )+ return rebound("rid", {"error": "poll timeout"})++ def test_desktop_fail_refuses_running_row(self, db):+ db.ensure_session("d1", "desktop")+ assert db.request_handoff("d1", "discord")+ assert db.claim_handoff("d1")+ res = self._call(db, "d1")+ assert res["failed"] is False+ assert res["state"] == "running"+ assert db.get_handoff_state("d1")["state"] == "running"++ def test_desktop_fail_still_fails_pending_row(self, db):+ db.ensure_session("d2", "desktop")+ assert db.request_handoff("d2", "discord")+ res = self._call(db, "d2")+ assert res["failed"] is True+ assert db.get_handoff_state("d2")["state"] == "failed"diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.pyindex f76a4325c7d..978f446a2fb 100644--- a/tui_gateway/methods_session.py+++ b/tui_gateway/methods_session.py@@ -1658,10 +1658,16 @@ def _(rid, params: dict) -> dict:@method("handoff.fail")def _(rid, params: dict) -> dict:- """Mark an in-flight handoff as failed so the user can retry.-- Desktop calls this when its bounded poll times out. Only pending/running- rows are changed so a late success from the gateway watcher is not clobbered.+ """Mark a not-yet-claimed handoff as failed so the user can retry.++ Desktop calls this when its bounded poll times out. Only PENDING rows are+ changed (compare-and-swap in ``fail_handoff``): once the gateway watcher+ has claimed the row (``running``) it owns the terminal state — failing it+ from the waiter races the in-flight dispatch, which later overwrites+ ``failed`` → ``completed`` after the user was already told it failed+ (split-brain; the delivery actually happened). For a ``running`` row the+ caller gets ``{"failed": False, "state": "running"}`` and should surface+ "still transferring" instead."""session, err = _sess_nowait(params, rid)if err:@@ -1671,13 +1677,20 @@ def _(rid, params: dict) -> dict:if db is None:return _db_unavailable_error(rid, code=5007)key = session["session_key"]- record = db.get_handoff_state(key) or {}- state = record.get("state") or ""- if state in {"pending", "running"}:- db.fail_handoff(key, reason)+ try:+ failed = db.fail_handoff(key, reason, only_states=("pending",))+ except TypeError:+ # Older SessionDB without only_states: preserve prior behavior+ # minus the running-row stomp (fail only when still pending).+ record = db.get_handoff_state(key) or {}+ failed = (record.get("state") or "") == "pending"+ if failed:+ db.fail_handoff(key, reason)+ if failed:return _ok(rid, {"failed": True, "state": "failed"})+ record = db.get_handoff_state(key) or {}- return _ok(rid, {"failed": False, "state": state})+ return _ok(rid, {"failed": False, "state": record.get("state") or ""})@method("session.usage")diff --git a/website/docs/user-guide/sessions.md b/website/docs/user-guide/sessions.mdindex 0b62c69f715..af18e5c5ba4 100644--- a/website/docs/user-guide/sessions.md+++ b/website/docs/user-guide/sessions.md@@ -246,7 +246,8 @@ What happens:**Failure modes:**- No home channel configured → CLI refuses with a `/sethome` hint.-- Platform not enabled / gateway not running → CLI times out at 60s with a clear message and your CLI session stays intact.+- Gateway not running (nothing ever claims the request) → CLI times out at 60s with a clear message and your CLI session stays intact.+- Slow transfer: once the gateway claims the handoff it replays your full session through a real agent turn, which can take a few minutes on long sessions. The CLI shows "Still transferring..." heartbeats and waits up to 15 minutes — it never misreports a slow transfer as "gateway not running".- Thread creation fails (permissions, topics-mode off) → falls back to the home channel directly and still completes; no thread isolation but the handoff itself works.- `adapter.send` fails (rate limit, transient API error) → handoff marked failed with the reason; the row clears so you can retry.