Skip to content

The agent that grows with you

fix(cli): a failed gateway redial is retried even while its loop thread exits

Teknium2f7500d85e6d
diff --git a/hermes_cli/gateway_connection.py b/hermes_cli/gateway_connection.py
index 85e3de71611..d28b8138b6d 100644
--- a/hermes_cli/gateway_connection.py
+++ b/hermes_cli/gateway_connection.py
@@ -140,6 +140,10 @@ class GatewayConnection:
raise self._error
return
thread = self._thread
+ if thread is not None and self.closed and thread.is_alive() and thread is not threading.current_thread():
+ # ``_run`` reports ready before its thread returns: that life is over, so let it
+ # end instead of reading it as a dial in progress (and re-raising its stale error).
+ thread.join(max(deadline - time.monotonic(), 0))
if thread is None or not thread.is_alive():
from agent.memory_provider import spawn_context_thread
diff --git a/tests/hermes_cli/test_gateway_connection_reconnect.py b/tests/hermes_cli/test_gateway_connection_reconnect.py
index b94b73a0cb1..bb8938ba587 100644
--- a/tests/hermes_cli/test_gateway_connection_reconnect.py
+++ b/tests/hermes_cli/test_gateway_connection_reconnect.py
@@ -130,6 +130,31 @@ def test_a_failed_redial_is_retried_on_the_next_call(gateway, conn):
assert conn.call("status") == {"status": "ok", "life": 2}
+def test_a_failed_redial_is_retried_even_while_its_loop_thread_is_still_exiting(gateway, conn):
+ """The failed dial's loop thread reports ready before it returns; the next call must not read
+ that still-alive thread as a dial in progress and re-raise its stale error."""
+ gateway.hang_up(conn)
+ gateway.refusals = 1
+ released = threading.Event()
+ run = conn._run
+
+ def run_then_linger():
+ run()
+ released.wait(5) # still alive after ``_ready.set()``, as on a loaded runner
+
+ conn._run = run_then_linger
+ with pytest.raises(GatewayClientError, match="Gateway starting"):
+ conn.call("status")
+ assert conn._thread.is_alive()
+ timer = threading.Timer(0.2, released.set)
+ timer.start()
+ try:
+ assert conn.call("status") == {"status": "ok", "life": 2}
+ finally:
+ released.set()
+ timer.cancel()
+
+
def test_a_first_connect_failure_is_still_final(gateway):
gateway.refusals = 2
connection = GatewayConnection(connect=gateway.dial)