The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): route a session with no provider to setup, not a dead-end toast
rodricksz4h5961c79220a0d
diff --git a/agent/agent_init.py b/agent/agent_init.pyindex 5e00a582dc8..60997e229c1 100644--- a/agent/agent_init.py+++ b/agent/agent_init.py@@ -927,11 +927,12 @@ def _routed_client_kwargs(agent, fallback_model, _provider_timeout) -> Optional[raise ProviderCredentialsExhaustedError(_exhausted_message, provider=_explicit)if _explicit and _explicit not in {"auto", "openrouter", "custom"}:# Explicit non-OpenRouter provider with no creds and no usable fallback: fail fast.- from agent.auxiliary_unavailable import missing_provider_credentials_message- raise RuntimeError(missing_provider_credentials_message(_explicit))+ from agent.auxiliary_unavailable import ProviderNotConfiguredError, missing_provider_credentials_message+ raise ProviderNotConfiguredError(missing_provider_credentials_message(_explicit))from hermes_constants import profile_cli_selector+ from agent.auxiliary_unavailable import ProviderNotConfiguredError_sel = profile_cli_selector()- raise RuntimeError(+ raise ProviderNotConfiguredError("No LLM provider configured. Run `hermes model` to ""select a provider, or run `hermes setup` for first-time ""configuration."diff --git a/agent/auxiliary_unavailable.py b/agent/auxiliary_unavailable.pyindex 9eac20412de..b1c180d59ea 100644--- a/agent/auxiliary_unavailable.py+++ b/agent/auxiliary_unavailable.py@@ -177,6 +177,17 @@ def pool_billing_message()+class ProviderNotConfiguredError(RuntimeError):+ """Agent init found no usable inference provider: nothing is configured, or the explicitly+ configured one has no credentials.++ A distinct type because the remedy is setup, not a retry: clients route it to their provider+ setup / onboarding flow. The wording of the two messages has changed more than once, so a+ client that recognises this failure by matching their text silently stops routing (#119232's+ sibling); the type and the gateway's ``code`` survive rewording.+ """++def missing_provider_credentials_message(provider_id: str) -> str:"""The "Provider 'X' is set in config.yaml but …" error for an explicit provider with no credentials.diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/status.test.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/status.test.tsindex 66ba33a7e5c..f6f493d0465 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/status.test.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/status.test.ts@@ -6,6 +6,7 @@import { afterEach, describe, expect, it, vi } from 'vitest'import { $notifications } from '@/store/notifications'+import { requestDesktopOnboarding } from '@/store/onboarding'import { handleStatusEvent } from './status'import type { GatewayEventContext } from './types'@@ -17,9 +18,9 @@ const OWNED_REFUSAL ='Session 20260909_095312_6b93f5 already has a live owner (tui, pid 32977, lease age 22m). ' +'Attach through a compatible owner, or close the session in its owning surface before resuming here.'-function errorContext(message: string) {+function errorContext(message: string, code?: string) {const failAssistantMessage = vi.fn()- const payload = { message } as GatewayEventContext['payload']+ const payload = { code, message } as GatewayEventContext['payload']const ctx: GatewayEventContext = {deps: {@@ -46,6 +47,7 @@ function errorContext(message: string) {afterEach(() => {$notifications.set([])+ vi.mocked(requestDesktopOnboarding).mockClear()})describe('gateway `error` event → error card + toast', () => {@@ -75,6 +77,26 @@ describe('gateway `error` event → error card + toast', () => {expect(toast.action).toBeUndefined()})+ it('routes a blank install to onboarding on the gateway code, whatever the sentence says', () => {+ // agent init with no usable provider: the gateway stamps code=provider_not_configured+ // (tui_gateway/server.py). The fix for this chat is setup, so the user must land there and+ // not on a toast — even after the sentence is reworded again.+ const { ctx } = errorContext('Hermes could not start the assistant. Details: something new we never matched.',+ 'provider_not_configured')++ handleStatusEvent(ctx)++ expect(requestDesktopOnboarding).toHaveBeenCalledTimes(1)+ })++ it('does not route an unrelated failure to onboarding', () => {+ const { ctx } = errorContext('Hermes could not finish this turn. Try again.')++ handleStatusEvent(ctx)++ expect(requestDesktopOnboarding).not.toHaveBeenCalled()+ })+it("keeps the server's own plain copy as the toast message when no code was recovered", () => {// tui_gateway/user_messages.py already writes actionable sentences for// pre-turn failures; the generic "couldn't finish" gloss must not bury them.diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/status.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/status.tsindex 2bf40b9d935..bd21962032e 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/status.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/status.ts@@ -4,7 +4,7 @@ import { textPart } from '@/lib/chat-messages'import { coerceGatewayText } from '@/lib/chat-runtime'import type { ErrorSurface } from '@/lib/error-surface'import { errorCardText } from '@/lib/error-surface-copy'-import { isProviderSetupErrorMessage } from '@/lib/provider-setup-errors'+import { isProviderSetupErrorCode, isProviderSetupErrorMessage } from '@/lib/provider-setup-errors'import { type AgentNoticePayload, clearAgentNotice, nativeNoticeInput, showAgentNotice } from '@/store/agent-notices'import { clearSettledClarifyRequest } from '@/store/clarify'import { reconcileSessionCompacting, setSessionCompacting, takeCompressDeferred } from '@/store/compaction'@@ -280,7 +280,11 @@ export function handleStatusEvent(ctx: GatewayEventContext): boolean {if (event.type === 'error') {const errorMessage = payload?.message || 'Hermes reported an error'- const looksLikeProviderSetup = isProviderSetupErrorMessage(errorMessage)++ // The gateway's own verdict when it sent one (agent init with no usable provider), else the+ // sentence: a blank install must reach onboarding, not a toast it cannot act on.+ const looksLikeProviderSetup =+ isProviderSetupErrorCode(payload?.code) || isProviderSetupErrorMessage(errorMessage)// The gateway's `error` event carries no error_surface (prompt_turn.py// emits it for pre-turn refusals). Recover the two codes it CAN mean fromdiff --git a/apps/desktop/src/lib/chat-messages/types.ts b/apps/desktop/src/lib/chat-messages/types.tsindex d6a23486aa0..337832cfa8a 100644--- a/apps/desktop/src/lib/chat-messages/types.ts+++ b/apps/desktop/src/lib/chat-messages/types.ts@@ -101,6 +101,10 @@ export type GatewayEventPayload = {result?: unknownsummary?: stringerror?: string | boolean+ // error — the gateway's machine-readable cause, when it has one (currently+ // "provider_not_configured" from a failed agent init). Absent on older+ // gateways; consumers must fall back to string heuristics.+ code?: string// message.complete with status "error" — structured {layer, code, retryable}// descriptor naming which stack layer failed (agent/error_surface.py).// Absent on older gateways; consumers must fall back to string heuristics.diff --git a/apps/desktop/src/lib/provider-setup-errors.test.ts b/apps/desktop/src/lib/provider-setup-errors.test.tsindex 6014cee46b7..a594801e9d4 100644--- a/apps/desktop/src/lib/provider-setup-errors.test.ts+++ b/apps/desktop/src/lib/provider-setup-errors.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest'-import { isProviderSetupErrorMessage } from './provider-setup-errors'+import { isProviderSetupErrorCode, isProviderSetupErrorMessage } from './provider-setup-errors'describe('isProviderSetupErrorMessage', () => {it('matches generic missing-provider copy', () => {@@ -12,6 +12,35 @@ describe('isProviderSetupErrorMessage', () => {expect(isProviderSetupErrorMessage('set an API key (OPENROUTER_API_KEY) in ~/.hermes/.env')).toBe(true)})+ it('matches what agent init actually says on a blank install', () => {+ // tui_gateway/user_messages.py::agent_init_failed_message wrapping agent/agent_init.py's raise.+ expect(+ isProviderSetupErrorMessage(+ 'Hermes could not start the assistant for this session. Details: No LLM provider configured. Run `hermes model` to select a provider, or run `hermes setup` for first-time configuration. Check the model and provider with /model, or run `hermes setup` in a terminal to reconfigure.'+ )+ ).toBe(true)+ })++ it('matches an explicit provider that has no credentials', () => {+ // agent/auxiliary_unavailable.py::missing_provider_credentials_message, both shapes.+ expect(+ isProviderSetupErrorMessage(+ "Provider 'openai' is set in config.yaml but no API key was found. Set the OPENAI_API_KEY environment variable, or switch to a different provider with `hermes model`."+ )+ ).toBe(true)+ expect(+ isProviderSetupErrorMessage(+ "Provider 'anthropic' is set in config.yaml but no credentials were found. Run `hermes auth add anthropic` to sign in, or switch to a different provider with `hermes model`."+ )+ ).toBe(true)+ })++ it('reads the gateway code in preference to any sentence', () => {+ expect(isProviderSetupErrorCode('provider_not_configured')).toBe(true)+ expect(isProviderSetupErrorCode('disk_full')).toBe(false)+ expect(isProviderSetupErrorCode(undefined)).toBe(false)+ })+it('matches the exact empty-key warning emitted in session.info', () => {expect(isProviderSetupErrorMessage("No API key configured for provider 'openrouter'. First message will fail.")diff --git a/apps/desktop/src/lib/provider-setup-errors.ts b/apps/desktop/src/lib/provider-setup-errors.tsindex 81a63356a29..fbdf4905536 100644--- a/apps/desktop/src/lib/provider-setup-errors.ts+++ b/apps/desktop/src/lib/provider-setup-errors.ts@@ -1,8 +1,20 @@+// Fallback for gateways that send no `code` on the error event. Every alternative here is a+// sentence the backend actually produces today: `agent_init` raises "No LLM provider configured"+// on a blank install and `missing_provider_credentials_message()` the "is set in config.yaml+// but …" form, and both arrive wrapped in `agent_init_failed_message()`. Matching is by the+// noun phrase, never the surrounding wording, and deliberately NOT by "provider configured"+// alone: the auxiliary-model warning says "No auxiliary LLM provider configured" and is not a+// provider-setup failure.const PROVIDER_SETUP_ERROR_RE =- /No (?:inference|Hermes) provider(?: is)? configured|no_provider_configured|set an API key/i+ /No (?:inference|Hermes|LLM) provider(?: is)? configured|no_provider_configured|set an API key|is set in config\.yaml but no (?:API key|credentials)/iconst SESSION_INFO_CREDENTIAL_WARNING_RE = /^No API key configured for provider '[^']*'\. First message will fail\.$/+/** True when the gateway named this failure itself: preferred over reading the sentence. */+export function isProviderSetupErrorCode(code: null | string | undefined): boolean {+ return code === 'provider_not_configured'+}+export function isProviderSetupErrorMessage(message: null | string | undefined): boolean {const text = message?.trim()diff --git a/tests/tui_gateway/test_provider_not_configured_code.py b/tests/tui_gateway/test_provider_not_configured_code.pynew file mode 100644index 00000000000..b09911033b6--- /dev/null+++ b/tests/tui_gateway/test_provider_not_configured_code.py@@ -0,0 +1,100 @@+"""A session that cannot start for lack of a provider says so in a machine-readable way.++The Desktop routes this failure to its provider-setup flow — the one thing that fixes it — and had+to recognise it by matching the sentence. The sentences moved (``agent_init`` says "No LLM provider+configured", ``missing_provider_credentials_message`` says "Provider 'x' is set in config.yaml+but …"), the matcher did not, and a blank install got a dead-end toast instead of onboarding.+"""++import pytest++from agent.auxiliary_unavailable import ProviderNotConfiguredError+from tui_gateway import server+++def emitted(monkeypatch):+ events = []+ monkeypatch.setattr(server, "_emit", lambda kind, sid, payload: events.append((kind, payload)))+ return events+++def _fail_build(monkeypatch, exc):+ """Run the deferred agent build against a registered session, failing at ``_make_agent``."""+ import threading++ def _raise(*_a, **_kw):+ raise exc++ monkeypatch.setattr(server, "_make_agent", _raise)+ monkeypatch.setattr(server, "_deferred_build_agent_kwargs", lambda *a, **kw: {})+ monkeypatch.setattr(server, "_await_resume_history", lambda *a, **kw: True)+ monkeypatch.setattr(server, "_set_session_context", lambda *a, **kw: None)+ monkeypatch.setattr(server, "_clear_session_context", lambda *a, **kw: None)+ monkeypatch.setattr(server, "_session_cwd", lambda *a, **kw: None)+ monkeypatch.setattr(server, "_bind_build_profile_scopes", lambda *a, **kw: None)+ monkeypatch.setattr(server, "_finish_agent_build", lambda *a, **kw: None)++ session = {"session_key": "key", "agent_ready": threading.Event()}+ monkeypatch.setitem(server._sessions, "sid", session)+ return session+++def _run_build(session):+ server._start_agent_build("sid", session)+ session["_agent_build_thread"].join(timeout=30)+++def test_provider_not_configured_is_named_in_the_error_event(monkeypatch, emitted):+ session = _fail_build(monkeypatch, ProviderNotConfiguredError(+ "No LLM provider configured. Run `hermes model` to select a provider, or run `hermes setup` "+ "for first-time configuration."))++ _run_build(session)++ kind, payload = next((k, p) for k, p in emitted if k == "error")+ assert payload["code"] == "provider_not_configured"+ assert "No LLM provider configured" in payload["message"] # the sentence still reaches the reader+++def test_an_unrelated_build_failure_carries_no_code(monkeypatch, emitted):+ session = _fail_build(monkeypatch, RuntimeError("the session database is locked"))++ _run_build(session)++ _, payload = next((k, p) for k, p in emitted if k == "error")+ assert "code" not in payload+++class TestAgentInitRaisesTheNamedError:+ """Both "cannot serve this session" paths in agent_init raise the type, not a bare RuntimeError."""++ def test_no_provider_configured_at_all(self, monkeypatch, tmp_path):+ from types import SimpleNamespace++ from agent.agent_init import _routed_client_kwargs++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ # Nothing resolves and no fallback chain: the end of the ladder.+ monkeypatch.setattr("agent.auxiliary_client.resolve_provider_client", lambda *a, **kw: (None, None))+ agent = SimpleNamespace(provider="auto", model="m", base_url=None, api_key=None,+ _fallback_activated=False, _explicit_provider="")++ with pytest.raises(ProviderNotConfiguredError, match="No LLM provider configured"):+ _routed_client_kwargs(agent, None, 60)++ def test_explicit_provider_without_credentials(self, monkeypatch, tmp_path):+ from types import SimpleNamespace++ from agent.agent_init import _routed_client_kwargs++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ agent = SimpleNamespace(provider="minimax-oauth", model="m", base_url=None, api_key=None,+ _fallback_activated=False, _explicit_provider="minimax-oauth")++ with pytest.raises(ProviderNotConfiguredError, match=r"hermes auth add minimax-oauth"):+ _routed_client_kwargs(agent, None, 60)++ def test_the_type_is_a_runtime_error(self):+ """Existing `except RuntimeError` handlers keep catching it."""+ assert issubclass(ProviderNotConfiguredError, RuntimeError)diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex a06c59f59f1..0b8ce58e8b0 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -1160,8 +1160,14 @@ def _start_agent_build(sid: str, session: dict) -> None:notify_registered = _wire_session_agent(sid, key, agent)_announce_built_agent(sid, key, current, agent)except Exception as e:+ from agent.auxiliary_unavailable import ProviderNotConfiguredErrorcurrent["agent_error"] = str(e)- _emit("error", sid, {"message": agent_init_failed_message(e)})+ # A client can route "no provider is set up" to its setup flow instead of a dead-end+ # error toast — but only if it can tell. The sentence is for the reader, the code is+ # for the client; older clients keep matching the text.+ _emit("error", sid, {+ "message": agent_init_failed_message(e),+ **({"code": "provider_not_configured"} if isinstance(e, ProviderNotConfiguredError) else {})})finally:_finish_agent_build(sid, key, current, notify_registered=notify_registered, scopes=scopes, session_db=session_db)