The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): retry transient transport blips in the Codex device-code login
liuhao102482e5db63bc74
diff --git a/hermes_cli/auth_codex.py b/hermes_cli/auth_codex.pyindex acd66e45c4d..a77aa54bf7e 100644--- a/hermes_cli/auth_codex.py+++ b/hermes_cli/auth_codex.py@@ -243,13 +243,41 @@ def _ssl_interop_hint(exc: BaseException) -> str:)+def _is_transient_transport_error(exc: BaseException) -> bool:+ """True when *exc* is transport-level (connection/TLS/socket) and safe to retry.++ httpx raises ``httpx.TransportError`` subclasses wrapping the original ``ssl``/``socket``+ error as ``__cause__``, so both spellings count. Anything else (decode errors, bugs) is+ not a network blip and must surface immediately.+ """+ err: Optional[BaseException] = exc+ seen: set[int] = set()+ while err is not None and id(err) not in seen:+ if isinstance(err, (httpx.TransportError, OSError)):+ return True+ seen.add(id(err))+ err = err.__cause__+ return False++def _codex_login_post(url: str, *, failure: Tuple[str, str], **kwargs: Any) -> "httpx.Response":- """One 15s POST for the device-login flow; transport errors become ``_codex_err(*failure)``."""- try:- with _codex_http_client(timeout=httpx.Timeout(15.0)) as client:- return client.post(url, **kwargs)- except Exception as exc:- raise _codex_err(f"{failure[0]}: {exc}{_ssl_interop_hint(exc)}", failure[1]) from exc+ """One 15s POST for the device-login flow; transport errors become ``_codex_err(*failure)``.++ A transient transport blip (a dropped connection mid-flow) is retried twice with a small+ linear backoff before failing: losing the token exchange to a single SSL EOF wastes a+ device-code approval the user already completed in the browser (#114610).+ """+ attempts = 3+ for attempt in range(1, attempts + 1):+ try:+ with _codex_http_client(timeout=httpx.Timeout(15.0)) as client:+ return client.post(url, **kwargs)+ except Exception as exc:+ if attempt < attempts and _is_transient_transport_error(exc):+ time.sleep(attempt)+ continue+ raise _codex_err(f"{failure[0]}: {exc}{_ssl_interop_hint(exc)}", failure[1]) from exc+ raise _codex_err(f"{failure[0]}: exhausted retries", failure[1]) # pragma: no coverdef _codex_http_client(**kwargs: Any) -> "httpx.Client":@@ -765,10 +793,12 @@ def _codex_poll_authorization_code(issuer: str, *, device_auth_id: str, user_code: str, poll_interval: int) -> Dict[str, Any]:"""Step 3 of the Codex device flow: poll until sign-in completes (403/404 = still pending)."""max_wait = 15 * 60 # 15 minutes+ max_consecutive_blips = 6 # survives transient drops, still fails fast on a dead networkstart = time.monotonic()code_resp = Nonetry:with _codex_http_client(timeout=httpx.Timeout(15.0)) as client:+ consecutive_blips = 0while time.monotonic() - start < max_wait:time.sleep(poll_interval)try:@@ -777,9 +807,19 @@ def _codex_poll_authorization_code(json={"device_auth_id": device_auth_id, "user_code": user_code},headers={"Content-Type": "application/json"})except Exception as exc:- raise _codex_err(- f"Device auth polling request failed: {exc}{_ssl_interop_hint(exc)}",- "device_code_poll_error") from exc+ if not _is_transient_transport_error(exc):+ raise _codex_err(+ f"Device auth polling request failed: {exc}{_ssl_interop_hint(exc)}",+ "device_code_poll_error") from exc+ consecutive_blips += 1+ if consecutive_blips >= max_consecutive_blips:+ raise _codex_err(+ f"Device auth polling request failed after {consecutive_blips} consecutive"+ f" transport errors: {exc}{_ssl_interop_hint(exc)}",+ "device_code_poll_error") from exc+ print("Transient network error while waiting for sign-in; retrying...")+ continue+ consecutive_blips = 0if poll_resp.status_code == 200:code_resp = poll_resp.json()break@@ -790,6 +830,9 @@ def _codex_poll_authorization_code(except KeyboardInterrupt:print("\nLogin cancelled.")raise SystemExit(130)+ except KeyboardInterrupt:+ print("\nLogin cancelled.")+ raise SystemExit(130)if code_resp is None:raise _codex_err("Login timed out after 15 minutes.", "device_code_timeout")return code_respdiff --git a/tests/hermes_cli/test_codex_device_login_ssl_hint.py b/tests/hermes_cli/test_codex_device_login_ssl_hint.pyindex 6a0d753b54d..83601654d88 100644--- a/tests/hermes_cli/test_codex_device_login_ssl_hint.py+++ b/tests/hermes_cli/test_codex_device_login_ssl_hint.py@@ -54,6 +54,9 @@ def _poll():def test_ssl_transport_error_keeps_detail_and_adds_hint(monkeypatch, call, code):exc = ssl.SSLEOFError(8, _SSL_EOF_MESSAGE)monkeypatch.setattr(auth_codex, "_codex_http_client", lambda **kw: _RaisingClient(exc))+ # The persistent-blip path retries before failing (see test_codex_device_login_transient_retry);+ # skip its backoff sleeps so this shape test stays instant.+ monkeypatch.setattr(auth_codex.time, "sleep", lambda *_: None)with pytest.raises(AuthError) as excinfo:call()@@ -68,6 +71,7 @@ def test_ssl_transport_error_keeps_detail_and_adds_hint(monkeypatch, call, code)def test_plain_timeout_has_no_ssl_hint(monkeypatch):exc = httpx.ConnectTimeout("timed out")monkeypatch.setattr(auth_codex, "_codex_http_client", lambda **kw: _RaisingClient(exc))+ monkeypatch.setattr(auth_codex.time, "sleep", lambda *_: None) # skip retry backoffwith pytest.raises(AuthError) as excinfo:_login_post()diff --git a/tests/hermes_cli/test_codex_device_login_transient_retry.py b/tests/hermes_cli/test_codex_device_login_transient_retry.pynew file mode 100644index 00000000000..c2947db8cf2--- /dev/null+++ b/tests/hermes_cli/test_codex_device_login_transient_retry.py@@ -0,0 +1,151 @@+"""Codex device-login survives transient transport blips (#114610).++A single dropped connection (e.g. an SSL EOF between polls) used to abort the whole+device-code flow and waste the browser approval the user had already completed. Transient+transport errors are now retried — the poll loop tolerates up to 6 consecutive blips and the+one-shot device-login POSTs retry twice — while persistent failures still surface the typed+``AuthError`` with the original cause chained, and non-transport errors fail immediately+without burning retries.+"""++import ssl++import httpx+import pytest++from hermes_cli import auth_codex+from hermes_cli.auth import AuthError+++_SSL_EOF_MESSAGE = (+ "[SSL: UNEXPECTED_EOF_WHILE_READING] EOF occurred in violation of protocol (_ssl.c:1016)")+++class _ScriptedClient:+ """Context-manager httpx.Client stand-in replaying a scripted sequence of results.++ Each ``post`` call pops the next entry: a ``BaseException`` is raised, anything else is+ returned as-is (tests pass simple response stubs).+ """++ def __init__(self, script):+ self._script = list(script)+ self.calls = 0++ def __enter__(self):+ return self++ def __exit__(self, *exc_info):+ return False++ def post(self, url, **kwargs):+ self.calls += 1+ step = self._script.pop(0)+ if isinstance(step, BaseException):+ raise step+ return step+++class _Response:+ def __init__(self, status_code, payload=None):+ self.status_code = status_code+ self._payload = payload++ def json(self):+ return self._payload+++def _install(monkeypatch, client):+ monkeypatch.setattr(auth_codex, "_codex_http_client", lambda **kw: client)+ monkeypatch.setattr(auth_codex.time, "sleep", lambda *_: None)+++def _login_post():+ return auth_codex._codex_login_post(+ "https://auth.openai.com/api/accounts/deviceauth/usercode",+ failure=("Failed to request device code", "device_code_request_failed"))+++def _poll():+ return auth_codex._codex_poll_authorization_code(+ "https://auth.openai.com", device_auth_id="da", user_code="uc", poll_interval=0)+++def test_poll_survives_transients_then_completes(monkeypatch):+ client = _ScriptedClient([+ ssl.SSLEOFError(8, _SSL_EOF_MESSAGE),+ httpx.ConnectError("connection reset by peer"),+ _Response(200, {"authorization_code": "ac", "code_verifier": "cv"})])+ _install(monkeypatch, client)++ result = _poll()++ assert result == {"authorization_code": "ac", "code_verifier": "cv"}+ assert client.calls == 3+++def test_login_post_retries_transient_blip(monkeypatch):+ client = _ScriptedClient([+ ssl.SSLEOFError(8, _SSL_EOF_MESSAGE), _Response(200, {"user_code": "uc"})])+ _install(monkeypatch, client)++ resp = _login_post()++ assert resp.status_code == 200+ assert client.calls == 2+++def test_login_post_persistent_transient_fails_typed(monkeypatch):+ exc = ssl.SSLEOFError(8, _SSL_EOF_MESSAGE)+ client = _ScriptedClient([exc, exc, exc])+ _install(monkeypatch, client)++ with pytest.raises(AuthError) as excinfo:+ _login_post()++ err = excinfo.value+ assert err.code == "device_code_request_failed"+ assert "UNEXPECTED_EOF_WHILE_READING" in str(err)+ assert "OPENSSL_CONF" in str(err)+ assert err.__cause__ is exc+ assert client.calls == 3 # capped at three attempts, not an endless retry+++def test_poll_persistent_transient_fails_after_consecutive_cap(monkeypatch):+ exc = httpx.ConnectTimeout("timed out")+ client = _ScriptedClient([exc] * 6)+ _install(monkeypatch, client)++ with pytest.raises(AuthError) as excinfo:+ _poll()++ err = excinfo.value+ assert err.code == "device_code_poll_error"+ assert "6 consecutive" in str(err)+ assert "timed out" in str(err)+ assert err.__cause__ is exc+ assert client.calls == 6+++def test_poll_non_transport_error_fails_immediately(monkeypatch):+ exc = ValueError("decode bug")+ client = _ScriptedClient([exc, _Response(200, {"authorization_code": "ac"})])+ _install(monkeypatch, client)++ with pytest.raises(AuthError) as excinfo:+ _poll()++ assert excinfo.value.__cause__ is exc+ assert client.calls == 1 # never retried: not a network blip+++def test_login_post_non_transport_error_fails_immediately(monkeypatch):+ exc = ValueError("unsupported kwarg")+ client = _ScriptedClient([exc, _Response(200, {"user_code": "uc"})])+ _install(monkeypatch, client)++ with pytest.raises(AuthError) as excinfo:+ _login_post()++ assert excinfo.value.__cause__ is exc+ assert client.calls == 1