The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(dashboard): custom endpoint validation persists the base URL that served /models (#65488)
teknium1859c883ce57b
diff --git a/apps/desktop/src/api/config.ts b/apps/desktop/src/api/config.tsindex bd64712cbd2..0de58dbda28 100644--- a/apps/desktop/src/api/config.ts+++ b/apps/desktop/src/api/config.ts@@ -162,8 +162,8 @@ export function validateProviderCredential(key: string,value: string,apiKey?: string-): Promise<{ ok: boolean; reachable: boolean; message: string; models?: string[] }> {- return hermesApi<{ ok: boolean; reachable: boolean; message: string; models?: string[] }>({+): Promise<{ ok: boolean; reachable: boolean; message: string; models?: string[]; resolved_base_url?: string }> {+ return hermesApi<{ ok: boolean; reachable: boolean; message: string; models?: string[]; resolved_base_url?: string }>({...profileScoped(),path: '/api/providers/validate',method: 'POST',diff --git a/apps/desktop/src/app/settings/custom-endpoints-settings.tsx b/apps/desktop/src/app/settings/custom-endpoints-settings.tsxindex 6259c73f425..f382d7da6db 100644--- a/apps/desktop/src/app/settings/custom-endpoints-settings.tsx+++ b/apps/desktop/src/app/settings/custom-endpoints-settings.tsx@@ -181,10 +181,19 @@ export function CustomEndpointsSettings({ onConfigSaved, onMainModelChanged }: CsetDiscoveredModels(response.models)if (response.ok) {+ // Persist the URL that actually served /models (e.g. "<root>/v1" when the user typed the+ // bare root): chat POSTs {base_url}/chat/completions verbatim, so saving the typed root+ // would 404 every request even though the test looked green (#65488).+ const resolvedBaseUrl = response.resolved_base_url?.trim()+if (!form.model && response.models[0]) {setForm(current => ({ ...current, model: response.models[0] }))}+ if (resolvedBaseUrl && resolvedBaseUrl !== form.baseUrl.trim().replace(/\/+$/, '')) {+ setForm(current => ({ ...current, baseUrl: resolvedBaseUrl }))+ }+notify({kind: 'success',message: response.models.lengthdiff --git a/apps/desktop/src/store/onboarding.ts b/apps/desktop/src/store/onboarding.tsindex 8225d3c23d6..47d7505e024 100644--- a/apps/desktop/src/store/onboarding.ts+++ b/apps/desktop/src/store/onboarding.ts@@ -1102,6 +1102,10 @@ export async function saveOnboardingLocalEndpoint(baseUrl: string, apiKey: strin// the endpoint is up; an unreachable probe hard-blocks because we can't// resolve a model to route to.let model = ''+ // The probe tries the URL as entered and its /v1 variant; persist the one that answered —+ // the runtime POSTs {base_url}/chat/completions verbatim, so a bare host root that only+ // "detected" via /v1/models would 404 every chat (#65488).+ let resolvedUrl = urltry {const probe = await validateProviderCredential('OPENAI_BASE_URL', url, key)@@ -1119,6 +1123,7 @@ export async function saveOnboardingLocalEndpoint(baseUrl: string, apiKey: strin}model = (probe.models?.[0] ?? '').trim()+ resolvedUrl = probe.resolved_base_url?.trim() || url} catch {return { ok: false, message: `Could not reach ${url}.` }}@@ -1131,7 +1136,7 @@ export async function saveOnboardingLocalEndpoint(baseUrl: string, apiKey: strin}try {- await setMainModelAssignment({ provider: 'custom', model, base_url: url, api_key: key }, ctx.profile)+ await setMainModelAssignment({ provider: 'custom', model, base_url: resolvedUrl, api_key: key }, ctx.profile)if (generation !== flowGeneration) {return { ok: false }@@ -1152,7 +1157,7 @@ export async function saveOnboardingLocalEndpoint(baseUrl: string, apiKey: strinif (!runtime.ready) {const detail = (runtime.reason ?? '').trim()- return { ok: false, message: detail || `Saved, but Hermes still cannot reach ${url}.` }+ return { ok: false, message: detail || `Saved, but Hermes still cannot reach ${resolvedUrl}.` }}notifyReady('Local / custom endpoint')diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.tsindex aee88d03679..0773ab74d55 100644--- a/apps/desktop/src/types/hermes.ts+++ b/apps/desktop/src/types/hermes.ts@@ -263,6 +263,8 @@ export interface CustomEndpointValidationResponse {models: string[]ok: booleanreachable: boolean+ // Base URL that actually served /models (the entered URL or its /v1 variant); persist this one.+ resolved_base_url?: string}export interface MessagingEnvVarInfo {diff --git a/hermes_cli/web_routers/config_env.py b/hermes_cli/web_routers/config_env.pyindex d53b0e421cc..1c2a8d341a5 100644--- a/hermes_cli/web_routers/config_env.py+++ b/hermes_cli/web_routers/config_env.py@@ -714,23 +714,42 @@ async def validate_custom_endpoint(body: CustomEndpointUpdate):if not base_url:return {"ok": False, "reachable": True, "message": "Enter an endpoint URL first.", "models": []}- url = base_url + "/models"headers = {"Accept": "application/json"}if body.api_key and body.api_key.strip():headers["Authorization"] = f"Bearer {body.api_key.strip()}"- try:- async with _endpoint_probe_client(url, 8.0) as client:- resp = await client.get(url, headers=headers)- except Exception:- return {"ok": False, "reachable": False, "message": f"Could not reach {url}.", "models": []}+ resolved, resp = await _probe_openai_compatible_models(base_url, headers)+ if resp is None:+ return {"ok": False, "reachable": False, "message": f"Could not reach {base_url}/models.", "models": []}if resp.status_code in (401, 403):return {"ok": False, "reachable": True, "message": "The endpoint rejected the API key.", "models": []}if not resp.is_success:return {"ok": False, "reachable": True, "message": f"Endpoint returned HTTP {resp.status_code}.", "models": []}- return {"ok": True, "reachable": True, "message": "", "models": _parse_model_ids(resp)}+ return {"ok": True, "reachable": True, "message": "", "models": _parse_model_ids(resp), "resolved_base_url": resolved}+++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 the+ first answers a non-success. Returns ``(resolved_base_url, response)`` — the base that served the+ model list is what the caller must PERSIST: the runtime appends ``/chat/completions`` to the saved+ URL verbatim, so a bare host root that only "detected" via ``/v1/models`` would 404 every chat+ (#65488). ``response`` is None when no candidate could be reached at all."""+ base = base_url.rstrip("/")+ alternate = base[:-3].rstrip("/") if base.lower().endswith("/v1") else base + "/v1"+ resolved, resp = base, None+ async with _endpoint_probe_client(base, 8.0) as client:+ for candidate in (base, alternate):+ try:+ candidate_resp = await client.get(candidate + "/models", headers=headers)+ except Exception:+ continue+ if resp is None or candidate_resp.is_success:+ resolved, resp = candidate, candidate_resp+ if candidate_resp.is_success:+ break+ return resolved, respdef _endpoint_probe_client(url: str, timeout: float):@@ -766,20 +785,18 @@ async def validate_provider_credential(body: EnvVarUpdate, request: Request):# default. The optional API key is sent so servers that require auth on# ``/v1/models`` still enumerate instead of returning an empty list.if key == "OPENAI_BASE_URL":- url = value.rstrip("/") + "/models"api_key = (body.api_key or "").strip()headers = {"Authorization": f"Bearer {api_key}"} if api_key else None- try:- async with _endpoint_probe_client(url, 8.0) as client:- resp = await client.get(url, headers=headers)- except Exception:+ resolved, resp = await _probe_openai_compatible_models(value, headers)+ url = resolved + "/models"+ if resp is None:return {"ok": False, "reachable": False, "message": f"Could not reach {url}."}models = _parse_model_ids(resp)if not models and not resp.is_success:# A proxy/gateway error page parses as "no models"; name the status instead so the# GUI does not tell the user to "start a model" on a server that answered.return {"ok": False, "reachable": True, "message": f"{url} answered HTTP {resp.status_code}.", "models": []}- return {"ok": True, "reachable": True, "message": "", "models": models}+ return {"ok": True, "reachable": True, "message": "", "models": models, "resolved_base_url": resolved}probe = _CREDENTIAL_PROBES.get(key)if not probe:diff --git a/tests/hermes_cli/test_web_routers_endpoint_probe.py b/tests/hermes_cli/test_web_routers_endpoint_probe.pyindex 2b302428643..aecb490bf63 100644--- a/tests/hermes_cli/test_web_routers_endpoint_probe.py+++ b/tests/hermes_cli/test_web_routers_endpoint_probe.py@@ -64,3 +64,45 @@ def test_openai_base_url_probe_names_the_http_status_instead_of_no_models(monkeyassert out["ok"] is False and out["reachable"] is Trueassert "HTTP 502" in out["message"]++[email protected]("route", ["/api/providers/validate", "/api/providers/custom-endpoints/validate"])+def test_bare_root_probe_resolves_to_the_v1_base_that_served_models(route, monkeypatch):+ """A custom endpoint typed without ``/v1`` (#65488): the probe must fall through to+ ``{base}/v1/models`` AND report that base as ``resolved_base_url`` so the Desktop persists a URL+ the runtime can POST ``/chat/completions`` to — detection green + every chat 404 is the bug."""+ import hermes_cli.web_routers.config_env as mod+ from hermes_cli.web_models import CustomEndpointUpdate, EnvVarUpdate++ class _Resp:+ def __init__(self, status):+ self.status_code, self.is_success = status, status == 200++ def json(self):+ return {"data": [{"id": "local-model"}]} if self.is_success else {"error": "Unexpected endpoint"}++ seen = []++ class _Client:+ async def __aenter__(self):+ return self++ async def __aexit__(self, *a):+ return False++ async def get(self, url, *a, **k):+ seen.append(url)+ return _Resp(200 if url.endswith("/v1/models") else 404)++ monkeypatch.setattr(mod, "_endpoint_probe_client", lambda url, timeout: _Client())+ monkeypatch.setattr(mod, "_require_token", lambda request: None)+ if route == "/api/providers/validate":+ body = EnvVarUpdate(key="OPENAI_BASE_URL", value="http://127.0.0.1:39080/", api_key="")+ data = asyncio.run(mod.validate_provider_credential(body, request=None))+ else:+ body = CustomEndpointUpdate(id="", name="local", base_url="http://127.0.0.1:39080/", api_key="", model="")+ data = asyncio.run(mod.validate_custom_endpoint(body))++ assert seen == ["http://127.0.0.1:39080/models", "http://127.0.0.1:39080/v1/models"]+ assert data["ok"] is True and data["models"] == ["local-model"]+ assert data["resolved_base_url"] == "http://127.0.0.1:39080/v1"diff --git a/tests/hermes_cli/test_web_server.py b/tests/hermes_cli/test_web_server.pyindex 148909e5877..022e8674bf6 100644--- a/tests/hermes_cli/test_web_server.py+++ b/tests/hermes_cli/test_web_server.py@@ -5243,6 +5243,7 @@ class TestValidateProviderCredential:"reachable": True,"message": "","models": ["local-model"],+ "resolved_base_url": "http://localhost:8000/v1",}assert captured == {"url": "http://localhost:8000/v1/models",diff --git a/website/docs/user-guide/local-models.md b/website/docs/user-guide/local-models.mdindex a2202cd89df..9f379aeec1f 100644--- a/website/docs/user-guide/local-models.md+++ b/website/docs/user-guide/local-models.md@@ -102,7 +102,10 @@ models** section on the same page searches all of Hugging Face:If a llama-server is already running on your machine, Hermes detects itand uses it instead of starting its own. Point a custom endpoint at anyOpenAI-compatible server for full manual control — the managed runtime is-a default, not a requirement. For manual setups (Ollama, MLX, custom+a default, not a requirement. You can enter the server root (for example+`http://127.0.0.1:8080`) or the full `/v1` URL: the endpoint test tries+both and saves the variant that actually served `/models`, so chat+requests go to the same prefix the model list came from. For manual setups (Ollama, MLX, custombuilds, headless CLI machines), see[Run Hermes Locally with Ollama](../guides/local-ollama-setup.md) and[Run Local LLMs on Mac](../guides/local-llm-on-mac.md).