Skip to content

The agent that grows with you

fix(web): retry transient transport blips in the dashboard Codex device-code login

teknium197c67507c76a
diff --git a/hermes_cli/web_routers/oauth.py b/hermes_cli/web_routers/oauth.py
index c804336dc72..3b2eb16da41 100644
--- a/hermes_cli/web_routers/oauth.py
+++ b/hermes_cli/web_routers/oauth.py
@@ -150,15 +150,35 @@ def _codex_cancelled(sess: Dict[str, Any], session_id: str, stage: str = "") ->
return True
+def _codex_post(httpx, url: str, **kwargs: Any) -> Any:
+ """One 15s POST for the device-login flow, mirroring ``auth_codex._codex_login_post``.
+
+ A transient transport blip (a dropped connection mid-flow) is retried twice with a small
+ linear backoff before propagating: losing the token exchange to a single SSL EOF wastes a
+ device-code approval the user already completed in the browser (#114610).
+ """
+ from hermes_cli.auth_codex import _is_transient_transport_error
+
+ attempt, attempts = 1, 3
+ while True:
+ try:
+ with httpx.Client(timeout=httpx.Timeout(15.0)) as client:
+ return client.post(url, **kwargs)
+ except Exception as exc:
+ if attempt == attempts or not _is_transient_transport_error(exc):
+ raise
+ time.sleep(attempt)
+ attempt += 1
+
+
def _codex_request_user_code(httpx) -> Dict[str, Any]:
"""Step 1: request device code; returns device_data with ``interval`` clamped (>= 3s)."""
from hermes_cli.auth import CODEX_OAUTH_CLIENT_ID
- with httpx.Client(timeout=httpx.Timeout(15.0)) as client:
- resp = client.post(
- f"{_CODEX_ISSUER}/api/accounts/deviceauth/usercode", json={"client_id": CODEX_OAUTH_CLIENT_ID},
- headers=_JSON_HEADERS,
- )
+ resp = _codex_post(
+ httpx, f"{_CODEX_ISSUER}/api/accounts/deviceauth/usercode", json={"client_id": CODEX_OAUTH_CLIENT_ID},
+ headers=_JSON_HEADERS,
+ )
if resp.status_code != 200:
raise RuntimeError(_codex_device_code_start_error(resp))
device_data = resp.json()
@@ -170,8 +190,12 @@ def _codex_request_user_code(httpx) -> Dict[str, Any]:
def _codex_poll_authorization(httpx, sess: Dict[str, Any], session_id: str) -> Any:
"""Step 2: poll until authorized. ``None`` = expired; ``_CANCELLED`` = user cancelled."""
+ from hermes_cli.auth_codex import _is_transient_transport_error
+
deadline = time.monotonic() + sess["expires_in"]
payload = {"device_auth_id": sess["device_auth_id"], "user_code": sess["user_code"]}
+ max_consecutive_blips = 6 # same cap as the CLI poll loop: survives drops, fails fast on a dead network
+ consecutive_blips = 0
with httpx.Client(timeout=httpx.Timeout(15.0)) as client:
while time.monotonic() < deadline:
if _codex_cancelled(sess, session_id):
@@ -179,7 +203,20 @@ def _codex_poll_authorization(httpx, sess: Dict[str, Any], session_id: str) -> A
time.sleep(sess["interval"])
if _codex_cancelled(sess, session_id):
return _CANCELLED
- poll = client.post(f"{_CODEX_ISSUER}/api/accounts/deviceauth/token", json=payload, headers=_JSON_HEADERS)
+ try:
+ poll = client.post(
+ f"{_CODEX_ISSUER}/api/accounts/deviceauth/token", json=payload, headers=_JSON_HEADERS)
+ except Exception as exc:
+ if not _is_transient_transport_error(exc):
+ raise
+ consecutive_blips += 1
+ if consecutive_blips >= max_consecutive_blips:
+ raise RuntimeError(
+ f"deviceauth/token poll failed after {consecutive_blips} consecutive"
+ f" transport errors: {exc}") from exc
+ _log.info("oauth/device: openai-codex poll transport blip, retrying (session=%s)", session_id)
+ continue
+ consecutive_blips = 0
if poll.status_code == 200:
return poll.json()
if poll.status_code in {403, 404}:
@@ -196,16 +233,15 @@ def _codex_exchange_tokens(httpx, code_resp: Dict[str, Any]) -> Dict[str, str]:
code_verifier = code_resp.get("code_verifier", "")
if not authorization_code or not code_verifier:
raise RuntimeError("device-auth response missing authorization_code/code_verifier")
- with httpx.Client(timeout=httpx.Timeout(15.0)) as client:
- token_resp = client.post(
- CODEX_OAUTH_TOKEN_URL,
- data={
- "grant_type": "authorization_code", "code": authorization_code,
- "redirect_uri": f"{_CODEX_ISSUER}/deviceauth/callback",
- "client_id": CODEX_OAUTH_CLIENT_ID, "code_verifier": code_verifier,
- },
- headers={"Content-Type": "application/x-www-form-urlencoded"},
- )
+ token_resp = _codex_post(
+ httpx, CODEX_OAUTH_TOKEN_URL,
+ data={
+ "grant_type": "authorization_code", "code": authorization_code,
+ "redirect_uri": f"{_CODEX_ISSUER}/deviceauth/callback",
+ "client_id": CODEX_OAUTH_CLIENT_ID, "code_verifier": code_verifier,
+ },
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ )
if token_resp.status_code != 200:
raise RuntimeError(f"token exchange returned {token_resp.status_code}")
tokens = token_resp.json()
diff --git a/tests/hermes_cli/web_routers/__init__.py b/tests/hermes_cli/web_routers/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/tests/hermes_cli/web_routers/test_codex_device_login_transient_retry.py b/tests/hermes_cli/web_routers/test_codex_device_login_transient_retry.py
new file mode 100644
index 00000000000..b9ce89902bc
--- /dev/null
+++ b/tests/hermes_cli/web_routers/test_codex_device_login_transient_retry.py
@@ -0,0 +1,86 @@
+"""Dashboard/Desktop Codex device-code login survives transient transport blips.
+
+The web-surface worker is a deliberate copy of the CLI poll loop (``auth_codex``); it must
+share the same retry contract: the poll tolerates a bounded run of consecutive transport
+errors (reset by any response) and the one-shot POSTs retry twice, while non-transport
+errors still surface immediately without burning retries.
+"""
+
+import ssl
+from types import SimpleNamespace
+
+import pytest
+
+from hermes_cli.web_routers import oauth as rt_oauth
+
+
+_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: each ``post`` pops the next scripted step —
+ a ``BaseException`` is raised, anything else is returned as the response."""
+
+ 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 _fake_httpx(monkeypatch, client):
+ """The worker helpers take the ``httpx`` module as a parameter; hand them a scripted one."""
+ monkeypatch.setattr(rt_oauth.time, "sleep", lambda *_: None)
+ return SimpleNamespace(Client=lambda **kw: client, Timeout=lambda t: t)
+
+
+def test_poll_survives_transport_blips_and_returns_approval(monkeypatch):
+ approved = {"authorization_code": "code", "code_verifier": "verifier"}
+ client = _ScriptedClient([
+ ssl.SSLEOFError(8, _SSL_EOF_MESSAGE),
+ _Response(404), # still pending — any response resets the blip counter
+ ssl.SSLEOFError(8, _SSL_EOF_MESSAGE),
+ _Response(200, approved),
+ ])
+ sess = {"expires_in": 900, "device_auth_id": "dev", "user_code": "ABCD-EFGH", "interval": 3}
+
+ result = rt_oauth._codex_poll_authorization(_fake_httpx(monkeypatch, client), sess, "sid")
+
+ assert result == approved
+ assert client.calls == 4
+
+
+def test_one_shot_posts_retry_blips_but_not_other_errors(monkeypatch):
+ monkeypatch.setattr("hermes_cli.auth.CODEX_OAUTH_CLIENT_ID", "client-id", raising=False)
+ device = {"user_code": "ABCD-EFGH", "device_auth_id": "dev", "interval": "5"}
+ client = _ScriptedClient([ssl.SSLEOFError(8, _SSL_EOF_MESSAGE), _Response(200, dict(device))])
+
+ assert rt_oauth._codex_request_user_code(_fake_httpx(monkeypatch, client))["device_auth_id"] == "dev"
+ assert client.calls == 2
+
+ client = _ScriptedClient([ValueError("not a network blip"), _Response(200, {"access_token": "t"})])
+ with pytest.raises(ValueError):
+ rt_oauth._codex_exchange_tokens(
+ _fake_httpx(monkeypatch, client), {"authorization_code": "code", "code_verifier": "verifier"})
+ assert client.calls == 1