The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): stop UI freeze on unreachable provider Closes #81123
finn76348b8528e7c5e
diff --git a/hermes_cli/models.py b/hermes_cli/models.pyindex d3e5046cfdb..ab83fe72720 100644--- a/hermes_cli/models.py+++ b/hermes_cli/models.py@@ -2159,6 +2159,35 @@ def github_model_reasoning_efforts(return _github_reasoning_efforts_for_model_id(str(model_id or normalized))+# Negative cache: monotonic timestamp of the last fully-failed probe, keyed+# by ``host:port`` so both URL candidates (``/v1`` + root) share one entry.+# Without this, an unreachable endpoint (TCP blackhole — SYN draws no reply,+# so every attempt burns its full connect timeout) makes every picker open /+# chat turn re-pay the timeout per candidate, and the sequential stalls stack+# past 10s while the Desktop sits on a spinner with no error (#81123). Short+# TTL collapses the burst but still picks up recovery without a restart.+# Mirrors _deepinfra_catalog_neg_cache.+_probe_neg_cache: dict[str, float] = {}+_PROBE_NEG_TTL = 60.0 # seconds+++def _probe_neg_key(base_url: str) -> Optional[str]:+ """Return a ``host:port`` key for *base_url*, or None if it has no host."""+ normalized = (base_url or "").strip().lower()+ if not normalized:+ return None+ url = normalized if "://" in normalized else f"http://{normalized}"+ try:+ parsed = urllib.parse.urlparse(url)+ host = parsed.hostname or ""+ if not host:+ return None+ port = parsed.port or (443 if parsed.scheme == "https" else 80)+ except Exception:+ return None+ return f"{host}:{port}"++def _probe_result(models, probed_url, resolved_base_url, suggested_base_url=None, used_fallback=False) -> dict[str, Any]:@@ -2190,6 +2219,14 @@ def probe_api_models(candidates.append((alternate_base, True))tried: list[str] = []+ # ponytail: short-TTL negative cache; full re-probe once it expires.+ _neg_key = _probe_neg_key(normalized)+ if _neg_key is not None:+ _neg_seen = _probe_neg_cache.get(_neg_key)+ if _neg_seen is not None and (time.monotonic() - _neg_seen) < _PROBE_NEG_TTL:+ return _probe_result(+ None, normalized.rstrip("/") + "/models", normalized,+ alternate_base if alternate_base != normalized else None)headers: dict[str, str] = {"User-Agent": _HERMES_USER_AGENT}if urllib.parse.urlparse(normalized).hostname == "generativelanguage.googleapis.com":headers["X-Goog-Api-Client"] = f"hermes-agent/{_HERMES_VERSION}"@@ -2222,6 +2259,9 @@ def probe_api_models(return _probe_result([m.get("id", "") for m in data.get("data", [])], url, candidate_base.rstrip("/"),alternate_base if alternate_base != candidate_base else normalized, is_fallback)++ if _neg_key is not None:+ _probe_neg_cache[_neg_key] = time.monotonic()return _probe_result(None, tried[0] if tried else normalized.rstrip("/") + "/models", normalized,alternate_base if alternate_base != normalized else None)diff --git a/tests/agent/test_custom_provider_ca_probes.py b/tests/agent/test_custom_provider_ca_probes.pyindex 1c32edc3fc3..b924adb75cf 100644--- a/tests/agent/test_custom_provider_ca_probes.py+++ b/tests/agent/test_custom_provider_ca_probes.py@@ -239,6 +239,14 @@ class TestMetadataProbeThreadsProviderCA:class TestCatalogProbeThreadsSSLContext:"""End-to-end: the urllib catalog probe carries the provider SSL context."""+ @pytest.fixture(autouse=True)+ def _clear_probe_neg_cache(self):+ import hermes_cli.models as models++ models._probe_neg_cache.clear()+ yield+ models._probe_neg_cache.clear()+def test_probe_api_models_passes_ssl_context(self, clean_env, real_ca):import hermes_cli.models as modelsdiff --git a/tests/hermes_cli/test_cached_fetch_api_models.py b/tests/hermes_cli/test_cached_fetch_api_models.pyindex 0424b7ff876..e2c6f1864d3 100644--- a/tests/hermes_cli/test_cached_fetch_api_models.py+++ b/tests/hermes_cli/test_cached_fetch_api_models.py@@ -378,3 +378,37 @@ class TestSalvageFollowups:out = mod.cached_fetch_api_models("sk-key", "https://gw.example.com/v1")assert out == ["live-models"]live.assert_called_once()+++class TestProbeApiModelsNegativeCache:+ """#81123: a fully-failed /models probe must degrade fast, not re-burn+ connect timeouts per URL candidate on every picker open."""++ def _fail(self, req, **kw):+ raise TimeoutError("connect timed out")++ def test_repeat_failure_skips_network(self, monkeypatch):+ import hermes_cli.models as mod++ monkeypatch.setattr(mod, "_probe_neg_cache", {})+ monkeypatch.setattr(mod, "_urlopen_model_catalog_request", self._fail)+ r1 = mod.probe_api_models("", "https://blackhole.invalid/v1", timeout=1.0)+ calls = []+ monkeypatch.setattr(+ mod, "_urlopen_model_catalog_request",+ lambda req, **kw: calls.append(req.full_url) or self._fail(req, **kw),+ )+ r2 = mod.probe_api_models("", "https://blackhole.invalid/v1/", timeout=1.0)+ assert (r1["models"], r2["models"]) == (None, None)+ assert calls == [] # /v1 + root share one host:port entry+ assert r2["probed_url"] == "https://blackhole.invalid/v1/models"++ def test_expired_entry_reprobes(self, monkeypatch):+ import hermes_cli.models as mod++ old = time.monotonic() - mod._PROBE_NEG_TTL - 1+ monkeypatch.setattr(mod, "_probe_neg_cache", {"blackhole.invalid:443": old})+ monkeypatch.setattr(mod, "_urlopen_model_catalog_request", self._fail)+ out = mod.probe_api_models("", "https://blackhole.invalid/v1", timeout=1.0)+ assert out["models"] is None+ assert mod._probe_neg_cache["blackhole.invalid:443"] > old