The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(web): custom endpoint Test requires a JSON models reply
Austin Pickette9357f0b5cad
diff --git a/hermes_cli/web_routers/config_env.py b/hermes_cli/web_routers/config_env.pyindex 09f5946854e..2f94f063209 100644--- a/hermes_cli/web_routers/config_env.py+++ b/hermes_cli/web_routers/config_env.py@@ -871,6 +871,14 @@ async def validate_custom_endpoint(body: CustomEndpointUpdate):# alias metadata (``canonical_model`` / ``reasoning_effort``) the id list flattens.entries = _parse_model_entries(resp)ids = [e["id"] for e in entries]+ if not ids:+ # A 200 that parses to zero models is the SPA-catch-all signature (#83128): a real+ # OpenAI-compatible /models answers JSON with a usable list. ``_parse_model_entries``+ # is lenient by design, so classify the empty result here instead of reporting+ # success. ok:false + reachable:true is a warning in the UI — Save stays possible+ # for endpoints that legitimately expose no model list.+ return {"ok": False, "reachable": True, "message": _no_models_probe_message(resp, resolved),+ "models": [], "model_details": [], "resolved_base_url": resolved}# /models answering proves nothing about the transport the runtime will POST to:# a Responses-only host lists models fine and 404s every /chat/completions (#93622).# Probe the route the saved mode (or the runtime's URL auto-detect) actually uses, on the@@ -889,6 +897,30 @@ async def validate_custom_endpoint(body: CustomEndpointUpdate):result.update(ok=False, message=missing)return result+def _no_models_probe_message(resp: Any, base_url: str) -> str:+ """Why a 200 ``/models`` probe yielded no usable models (#83128).++ Distinguishes the three ways that happens — a non-JSON body (an SPA catch-all serves+ HTML for every route, so 200 proves nothing), a JSON body without a model list, and a+ genuinely empty list — mirroring the onboarding store's wording for the last case.+ """+ url = base_url + "/models"+ content_type = (resp.headers.get("content-type") or "").split(";")[0].strip()+ try:+ payload = resp.json()+ except ValueError: # json.JSONDecodeError — a non-JSON body (HTML, plain text) is the case being named+ payload = None+ if not isinstance(payload, (dict, list)):+ kind = content_type or "a non-JSON body"+ return (f"Connected to {url}, but it returned {kind} instead of a JSON model list — "+ "the URL may be an SPA catch-all or a wrong base URL, not an OpenAI-compatible API.")+ data = payload.get("data") if isinstance(payload, dict) else payload+ if not isinstance(data, list):+ return f"Connected to {url}, but its response is not an OpenAI-compatible model list."+ return (f"Connected to {url}, but it advertised no models. "+ "Start a model on that endpoint and try again.")++async def _probe_openai_compatible_models(base_url: str, headers: Optional[dict]) -> Tuple[str, Any]:"""GET ``{base}/models``, then ``{base}/v1/models`` (or the ``/v1``-stripped variant) when thefirst answers a non-success. Returns ``(resolved_base_url, response)`` — the base that served thediff --git a/tests/hermes_cli/test_web_routers_endpoint_probe.py b/tests/hermes_cli/test_web_routers_endpoint_probe.pyindex 86a4530d42b..0c4fa1e8c72 100644--- a/tests/hermes_cli/test_web_routers_endpoint_probe.py+++ b/tests/hermes_cli/test_web_routers_endpoint_probe.py@@ -143,3 +143,79 @@ def test_bare_root_probe_reports_the_v1_key_rejection_not_the_root_404(route, modata = asyncio.run(mod.validate_custom_endpoint(body))assert data["ok"] is False and data["reachable"] is Trueassert "404" not in data["message"]+++def _models_probe_host(monkeypatch, content_type, body):+ """A custom-endpoint ``/models`` probe answering 200 with the given body/content type.+ The transport POST answers 200 too — an SPA catch-all serves every route, so the+ transport probe alone cannot catch it."""+ import hermes_cli.web_routers.config_env as mod++ class _Resp:+ status_code = 200+ is_success = True+ headers = {"content-type": content_type}++ def json(self):+ if isinstance(body, str):+ raise ValueError("Expecting value: not JSON")+ return body++ class _Client:+ async def __aenter__(self):+ return self++ async def __aexit__(self, *a):+ return False++ async def get(self, url, *a, **k):+ return _Resp()++ async def post(self, url, *a, **k):+ return _Resp()++ monkeypatch.setattr(mod, "_endpoint_probe_client", lambda url, timeout: _Client())+++ "name, content_type, body, needle",+ [+ ("spa_html", "text/html", "<html><body><div id=root></div></body></html>", "text/html"),+ ("non_json_body", "text/plain", "OK", "instead of a JSON model list"),+ ("empty_model_list", "application/json", {"data": []}, "advertised no models"),+ ],+)+def test_custom_endpoint_probe_warns_when_no_models_parse(name, content_type, body, needle, monkeypatch):+ """A 200 ``/models`` answer is only a pass when it is JSON with a usable model list: an SPA+ catch-all (200 + HTML), a non-JSON body, or an empty list must be ``ok:false`` with a+ message naming the cause, not a green check (#83128)."""+ import hermes_cli.web_routers.config_env as mod+ from hermes_cli.web_models import CustomEndpointUpdate++ _models_probe_host(monkeypatch, content_type, body)+ req = CustomEndpointUpdate(id="", name="x", base_url="https://spa.example.com/v1",+ api_key="", model="")+ data = asyncio.run(mod.validate_custom_endpoint(req))++ assert data["ok"] is False, name+ assert data["reachable"] is True, name # warning, not a hard block: Save stays possible+ assert needle in data["message"], (name, data["message"])+ assert "https://spa.example.com/v1" in data["message"], name+ assert data["models"] == [], name+++def test_custom_endpoint_probe_passes_on_a_json_models_reply(monkeypatch):+ """A genuine OpenAI-compatible reply (200, JSON, ``{"data": [...]}``) still passes — the+ no-models guard classifies only empty/unparseable answers, never honest ones."""+ import hermes_cli.web_routers.config_env as mod+ from hermes_cli.web_models import CustomEndpointUpdate++ _models_probe_host(monkeypatch, "application/json",+ {"data": [{"id": "gpt-4o"}, {"id": "gpt-4o-mini"}], "object": "list"})+ req = CustomEndpointUpdate(id="", name="x", base_url="https://api.example.com/v1",+ api_key="", model="")+ data = asyncio.run(mod.validate_custom_endpoint(req))++ assert data["ok"] is True and data["reachable"] is True+ assert data["models"] == ["gpt-4o", "gpt-4o-mini"]+ assert data["message"] == ""