Skip to content

The agent that grows with you

fix(picker): never wait on provider catalog probes in the model-options read path

finn763cdacc2bcf118
diff --git a/hermes_cli/inventory.py b/hermes_cli/inventory.py
index ae713969192..febe74f1ba0 100644
--- a/hermes_cli/inventory.py
+++ b/hermes_cli/inventory.py
@@ -77,12 +77,14 @@ def build_models_payload(
pricing_cache_only: bool = False,
capabilities: bool = False, featured: bool = False, force_fresh_nous_tier: bool = False,
refresh: bool = False, probe_custom_providers: bool = True, probe_current_custom_provider: bool = False,
- for_picker: bool = False, max_models: int | None = None,
+ for_picker: bool = False, max_models: int | None = None, non_blocking_catalogs: bool = False,
) -> dict:
"""Build the ``{providers, model, provider}`` shape every consumer needs. ``explicit_only`` keeps
only providers the user explicitly configured — hides ambient/auto-seeded credentials from
desktop chat pickers. ``pricing_cache_only``: with ``pricing``, use only values already resident
- in process caches (normal picker opens, while a background worker warms cold endpoints)."""
+ in process caches (normal picker opens, while a background worker warms cold endpoints).
+ ``non_blocking_catalogs``: provider catalogs come from the disk cache only — a degraded provider
+ cannot stall the response (GUI picker opens)."""
from hermes_cli.model_switch import list_authenticated_providers
rows = list_authenticated_providers(
@@ -92,6 +94,7 @@ def build_models_payload(
max_models=max_models, refresh=refresh, probe_custom_providers=probe_custom_providers,
probe_current_custom_provider=probe_current_custom_provider, for_picker=for_picker,
excluded_providers=ctx.excluded_providers or [],
+ non_blocking_catalogs=non_blocking_catalogs,
)
# Managed local runtime: staged GGUFs are selectable like any provider's models, but
@@ -184,13 +187,19 @@ def build_model_options_payload(
refresh: bool = False,
) -> dict:
"""Shared API-server/dashboard/TUI payload. Normal open probes only the current custom provider so
- offline saved endpoints don't block the picker; explicit refresh probes all and busts the cache."""
+ offline saved endpoints don't block the picker; explicit refresh probes all and busts the cache.
+
+ A normal open (``refresh=False``) is a READ path: provider catalogs come from the disk cache
+ only, stale/missing ones warm in the background, and rows still waiting carry ``catalog_pending``.
+ A degraded provider (hanging endpoint, failed auth probe) can therefore delay neither the other
+ providers' rows nor the response (#114215)."""
refresh = bool(refresh)
payload = build_models_payload(
ctx, explicit_only=bool(explicit_only), include_unconfigured=bool(include_unconfigured),
picker_hints=True, canonical_order=True, pricing=True, pricing_cache_only=not refresh,
capabilities=True, featured=True,
refresh=refresh, probe_custom_providers=refresh, probe_current_custom_provider=not refresh,
+ non_blocking_catalogs=not refresh,
)
if not refresh:
_prewarm_pricing_async(payload["providers"], current_provider=ctx.current_provider,
diff --git a/hermes_cli/model_switch_providers.py b/hermes_cli/model_switch_providers.py
index 4178f08b60d..cae355b524e 100644
--- a/hermes_cli/model_switch_providers.py
+++ b/hermes_cli/model_switch_providers.py
@@ -208,6 +208,21 @@ def prewarm_picker_cache_async() -> Optional["_threading.Thread"]:
return t
+def _spawn_background_warm(target, *args, cache_key: str = "", **kwargs) -> None:
+ """Run a cache-warming probe in a daemon thread (fire-and-forget, exception-isolated).
+
+ The GUI read path never waits on a probe; the warm thread makes the NEXT open cheap. Named by
+ ``cache_key`` so a stack dump says which catalog is being fetched."""
+ def _warm() -> None:
+ try:
+ target(*args, **kwargs)
+ except Exception:
+ logger.debug("background catalog warm failed (%s)", cache_key or target, exc_info=True)
+
+ _threading.Thread(target=_warm, daemon=True,
+ name=f"catalog-warm-{cache_key or 'anon'}").start()
+
+
def _prefetch_provider_models_parallel(provider_slugs: list[str]) -> None:
"""Fetch stale/missing provider catalogs in parallel before the serial picker loop.
@@ -390,11 +405,14 @@ def _is_aws_sdk(pconfig) -> bool:
return bool(pconfig) and getattr(pconfig, "auth_type", "") == "aws_sdk"
-def _live_or_curated_ids(slug: str, curated: dict, *fallback_keys: str, merge_models_dev: bool = True) -> list:
+def _live_or_curated_ids(slug: str, curated: dict, *fallback_keys: str, merge_models_dev: bool = True,
+ non_blocking: bool = False) -> list:
"""``cached_provider_model_ids`` (the SAME disk-cached list ``hermes model`` builds), falling
- back to the curated list (merged with models.dev for preferred providers) when live is empty."""
+ back to the curated list (merged with models.dev for preferred providers) when live is empty.
+ ``non_blocking`` (GUI read path) reads the disk cache only — a provider that is slow or down
+ contributes its curated list instead of stalling the whole picker (#114215)."""
from hermes_cli.models import _MODELS_DEV_PREFERRED, _merge_with_models_dev, cached_provider_model_ids
- model_ids = cached_provider_model_ids(slug)
+ model_ids = cached_provider_model_ids(slug, non_blocking=non_blocking)
if not model_ids:
model_ids = _first_curated(curated, fallback_keys or (slug,))
if merge_models_dev and slug in _MODELS_DEV_PREFERRED:
@@ -412,11 +430,13 @@ def _first_curated(curated: dict, keys) -> list:
return model_ids
-def _aws_live_or_curated_ids(slug: str, curated: dict, *fallback_keys: str) -> list:
+def _aws_live_or_curated_ids(slug: str, curated: dict, *fallback_keys: str,
+ non_blocking: bool = False) -> list:
"""Bedrock: live discovery reflects the active region (eu.*, ap.*) rather than the static
us.* list; any failure falls back to the curated list."""
try:
- return _live_or_curated_ids(slug, curated, *fallback_keys, merge_models_dev=False) or []
+ return _live_or_curated_ids(slug, curated, *fallback_keys, merge_models_dev=False,
+ non_blocking=non_blocking) or []
except Exception:
return _first_curated(curated, fallback_keys or (slug,)) or []
@@ -664,6 +684,8 @@ class _PickerBuild:
refresh: bool
excluded: set
curated: dict
+ # GUI read path: catalogs are read from cache only; stale/missing ones warm in the background.
+ non_blocking_catalogs: bool = False
results: list = field(default_factory=list)
seen_slugs: set = field(default_factory=set) # lowercase-normalized to catch case variants
# Effective base URLs of every built-in row: section 4 hides ``custom_providers`` duplicates.
@@ -788,7 +810,7 @@ def _lap_builtin_rows(b: _PickerBuild, data: dict, user_providers: dict) -> None
# LAUNCH profile's env-keyed providers and hid its own .env-keyed ones.
if not (_any_env(env_vars, _scoped_key_env) or _raw_pool_usable(hermes_id)):
continue
- model_ids = _live_or_curated_ids(hermes_id, b.curated)
+ model_ids = _live_or_curated_ids(hermes_id, b.curated, non_blocking=b.non_blocking_catalogs)
# A providers.<built-in>.models block extends the discovered catalog; section 3 cannot
# emit it later because this row owns the slug.
configured = user_providers.get(hermes_id) if isinstance(user_providers, dict) else None
@@ -871,9 +893,10 @@ def _lap_overlay_rows(b: _PickerBuild, data: dict) -> None:
# Live OAuth-backed discovery so Pro-only Codex slugs not in the static catalog
# appear; falls back to curated when unreachable.
from hermes_cli.models import cached_provider_model_ids
- model_ids = cached_provider_model_ids(hermes_slug)
+ model_ids = cached_provider_model_ids(hermes_slug, non_blocking=b.non_blocking_catalogs)
elif overlay.auth_type == "aws_sdk":
- model_ids = _aws_live_or_curated_ids(hermes_slug, b.curated, hermes_slug, pid)
+ model_ids = _aws_live_or_curated_ids(hermes_slug, b.curated, hermes_slug, pid,
+ non_blocking=b.non_blocking_catalogs)
elif hermes_slug == "nous":
# A guest identity never needs the Portal catalog: add_builtin_row pins nous/welcome
# (or drops the row when nous.guest is off), so only a real account fetches.
@@ -881,7 +904,8 @@ def _lap_overlay_rows(b: _PickerBuild, data: dict) -> None:
real_account = tier_row is not None and not tier_row["models"]
model_ids = _nous_picker_model_ids(b.curated, b.force_fresh_nous_tier) if real_account else []
else:
- model_ids = _live_or_curated_ids(hermes_slug, b.curated, hermes_slug, pid)
+ model_ids = _live_or_curated_ids(hermes_slug, b.curated, hermes_slug, pid,
+ non_blocking=b.non_blocking_catalogs)
b.add_builtin_row(
hermes_slug, get_label(hermes_slug), b.current_provider in (hermes_slug, pid), model_ids, "hermes")
b.seen_slugs.add(pid.lower())
@@ -911,9 +935,10 @@ def _lap_canonical_rows(b: _PickerBuild) -> None:
if not has_creds:
continue
if _is_aws_sdk(cp_config):
- model_ids = _aws_live_or_curated_ids(cp.slug, b.curated)
+ model_ids = _aws_live_or_curated_ids(cp.slug, b.curated, non_blocking=b.non_blocking_catalogs)
else:
- model_ids = _live_or_curated_ids(cp.slug, b.curated, merge_models_dev=False)
+ model_ids = _live_or_curated_ids(cp.slug, b.curated, merge_models_dev=False,
+ non_blocking=b.non_blocking_catalogs)
b.add_builtin_row(
cp.slug, cp.label, cp.slug == b.current_provider, model_ids, "canonical", uncapped_ok=False)
@@ -1086,9 +1111,11 @@ def _lap_custom_provider_rows(b: _PickerBuild, custom_providers: list) -> None:
section4_slugs.add(slug.lower())
-def _build_curated_lists(current_provider: str, current_base_url: str, current_model: str) -> dict[str, list[str]]:
+def _build_curated_lists(current_provider: str, current_base_url: str, current_model: str,
+ non_blocking: bool = False) -> dict[str, list[str]]:
"""Curated model lists keyed by hermes provider id, plus the dynamic ones (nous manifest,
- Ollama Cloud, LM Studio live probe)."""
+ Ollama Cloud, LM Studio live probe). ``non_blocking`` (GUI read path) takes cached Ollama Cloud
+ ids and warms them in the background rather than waiting on an 8s probe (#114215)."""
from hermes_cli.models import OPENROUTER_MODELS, _PROVIDER_MODELS, get_curated_nous_model_ids
curated: dict[str, list[str]] = dict(_PROVIDER_MODELS)
curated["openrouter"] = [mid for mid, _ in OPENROUTER_MODELS]
@@ -1096,10 +1123,17 @@ def _build_curated_lists(current_provider: str, current_base_url: str, current_m
curated["nous"] = get_curated_nous_model_ids()
if "ollama-cloud" not in curated:
from hermes_cli.models import fetch_ollama_cloud_models
- curated["ollama-cloud"] = fetch_ollama_cloud_models()
+ if non_blocking:
+ curated["ollama-cloud"] = fetch_ollama_cloud_models(cache_only=True)
+ if not curated["ollama-cloud"]: # nothing cached: warm for the next open, return now
+ _spawn_background_warm(fetch_ollama_cloud_models, cache_key="ollama-cloud")
+ else:
+ curated["ollama-cloud"] = fetch_ollama_cloud_models()
# LM Studio has no static catalog: probe its native endpoint live. Base URL precedence:
# LM_BASE_URL > active config base_url (when current) > default. On auth rejection /
# unreachable, fall back to the current model so the picker still shows something offline.
+ # Left live even on the non-blocking path: it is a loopback endpoint with a 1.5s timeout, so it
+ # cannot be the degraded remote provider this path must never wait on.
is_current_lmstudio = current_provider.strip().lower() == "lmstudio"
if "lmstudio" not in curated and (os.environ.get("LM_API_KEY") or os.environ.get("LM_BASE_URL") or is_current_lmstudio):
from hermes_cli.models_local import fetch_lmstudio_models
@@ -1123,7 +1157,8 @@ def list_authenticated_providers(
custom_providers: list | None = None, *, force_fresh_nous_tier: bool = False,
max_models: int | None = None, current_model: str = "", refresh: bool = False,
probe_custom_providers: bool = True, probe_current_custom_provider: bool = False,
- for_picker: bool = False, excluded_providers: list | None = None) -> List[dict]:
+ for_picker: bool = False, excluded_providers: list | None = None,
+ non_blocking_catalogs: bool = False) -> List[dict]:
"""Detect which providers have credentials and list their curated (not full models.dev) models.
Returns dicts with ``slug`` (the --provider value), ``name``, ``is_current``,
@@ -1132,14 +1167,22 @@ def list_authenticated_providers(
``force_fresh_nous_tier`` bypasses the short Nous tier cache (account-sensitive flows only);
``refresh`` busts the model-id disk cache up front (explicit user action only);
``probe_custom_providers`` enables live ``/models`` discovery for saved custom endpoints (CLI
- true, GUI false); ``probe_current_custom_provider`` probes only the selected custom endpoint."""
+ true, GUI false); ``probe_current_custom_provider`` probes only the selected custom endpoint.
+ ``non_blocking_catalogs`` is the GUI read path (``model.options``): provider catalogs come from
+ the disk cache only, stale/missing ones warm in the background, and rows still waiting on a
+ warm-up carry ``catalog_pending``. A degraded provider therefore never stalls the picker
+ (#114215)."""
+
from agent.models_dev import fetch_models_dev
from hermes_cli.config import coerce_provider_id, stringify_provider_map
+ non_blocking_catalogs = bool(non_blocking_catalogs)
+
# Explicit refresh: drop every cached list so the calls below re-fetch live. A stale cache
# can fall back to the curated static list when its live fetch fails, silently dropping
# live-only models the user had seen.
if refresh:
+ non_blocking_catalogs = False # an explicit refresh is allowed to block on live probes
try:
from hermes_cli.models import clear_provider_models_cache
clear_provider_models_cache()
@@ -1161,12 +1204,17 @@ def list_authenticated_providers(
max_models=max_models, for_picker=for_picker, force_fresh_nous_tier=force_fresh_nous_tier,
probe_custom_providers=probe_custom_providers, probe_current_custom_provider=probe_current_custom_provider,
refresh=refresh, excluded={str(p).strip().lower() for p in (excluded_providers or []) if p},
- curated=_build_curated_lists(current_provider, current_base_url, current_model))
+ non_blocking_catalogs=non_blocking_catalogs,
+ curated=_build_curated_lists(current_provider, current_base_url, current_model,
+ non_blocking=non_blocking_catalogs))
# Warm the disk cache in parallel before the serial section loops (otherwise 15-30s of live
# round-trips on a cold cache). Skipped when refresh=True (serial path force-refreshes) and
- # for <=3 providers (serial is fast enough; avoids thread-pool overhead).
- prefetch_slugs = [] if refresh else _collect_authed_provider_slugs(data, b.curated, excluded_providers or [])
+ # for <=3 providers (serial is fast enough; avoids thread-pool overhead). The GUI read path
+ # collects nothing either: every cache-only row read spawns its own deduped background refresh,
+ # so no thread pool is joined and no probe can hold up the response.
+ prefetch_slugs = ([] if (refresh or non_blocking_catalogs)
+ else _collect_authed_provider_slugs(data, b.curated, excluded_providers or []))
if len(prefetch_slugs) > 3:
try:
_prefetch_provider_models_parallel(prefetch_slugs)
@@ -1182,9 +1230,29 @@ def list_authenticated_providers(
_lap_bare_custom_row(b, custom_providers)
if custom_providers and isinstance(custom_providers, list):
_lap_custom_provider_rows(b, custom_providers)
+
+ if non_blocking_catalogs:
+ _mark_catalogs_pending(b.results)
+
return _finalize_picker_rows(b.results, user_providers, current_model)
+def _mark_catalogs_pending(rows: list) -> None:
+ """Flag rows whose catalog is still being warmed in the background (``catalog_pending``), so a
+ GUI knows an empty/short row is a not-yet-resolved state rather than that provider's catalog."""
+ try:
+ from hermes_cli.models import normalize_provider, provider_catalogs_refreshing
+ refreshing = provider_catalogs_refreshing()
+ except Exception:
+ return
+ if not refreshing:
+ return
+ for row in rows:
+ slug = str(row.get("slug") or "").strip().lower()
+ if slug and (normalize_provider(slug) or slug) in refreshing:
+ row["catalog_pending"] = True
+
+
def _finalize_picker_rows(results: list, user_providers, current_model: str) -> list:
"""Post-passes: drop ``providers.<name>.enabled: false`` rows, inject the current model, sort."""
# The enabled post-filter covers built-in rows (sections 1-2) that bypass the per-section
diff --git a/hermes_cli/models.py b/hermes_cli/models.py
index 37f8a85f4bb..ff410e1ffde 100644
--- a/hermes_cli/models.py
+++ b/hermes_cli/models.py
@@ -1562,7 +1562,10 @@ def _spawn_swr_refresh(cache_key: str, refresh_fn=None) -> None:
try:
entry = (refresh_fn or _default_refresh)()
if entry:
- _store_cache_entry(cache_key, entry)
+ # Under the write lock: the GUI read path spawns one of these per stale provider, so
+ # the plain load-modify-save would let concurrent warms drop each other's rows.
+ with _cache_write_lock:
+ _store_cache_entry(cache_key, entry)
except Exception:
logger.debug("SWR refresh failed for %s", cache_key, exc_info=True)
finally:
@@ -1574,6 +1577,14 @@ def _spawn_swr_refresh(cache_key: str, refresh_fn=None) -> None:
threading.Thread(target=lambda: ctx.run(_refresh), daemon=True, name=f"model-cache-swr-{cache_key}").start()
+def provider_catalogs_refreshing() -> set[str]:
+ """Slugs with a background catalog refresh in flight, for read paths that must mark which rows
+ are still warming (``catalog_pending``). Unscoped keys only — a routed profile's inflight key is
+ a (home, slug) tuple and reports nothing rather than the wrong slug."""
+ with _swr_refresh_lock:
+ return {key for key in _swr_refresh_inflight if isinstance(key, str)}
+
+
def _provider_models_cache_path() -> Path:
from hermes_constants import get_hermes_home
return get_hermes_home() / "provider_models_cache.json"
@@ -1704,9 +1715,14 @@ def _model_requires_account_discovery(provider: Optional[str], model: str) -> bo
def cached_provider_model_ids(
provider: Optional[str], *, force_refresh: bool = False,
- ttl_seconds: int = _PROVIDER_MODELS_CACHE_TTL) -> list[str]:
+ ttl_seconds: int = _PROVIDER_MODELS_CACHE_TTL, non_blocking: bool = False) -> list[str]:
"""Disk-cached :func:`provider_model_ids`: fresh cache hit, else live fetch persisting a non-empty
- result. Always returns a list."""
+ result. Always returns a list.
+
+ ``non_blocking`` marks the GUI read path (``model.options``): it NEVER waits on a provider probe.
+ A same-credentials row of any age is served as-is and a daemon thread warms the next open; a
+ cold/mismatched row returns ``[]`` so the caller keeps its curated list. One degraded provider
+ (hanging or timing-out ``/v1/models``) therefore delays nothing but itself (#114215)."""
normalized = _normalized_cache_slug(provider)
if not normalized:
return []
@@ -1730,6 +1746,16 @@ def cached_provider_model_ids(
_spawn_swr_refresh(normalized)
return list(entry["models"])
+ if non_blocking and not force_refresh:
+ # Read path: never touch the network in the caller's thread. A same-credentials row past the
+ # SWR window is still served (hour-old catalog beats an empty picker) while a daemon thread
+ # warms the next open; a cold row returns [] and the caller falls back to its curated list.
+ _spawn_swr_refresh(normalized)
+ if _cache_entry_valid(entry, fp, allow_empty=is_ollama):
+ return [model for model in entry["models"]
+ if not _model_requires_account_discovery(normalized, model)]
+ return []
+
live = provider_model_ids(normalized, force_refresh=force_refresh)
if live:
_store_cache_entry(normalized, _cache_entry(fp, live, now), cache)
diff --git a/hermes_cli/models_local.py b/hermes_cli/models_local.py
index 16e7457cefe..b11877f05f6 100644
--- a/hermes_cli/models_local.py
+++ b/hermes_cli/models_local.py
@@ -657,10 +657,11 @@ def fetch_ollama_cloud_models(
base_url: Optional[str] = None,
*,
force_refresh: bool = False,
+ cache_only: bool = False,
) -> list[str]:
"""Ollama Cloud models: fresh disk cache (< 1h, unless force_refresh) → live ``/v1/models``
(freshest) merged with models.dev additions (deduped, live first) → stale cache → ``[]``.
- Never None."""
+ ``cache_only`` (GUI read path) never runs the 8s network probe. Never None."""
from hermes_cli.models import fetch_api_models
if not force_refresh:
cached = _load_ollama_cloud_cache()
@@ -669,7 +670,9 @@ def fetch_ollama_cloud_models(
api_key = api_key or os.getenv("OLLAMA_API_KEY", "")
base_url = base_url or os.getenv("OLLAMA_BASE_URL", "") or "https://ollama.com/v1"
- live_models = (fetch_api_models(api_key, base_url, timeout=8.0) or []) if api_key else []
+ # cache_only (GUI read path): skip only the network probe. The models.dev additions are a local
+ # cache read, so the row still populates with what is known; the live catalog lands next open.
+ live_models = [] if cache_only else ((fetch_api_models(api_key, base_url, timeout=8.0) or []) if api_key else [])
mdev_models: list[str] = []
try:
from agent.models_dev import list_agentic_models
diff --git a/tests/hermes_cli/test_model_options_read_path_catalogs.py b/tests/hermes_cli/test_model_options_read_path_catalogs.py
new file mode 100644
index 00000000000..8841dc6f322
--- /dev/null
+++ b/tests/hermes_cli/test_model_options_read_path_catalogs.py
@@ -0,0 +1,160 @@
+"""``model.options`` is a READ path: opening the picker must not wait on a provider catalog probe.
+
+A normal open (``refresh=False``) used to run live ``/v1/models`` fetches inline — a cold cache
+serialized every authed provider and one degraded provider (hanging endpoint, failed auth probe)
+held the whole picker for as long as its probe took (#114215). The open now serves cached/curated
+rows, marks the ones still warming (``catalog_pending``) and refreshes them off-thread; only an
+explicit refresh (``refresh=True``, the "Refresh Models" action) is allowed to block on probes.
+"""
+
+import threading
+import time
+
+import hermes_cli.models as models_mod
+from hermes_cli.inventory import build_model_options_payload, load_picker_context
+
+_DEAD_PROVIDER = "deepseek"
+
+
+def _picker_env(monkeypatch, tmp_path, *, hung=None):
+ """One authed provider visible to the picker, no real network, isolated model-id cache.
+
+ ``hung`` is a slug whose probe blocks on the returned event — a stand-in for a degraded
+ provider. Returns ``(live_calls, release_event)``; ``live_calls`` records
+ ``(provider, thread_name)`` for every live probe.
+ """
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setenv("DEEPSEEK_API_KEY", "test-key")
+ release = threading.Event()
+ live_calls: list[tuple[str, str]] = []
+
+ def fake_provider_model_ids(provider, *, force_refresh=False):
+ live_calls.append((provider, threading.current_thread().name))
+ if provider == hung:
+ release.wait(30)
+ return ["live-model"]
+
+ monkeypatch.setattr(models_mod, "provider_model_ids", fake_provider_model_ids)
+ monkeypatch.setattr(
+ "agent.models_dev.fetch_models_dev",
+ lambda *a, **k: {_DEAD_PROVIDER: {"env": ["DEEPSEEK_API_KEY"], "name": "DeepSeek"}},
+ )
+ monkeypatch.setattr("agent.models_dev.PROVIDER_TO_MODELS_DEV", {_DEAD_PROVIDER: _DEAD_PROVIDER})
+ monkeypatch.setattr("hermes_cli.providers.HERMES_OVERLAYS", {})
+ return live_calls, release
+
+
+def _drain_background_warms(timeout=10.0) -> None:
+ """Let spawned catalog warms finish so a tmp HERMES_HOME can be torn down with no writers left."""
+ refreshing = getattr(models_mod, "provider_catalogs_refreshing", None)
+ if refreshing is None: # pre-fix builds have no inflight registry to consult
+ time.sleep(0.3)
+ return
+ deadline = time.time() + timeout
+ while time.time() < deadline and refreshing():
+ time.sleep(0.02)
+
+
+def _row(payload, slug):
+ return next((row for row in payload["providers"] if row["slug"] == slug), None)
+
+
+def test_normal_open_never_probes_in_the_calling_thread(monkeypatch, tmp_path):
+ """The open returns without running one live catalog fetch on the caller: rows come from the
+ disk cache / curated list and rows still warming say so."""
+ live_calls, _ = _picker_env(monkeypatch, tmp_path)
+
+ payload = build_model_options_payload(load_picker_context())
+
+ caller_thread = threading.current_thread().name
+ assert [call for call in live_calls if call[1] == caller_thread] == []
+ row = _row(payload, _DEAD_PROVIDER)
+ assert row is not None, "the provider must still be offered from its cached/curated list"
+ assert "live-model" not in row["models"]
+ _drain_background_warms()
+
+
+def test_degraded_provider_cannot_stall_the_open(monkeypatch, tmp_path):
+ """One provider whose probe hangs must not hold the picker: the payload comes back while the
+ probe is still in flight. (Pre-fix this assertion only ever ran after the probe returned.)"""
+ live_calls, release = _picker_env(monkeypatch, tmp_path, hung=_DEAD_PROVIDER)
+
+ box: dict = {}
+
+ def _open():
+ box["payload"] = build_model_options_payload(load_picker_context())
+
+ opener = threading.Thread(target=_open, daemon=True)
+ opener.start()
+ opener.join(timeout=15)
+ returned_while_hung = "payload" in box
+ release.set() # never leave the probe hanging, whatever the outcome
+ opener.join(timeout=15)
+ _drain_background_warms()
+
+ assert returned_while_hung, "the open waited on a degraded provider's catalog probe"
+ row = _row(box["payload"], _DEAD_PROVIDER)
+ assert isinstance(row, dict), "the degraded row must still render"
+ assert row.get("catalog_pending") is True, "a row whose catalog is still warming must say so"
+ assert live_calls, "the degraded provider is still probed — off the read path"
+ _drain_background_warms()
+
+
+def test_explicit_refresh_still_probes_providers(monkeypatch, tmp_path):
+ """``refresh=True`` is the explicit "Refresh Models" action: it is allowed to run live probes."""
+ live_calls, _ = _picker_env(monkeypatch, tmp_path)
+
+ payload = build_model_options_payload(load_picker_context(), refresh=True)
+
+ assert live_calls, "an explicit refresh must still probe provider catalogs"
+ row = _row(payload, _DEAD_PROVIDER)
+ assert row is not None
+ assert "live-model" in row["models"]
+ assert not row.get("catalog_pending")
+ _drain_background_warms()
+
+
+def test_non_blocking_cache_read_serves_stale_entry_and_warms(monkeypatch, tmp_path):
+ """Beyond the stale-serve window a non-blocking read still returns the cached row (rather than
+ blocking on a probe) and kicks off the off-thread refresh."""
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ started = threading.Event()
+ release = threading.Event()
+
+ def fake_provider_model_ids(provider, *, force_refresh=False):
+ started.set()
+ release.wait(15)
+ return ["live-model"]
+
+ monkeypatch.setattr(models_mod, "provider_model_ids", fake_provider_model_ids)
+ models_mod._store_cache_entry(
+ _DEAD_PROVIDER,
+ {"fp": models_mod._credential_fingerprint(_DEAD_PROVIDER),
+ "at": time.time() - (models_mod._PROVIDER_MODELS_STALE_SERVE_MAX + 60),
+ "models": ["cached-model"]},
+ )
+
+ try:
+ served = models_mod.cached_provider_model_ids(_DEAD_PROVIDER, non_blocking=True)
+ assert served == ["cached-model"]
+ assert started.wait(10), "the stale row must be refreshed off-thread"
+ finally:
+ release.set()
+ _drain_background_warms()
+
+
+def test_warm_cache_open_is_served_from_disk_without_probing(monkeypatch, tmp_path):
+ """A fresh cache entry means the next open runs no probe at all and marks nothing pending.
+
+ ``_credential_fingerprint`` is pinned: any write to ``auth.json`` during a build (credential-pool
+ seeding) legitimately changes it, which would make this test race its own background warms."""
+ live_calls, _ = _picker_env(monkeypatch, tmp_path)
+ monkeypatch.setattr(models_mod, "_credential_fingerprint", lambda provider: "pinned")
+ build_model_options_payload(load_picker_context())
+ _drain_background_warms() # first open warmed the disk cache
+ live_calls.clear()
+
+ payload = build_model_options_payload(load_picker_context())
+
+ assert live_calls == []
+ assert not _row(payload, _DEAD_PROVIDER).get("catalog_pending")
diff --git a/tui_gateway/contracts/config_free_tier_control.py b/tui_gateway/contracts/config_free_tier_control.py
index afe5a22cb65..1a7c2cef085 100644
--- a/tui_gateway/contracts/config_free_tier_control.py
+++ b/tui_gateway/contracts/config_free_tier_control.py
@@ -269,6 +269,8 @@ class ModelOptionProvider(OpenModel):
free_tier_pending: bool | None = None
free_tier_row: bool | None = None
unavailable_models: list[str] | None = None
+ # Set on a normal picker open while this row's catalog is still warming in the background.
+ catalog_pending: bool | None = None
class ModelOptionsResult(Result):