The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(ux): plain-language, actionable user-facing messages (dashboard)
teknium1bdc791619646
diff --git a/hermes_cli/pty_session.py b/hermes_cli/pty_session.pyindex 01d9f344a07..378be522fc1 100644--- a/hermes_cli/pty_session.py+++ b/hermes_cli/pty_session.py@@ -140,7 +140,10 @@ class PtySession:class RegistryFull(Exception):- pass+ """Every keep-alive slot holds a PTY that some tab is still attached to."""++ def __init__(self, message: str = "Too many chat terminals are open in other tabs; close one and try again.") -> None:+ super().__init__(message)async def run_reaper(registry: "PtySessionRegistry", *, interval: float = 60.0) -> None:diff --git a/hermes_cli/web_routers/chat_ws.py b/hermes_cli/web_routers/chat_ws.pyindex f7d9c217d68..bf7ad173a2f 100644--- a/hermes_cli/web_routers/chat_ws.py+++ b/hermes_cli/web_routers/chat_ws.py@@ -18,6 +18,7 @@ from fastapi import APIRouter, FastAPI, HTTPException, WebSocket, WebSocketDiscofrom agent.interrupt_scope import InterruptScope, bind_interrupt_scopefrom hermes_cli.pty_session import RegistryFullfrom hermes_cli.web_deps import LateState, late+from hermes_cli.web_routers.chat_ws_errors import chat_start_failure_messagefrom hermes_cli.web_server_chat import (_build_sidecar_url, _close_stalled_pty_input, _get_console_executor, _legacy_pump, _ws_auth_ok,_ws_request_is_allowed,@@ -416,8 +417,11 @@ async def console_ws(ws: WebSocket) -> None:pass-async def _pty_fail(ws: WebSocket, text: str) -> None:- await ws.send_text(f"\r\n\x1b[31m{text}\x1b[0m\r\n")+async def _pty_fail(ws: WebSocket, exc: BaseException) -> None:+ """Tell the user why chat could not start, then close 1011 so the SPA renders+ "Start new session". The raw exception goes to the server log only."""+ _log.warning("pty start failed: %s: %s", type(exc).__name__, exc)+ await ws.send_text(f"\r\n\x1b[31m{chat_start_failure_message(exc)}\x1b[0m\r\n")await ws.close(code=1011)@@ -474,10 +478,10 @@ async def pty_ws(ws: WebSocket) -> None:try:argv, cwd, env = await _resolve_chat_argv_async(**resolve_kwargs)except HTTPException as exc: # unknown/invalid profile- await _pty_fail(ws, f"Chat unavailable: {exc.detail}")+ await _pty_fail(ws, exc)returnexcept SystemExit as exc: # _make_tui_argv sys.exit(1)s when node/npm is missing- await _pty_fail(ws, f"Chat unavailable: {exc}")+ await _pty_fail(ws, exc)returnattach_token = ws.query_params.get("attach") or None@@ -496,10 +500,10 @@ async def pty_ws(ws: WebSocket) -> None:try:bridge = _spawn()except PtyUnavailableError as exc:- await _pty_fail(ws, f"Chat unavailable: {exc}")+ await _pty_fail(ws, exc)returnexcept (FileNotFoundError, OSError) as exc:- await _pty_fail(ws, f"Chat failed to start: {exc}")+ await _pty_fail(ws, exc)returnawait _legacy_pump(ws, bridge)return@@ -508,7 +512,7 @@ async def pty_ws(ws: WebSocket) -> None:try:session, _created = await PTY_REGISTRY.attach_or_spawn(attach_token, spawn=_spawn)except (PtyUnavailableError, FileNotFoundError, OSError, RegistryFull) as exc:- await _pty_fail(ws, f"Chat unavailable: {exc}")+ await _pty_fail(ws, exc)return# A fresh xterm can't rebuild the TUI from an arbitrary tail of alternate-diff --git a/hermes_cli/web_routers/chat_ws_errors.py b/hermes_cli/web_routers/chat_ws_errors.pynew file mode 100644index 00000000000..94c5fbcdf9a--- /dev/null+++ b/hermes_cli/web_routers/chat_ws_errors.py@@ -0,0 +1,48 @@+"""User-facing copy for dashboard chat (``/api/pty``) start failures.++``pty_ws`` writes one red line into the terminal and closes with 1011 when the+``hermes --tui`` child cannot be spawned. The exception text alone is either+raw errno noise (``[Errno 2] No such file or directory: 'node'``), a bare exit+code (``SystemExit(1)`` after ``_make_tui_argv`` already printed to the server+log), or empty (``RegistryFull``). Turn each into what happened + what to do.+"""++from __future__ import annotations++from fastapi import HTTPException++from hermes_cli.pty_session import RegistryFull++CHAT_NEEDS_NODE = (+ "Chat could not start: Hermes needs Node.js to run the terminal chat. "+ "Install Node 18+ (for example from nodejs.org) and reopen this tab."+)+CHAT_TOO_MANY_TERMINALS = (+ "Chat could not start: too many chat terminals are open in other tabs. "+ "Close one and click Start new session."+)+CHAT_PROFILE_UNKNOWN = "Chat could not start: {detail} Pick another profile from the switcher and reopen this tab."+CHAT_START_FAILED = "Chat could not start: {detail} Check the server log (`hermes dashboard` terminal) and click Start new session."+++def _node_missing(exc: BaseException) -> bool:+ text = str(exc)+ return isinstance(exc, SystemExit) or "'node'" in text or "'npm'" in text or "Node.js" in text+++def chat_start_failure_message(exc: BaseException) -> str:+ """One plain sentence for the terminal pane; never the bare exception."""+ if isinstance(exc, RegistryFull):+ return CHAT_TOO_MANY_TERMINALS+ if isinstance(exc, HTTPException):+ return CHAT_PROFILE_UNKNOWN.format(detail=_sentence(str(exc.detail)))+ if _node_missing(exc):+ return CHAT_NEEDS_NODE+ return CHAT_START_FAILED.format(detail=_sentence(str(exc) or type(exc).__name__))+++def _sentence(text: str) -> str:+ text = text.strip()+ if not text:+ return "the terminal process could not be launched."+ return text if text.endswith((".", "!", "?")) else f"{text}."diff --git a/tests/hermes_cli/test_web_chat_ws_errors.py b/tests/hermes_cli/test_web_chat_ws_errors.pynew file mode 100644index 00000000000..1a79d035a0a--- /dev/null+++ b/tests/hermes_cli/test_web_chat_ws_errors.py@@ -0,0 +1,34 @@+"""Copy contract for dashboard chat start failures (``/api/pty`` close 1011).++The terminal pane used to show the raw exception (``Chat unavailable: [Errno 2]+No such file or directory: 'node'``, ``Chat unavailable: 1``, or an empty+``Chat unavailable:`` for a full registry). Each failure must now say what+happened and what to do, with no errno or exception class in the lead.+"""++from fastapi import HTTPException++from hermes_cli.pty_session import RegistryFull+from hermes_cli.web_routers.chat_ws_errors import chat_start_failure_message+++def test_registry_full_names_the_fix_and_carries_a_message():+ exc = RegistryFull()+ assert str(exc) # was empty before; the SPA printed "Chat unavailable:"+ msg = chat_start_failure_message(exc)+ assert "too many chat terminals" in msg+ assert "Start new session" in msg+++def test_missing_node_points_at_installing_node_not_errno():+ for exc in (FileNotFoundError(2, "No such file or directory", "node"), SystemExit(1)):+ msg = chat_start_failure_message(exc)+ assert "Node" in msg and "nodejs.org" in msg+ assert "Errno" not in msg and "SystemExit" not in msg+ assert not msg.endswith(": 1")+++def test_unknown_profile_keeps_detail_and_adds_next_step():+ msg = chat_start_failure_message(HTTPException(status_code=404, detail="Profile 'nope' not found"))+ assert msg.startswith("Chat could not start: Profile 'nope' not found.")+ assert "profile" in msg.lower()diff --git a/tests/hermes_cli/test_web_server.py b/tests/hermes_cli/test_web_server.pyindex 3c63087fc71..74bddd8d26a 100644--- a/tests/hermes_cli/test_web_server.py+++ b/tests/hermes_cli/test_web_server.py@@ -4670,7 +4670,7 @@ class TestPtyWebSocket:notice = conn.receive_text()with pytest.raises(WebSocketDisconnect) as exc:conn.receive_text()- assert "Chat unavailable" in notice+ assert "Chat could not start" in noticeassert exc.value.code == 1011if expect_detail is not None:assert expect_detail in noticediff --git a/web/src/components/AuthWidget.tsx b/web/src/components/AuthWidget.tsxindex 93657bf854d..3a26d23b654 100644--- a/web/src/components/AuthWidget.tsx+++ b/web/src/components/AuthWidget.tsx@@ -25,9 +25,14 @@import { useEffect, useState } from "react";import { api, type AuthMeResponse } from "@/lib/api";+import { ApiError } from "@/lib/api-error";import { cn } from "@/lib/utils";import { LogOut } from "lucide-react";+/** Shown when /api/auth/me fails for a reason other than "not gated". */+export const AUTH_STATUS_UNAVAILABLE_MESSAGE =+ "Could not check who is signed in. Reload the page; if it persists, sign in again.";+interface AuthWidgetProps {className?: string;}@@ -62,17 +67,15 @@ export function AuthWidget({ className }: AuthWidgetProps) {}).catch((err: unknown) => {if (cancelled) return;- // 401 from /api/auth/me means the gate isn't engaged in this- // process (loopback mode) — render nothing. fetchJSON throws an- // Error with the status code as a prefix; the global 401- // handler only redirects on the structured envelope, so a plain- // 401 from /api/auth/me with no envelope bubbles up here.- const msg = err instanceof Error ? err.message : String(err);- if (msg.startsWith("401:") || msg.startsWith("403:")) {+ // 401/403 from /api/auth/me means the gate isn't engaged in this+ // process (loopback mode) — render nothing. The global 401 handler+ // only redirects on the structured envelope, so a plain 401 from+ // /api/auth/me with no envelope bubbles up here as an ApiError.+ if (err instanceof ApiError && (err.status === 401 || err.status === 403)) {setHidden(true);return;}- setError("auth status unavailable");+ setError(AUTH_STATUS_UNAVAILABLE_MESSAGE);});return () => {cancelled = true;@@ -88,11 +91,19 @@ export function AuthWidget({ className }: AuthWidgetProps) {return (<divclassName={cn(- "px-5 py-2 text-[0.65rem] tracking-[0.05em] text-muted-foreground/70",+ "flex flex-col gap-1 px-5 py-2 text-[0.65rem] tracking-[0.05em] text-muted-foreground/70",className,)}+ role="status">- {error}+ <span>{error}</span>+ <button+ type="button"+ onClick={() => window.location.reload()}+ className="self-start underline underline-offset-2 hover:text-foreground"+ >+ Reload page+ </button></div>);}diff --git a/web/src/components/AutomationBlueprints.tsx b/web/src/components/AutomationBlueprints.tsxindex 209c75e0682..088dd678594 100644--- a/web/src/components/AutomationBlueprints.tsx+++ b/web/src/components/AutomationBlueprints.tsx@@ -12,6 +12,7 @@ import { Toast } from "@nous-research/ui/ui/components/toast";import { api } from "@/lib/api";import type { AutomationBlueprint, AutomationBlueprintField } from "@/lib/api";import { cn, themedBody } from "@/lib/utils";+import { errorMessage } from "@/lib/api-error";interface AutomationBlueprintsProps {profile: string;@@ -183,7 +184,7 @@ export function AutomationBlueprints({ profile, onCreated }: AutomationBlueprintif (!cancelled) setBlueprints(r.blueprints);}).catch((e) => {- if (!cancelled) setLoadError(e instanceof Error ? e.message : String(e));+ if (!cancelled) setLoadError(errorMessage(e));});return () => {cancelled = true;diff --git a/web/src/components/ChatSidebar.test.tsx b/web/src/components/ChatSidebar.test.tsxindex ed4b487751a..65f63fefb2b 100644--- a/web/src/components/ChatSidebar.test.tsx+++ b/web/src/components/ChatSidebar.test.tsx@@ -36,7 +36,14 @@ const reloadMocks = vi.hoisted(() => ({maybeReloadForLoopbackWsAuthFailure: vi.fn(() => true)}))+const routerMocks = vi.hoisted(() => ({ navigate: vi.fn() }))++vi.mock('react-router', () => ({+ useNavigate: () => routerMocks.navigate+}))+vi.mock('@/lib/api', () => ({+ HERMES_BASE_PATH: '',api: { getModelInfo: apiMocks.getModelInfo },buildWsUrl: apiMocks.buildWsUrl}))@@ -384,16 +391,16 @@ describe('ChatSidebar event socket reconnect', () => {await act(async () => {FakeWebSocket.instances[0].emit('close', { code: 1006 })})- expect(container.textContent).toContain('events feed disconnected')+ expect(container.textContent).toContain('Live tool activity paused')await advance(1_000)await act(async () => {FakeWebSocket.instances[1].emit('open', {})})- // Banner gone entirely — including the "reconnect events feed" button,+ // Banner gone entirely — including the "Reconnect side panel" button,// which only renders while `error` is set.- expect(container.textContent).not.toContain('events feed')+ expect(container.textContent).not.toContain('Live tool activity')})it('does not clear a credential warning when the feed recovers', async () => {@@ -441,9 +448,45 @@ describe('ChatSidebar event socket reconnect', () => {expect(container.textContent).toContain('ANTHROPIC_API_KEY is not set')// The disconnect message must not have replaced it. (Matching the- // banner text specifically — "reconnect events feed" is the button- // label, which is expected to be present whenever a banner shows.)- expect(container.textContent).not.toContain('events feed disconnected')+ // banner text specifically — the reconnect button label is expected to+ // be present whenever a banner shows.)+ expect(container.textContent).not.toContain('Live tool activity paused')+ })++ it('offers Add key and Switch model when the gateway reports a missing key', async () => {+ await renderSidebar()++ await act(async () => {+ gatewayMocks.handlers.get('session.info')?.({+ payload: {+ credential_warning: "No API key configured for provider 'openrouter'. First message will fail."+ }+ })+ })++ expect(container.textContent).toContain('No API key set for openrouter')+ expect(container.textContent).not.toContain('First message will fail')+ const buttons = Array.from(container.querySelectorAll('button'))+ const labels = buttons.map(b => b.textContent?.trim())+ expect(labels).toContain('Add key')+ expect(labels).toContain('Switch model')++ // Add key must be an in-app route change: a full page load would tear down+ // the terminal scrollback and the chat sockets.+ await act(async () => {+ buttons.find(b => b.textContent?.trim() === 'Add key')?.click()+ })+ expect(routerMocks.navigate).toHaveBeenCalledWith('/env')+ })++ it('explains that only the side panel is affected when the sidecar cannot connect', async () => {+ gatewayMocks.connect.mockRejectedValueOnce(new Error('WebSocket connection failed'))+ await renderSidebar()++ await vi.waitFor(() => expect(container.textContent).toContain('Chat still works'))+ expect(container.textContent).not.toContain('WebSocket')+ const labels = Array.from(container.querySelectorAll('button')).map(b => b.textContent?.trim())+ expect(labels).toContain('Reconnect side panel')})it('still reconnects while a foreign banner suppresses its message', async () => {@@ -476,7 +519,7 @@ describe('ChatSidebar event socket reconnect', () => {FakeWebSocket.instances[0].emit('close', { code: 1006 })})const reconnectButton = Array.from(container.querySelectorAll('button')).find(b =>- /reconnect events feed/i.test(b.textContent ?? '')+ /reconnect side panel/i.test(b.textContent ?? ''))expect(reconnectButton).toBeDefined()await act(async () => {diff --git a/web/src/components/ChatSidebar.tsx b/web/src/components/ChatSidebar.tsxindex 6a3eb6e8027..6f77ea7f26b 100644--- a/web/src/components/ChatSidebar.tsx+++ b/web/src/components/ChatSidebar.tsx@@ -42,14 +42,17 @@ import {eventsReconnectingMessage,eventsRejectedMessage,isEventsAuthRejection,+ isEventsAuthRejectionMessage,isEventsFeedMessage,shouldRetryEventsClose} from '@/lib/events-reconnect'+import { credentialWarning, sidecarErrorMessage } from '@/lib/chat-sidebar-banner'import { titleFromSessionInfoPayload } from '@/lib/chat-title'import { cn } from '@/lib/utils'-import { AlertCircle, ChevronDown, RefreshCw } from 'lucide-react'+import { AlertCircle, ChevronDown, KeyRound, RefreshCw } from 'lucide-react'import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import { useNavigate } from 'react-router'interface SessionInfo {cwd?: string@@ -106,6 +109,7 @@ export function ChatSidebar({onDashboardNewSessionRequest,onSessionTitleChange}: ChatSidebarProps) {+ const navigate = useNavigate()// `version` bumps on reconnect (manual button, profile/channel switch) and// re-runs the socket effects. The clients themselves live for the whole// component: the shared client keeps per-session seq watermarks and asks@@ -196,7 +200,8 @@ export function ChatSidebar({const message = ev.payload?.messageif (message) {- setError(message)+ console.warn(`[chat-sidebar] sidecar error: ${message}`)+ setError(sidecarErrorMessage(message))}})@@ -215,7 +220,8 @@ export function ChatSidebar({}).catch((e: Error) => {if (!cancelled) {- setError(e.message)+ console.warn(`[chat-sidebar] sidecar connect failed: ${e.message}`)+ setError(sidecarErrorMessage(e.message))}})@@ -302,6 +308,7 @@ export function ChatSidebar({if (unmounting) {return}+ console.warn(`[chat-sidebar] events feed closed code=${code ?? 'none'}`)if (code !== undefined && isEventsAuthRejection(code)) {surface(eventsRejectedMessage(code))return@@ -362,7 +369,9 @@ export function ChatSidebar({// sidecar gateway session, so it's available whenever the sidebar is mounted.const modelName = effectiveModel || info.model || '—'const modelLabel = modelName.split('/').slice(-1)[0] ?? '—'- const banner = error ?? info.credential_warning ?? null+ const credential = credentialWarning(info.credential_warning)+ const banner = error ?? credential?.message ?? null+ const showReload = isEventsAuthRejectionMessage(error)return (<aside@@ -429,11 +438,40 @@ export function ChatSidebar({<div className="min-w-0 flex-1"><div className="wrap-break-word text-destructive">{banner}</div>- {error && (+ {error && showReload && (+ <Button+ size="sm"+ outlined+ className="mt-1"+ onClick={() => window.location.reload()}+ prefix={<RefreshCw />}+ >+ Reload page+ </Button>+ )}+ {error && !showReload && (<Button size="sm" outlined className="mt-1" onClick={reconnect} prefix={<RefreshCw />}>- reconnect events feed+ Reconnect side panel</Button>)}+ {!error && credential && (+ <div className="mt-1 flex flex-wrap gap-2">+ <Button+ size="sm"+ outlined+ prefix={<KeyRound />}+ // Router navigation: a full page load would tear down the+ // xterm scrollback and the chat sockets. (The mobile portal+ // still lives under ChatPage, so router context is present.)+ onClick={() => navigate('/env')}+ >+ Add key+ </Button>+ <Button size="sm" outlined onClick={() => setModelOpen(true)}>+ Switch model+ </Button>+ </div>+ )}</div></Card>)}diff --git a/web/src/components/HermesConsoleModal.tsx b/web/src/components/HermesConsoleModal.tsxindex 4ce422c0ab0..069dd8a8e06 100644--- a/web/src/components/HermesConsoleModal.tsx+++ b/web/src/components/HermesConsoleModal.tsx@@ -14,6 +14,7 @@ import { api } from "@/lib/api";import { maybeReloadForLoopbackWsAuthFailure } from "@/lib/dashboard-auth-reload";import { cn, themedBody } from "@/lib/utils";import { useTheme } from "@/themes";+import { errorMessage } from "@/lib/api-error";type ConsoleFrame =| {@@ -113,6 +114,9 @@ export function HermesConsoleModal({ open, onClose }: HermesConsoleModalProps) {const hasReadyFrameRef = useRef(false);const [connectionState, setConnectionState] =useState<ConnectionState>("connecting");+ // Bumped by the Reconnect button; a dependency of the connect effect so the+ // console redials the same /api/console socket without closing the modal.+ const [connectNonce, setConnectNonce] = useState(0);const [consoleProfile, setConsoleProfile] = useState("current");const { profile } = useProfileScope();const { theme } = useTheme();@@ -432,17 +436,24 @@ export function HermesConsoleModal({ open, onClose }: HermesConsoleModalProps) {pendingCommandRef.current = null;if (cancelled) return;setConnectionState(ev.code === 1000 ? "closed" : "error");- const reason = ev.reason ? ` ${ev.reason}` : "";+ // Close code and server reason are diagnostics, not user copy.+ console.warn(`[console] websocket closed code=${ev.code}${ev.reason ? ` reason=${ev.reason}` : ""}`);const message =ev.code === 1006 && !hasReadyFrameRef.current- ? "Console connection failed before the server handshake. Check that this dashboard is connected to a backend with /api/console."- : `Console closed (${ev.code}).${reason}`;+ ? "Console could not connect to the dashboard server. Check that `hermes dashboard` is running, then click Reconnect."+ : ev.code === 1000+ ? "Console closed."+ : "Console disconnected from the dashboard server. Click Reconnect to try again.";writeLine(term, `\x1b[31m${message}\x1b[0m`);};} catch (err) {if (cancelled) return;setConnectionState("error");- writeLine(term, `\x1b[31mConsole unavailable: ${err}\x1b[0m`);+ console.warn(`[console] connect failed: ${errorMessage(err)}`);+ writeLine(+ term,+ "\x1b[31mConsole could not connect to the dashboard server. Check that `hermes dashboard` is running, then click Reconnect.\x1b[0m",+ );}})();@@ -460,7 +471,7 @@ export function HermesConsoleModal({ open, onClose }: HermesConsoleModalProps) {activeCommandRef.current = false;hasReadyFrameRef.current = false;};- }, [handleFrame, handleInputData, open, profile, theme]);+ }, [connectNonce, handleFrame, handleInputData, open, profile, theme]);useEffect(() => {if (!open) return;@@ -512,6 +523,19 @@ export function HermesConsoleModal({ open, onClose }: HermesConsoleModalProps) {<div className="mt-1 flex flex-wrap items-center gap-2 text-xs text-muted-foreground"><Badge tone={statusTone}>{connectionState}</Badge><span className="font-mono">{consoleProfile}</span>+ {(connectionState === "closed" || connectionState === "error") && (+ <Button+ size="sm"+ outlined+ onClick={() => {+ setConnectionState("connecting");+ setConnectNonce((n) => n + 1);+ }}+ aria-label="Reconnect console"+ >+ Reconnect+ </Button>+ )}</div></div><Buttondiff --git a/web/src/components/LoadErrorNotice.tsx b/web/src/components/LoadErrorNotice.tsxnew file mode 100644index 00000000000..3e17c52fcde--- /dev/null+++ b/web/src/components/LoadErrorNotice.tsx@@ -0,0 +1,51 @@+import { AlertCircle, RotateCcw } from "lucide-react";+import { Button } from "@nous-research/ui/ui/components/button";+import { Card } from "@nous-research/ui/ui/components/card";++import { useI18n } from "@/i18n";+import { loadErrorCopy } from "@/lib/load-error-copy";+import { cn } from "@/lib/utils";++interface LoadErrorNoticeProps {+ /** What failed to load, already translated (e.g. `t.cron.loadWhat`). */+ what: string;+ /** The humanized error (`errorMessage(err)`), shown as a dimmed detail line. */+ detail?: string | null;+ onRetry: () => void;+ className?: string;+}++/**+ * Persistent "could not load X" card with a Retry button. Used instead of an+ * error toast for page loaders: a toast vanishes after 3s and cannot carry a+ * retry action, so the user was left with an empty page and no next step.+ */+export function LoadErrorNotice({ what, detail, onRetry, className }: LoadErrorNoticeProps) {+ const { t } = useI18n();+ const copy = loadErrorCopy(t.common, what, detail);++ return (+ <Card+ role="alert"+ className={cn(+ "flex items-start gap-2 border-destructive/40 bg-destructive/5 px-3 py-2 text-xs",+ className,+ )}+ >+ <AlertCircle className="mt-0.5 h-3.5 w-3.5 shrink-0 text-destructive" />+ <div className="min-w-0 flex-1">+ <div className="text-destructive">{copy.title}</div>+ {copy.details && <div className="mt-0.5 text-muted-foreground">{copy.details}</div>}+ <Button+ size="sm"+ outlined+ className="mt-1"+ onClick={onRetry}+ prefix={<RotateCcw className="h-3.5 w-3.5" />}+ >+ {t.common.retry}+ </Button>+ </div>+ </Card>+ );+}diff --git a/web/src/components/ModelPickerDialog.tsx b/web/src/components/ModelPickerDialog.tsxindex 2b372125eab..44e5de48440 100644--- a/web/src/components/ModelPickerDialog.tsx+++ b/web/src/components/ModelPickerDialog.tsx@@ -10,9 +10,11 @@ import type { ModelOptionProvider, ModelOptionsResult } from "@hermes/shared";import { Check, RefreshCw, Search, X } from "lucide-react";import { useEffect, useMemo, useRef, useState } from "react";import { createPortal } from "react-dom";+import { Link } from "react-router";import { cn, themedBody } from "@/lib/utils";import { queryMatchesProviderOnly } from "@/lib/model-picker-filter";import { fuzzyRank, modelSearchText } from "@hermes/shared";+import { errorMessage } from "@/lib/api-error";/*** Two-stage model picker modal.@@ -143,7 +145,7 @@ export function ModelPickerDialog(props: Props) {}).catch((e) => {if (closedRef.current) return;- setError(e instanceof Error ? e.message : String(e));+ setError(errorMessage(e));}).finally(() => {if (closedRef.current) return;@@ -162,7 +164,7 @@ export function ModelPickerDialog(props: Props) {}).catch((e) => {if (closedRef.current) return;- setError(e instanceof Error ? e.message : String(e));+ setError(errorMessage(e));}).finally(() => {if (closedRef.current) return;@@ -283,7 +285,7 @@ export function ModelPickerDialog(props: Props) {}onClose();} catch (e) {- setError(e instanceof Error ? e.message : String(e));+ setError(errorMessage(e));} finally {setApplying(false);}@@ -311,7 +313,7 @@ export function ModelPickerDialog(props: Props) {}onClose();} catch (e) {- setError(e instanceof Error ? e.message : String(e));+ setError(errorMessage(e));} finally {setApplying(false);}@@ -383,6 +385,7 @@ export function ModelPickerDialog(props: Props) {<ProviderColumnloading={loading}error={error}+ onClose={onClose}providers={filteredProviders}total={providers.length}selectedSlug={selectedSlug}@@ -480,6 +483,10 @@ export function ModelPickerDialog(props: Props) {/* Provider column *//* ------------------------------------------------------------------ */+/** Empty picker: no key and no OAuth login anywhere. Points at the two in-app fixes. */+export const NO_PROVIDERS_MESSAGE =+ "No model providers are set up yet. Add an API key under Keys or sign in to a provider under Models to see models here.";+function ProviderColumn({loading,error,@@ -488,6 +495,7 @@ function ProviderColumn({selectedSlug,query,onSelect,+ onClose,}: {loading: boolean;error: string | null;@@ -496,6 +504,8 @@ function ProviderColumn({selectedSlug: string;query: string;onSelect(slug: string): void;+ /** The links below navigate away; the full-screen dialog must close or it keeps covering the target page. */+ onClose(): void;}) {return (<div className="border-r border-border overflow-y-auto">@@ -508,12 +518,22 @@ function ProviderColumn({{error && <div className="p-4 text-xs text-destructive">{error}</div>}{!loading && !error && providers.length === 0 && (- <div className="p-4 text-xs text-muted-foreground italic">- {query- ? "no matches"- : total === 0- ? "no authenticated providers"- : "no matches"}+ <div className="p-4 text-xs text-muted-foreground">+ {query || total > 0 ? (+ <span className="italic">No providers match your search.</span>+ ) : (+ <div className="flex flex-col gap-2">+ <span>{NO_PROVIDERS_MESSAGE}</span>+ <div className="flex flex-wrap gap-2">+ <Link to="/env" onClick={onClose} className="underline underline-offset-2 hover:text-foreground">+ Open Keys+ </Link>+ <Link to="/models" onClick={onClose} className="underline underline-offset-2 hover:text-foreground">+ Sign in to a provider+ </Link>+ </div>+ </div>+ )}</div>)}diff --git a/web/src/components/OAuthLoginModal.tsx b/web/src/components/OAuthLoginModal.tsxindex c20990c14fc..7ae62687dde 100644--- a/web/src/components/OAuthLoginModal.tsx+++ b/web/src/components/OAuthLoginModal.tsx@@ -8,6 +8,7 @@ import { copyTextToClipboard } from "@/lib/clipboard";import { Input } from "@nous-research/ui/ui/components/input";import { useI18n } from "@/i18n";import { cn, themedBody } from "@/lib/utils";+import { errorMessage } from "@/lib/api-error";interface Props {provider: OAuthProvider;@@ -58,7 +59,7 @@ export function OAuthLoginModal({ provider, onClose, onSuccess }: Props) {.catch((e) => {if (!isMounted.current) return;setPhase("error");- setErrorMsg(`Failed to start login: ${e}`);+ setErrorMsg(`Failed to start login: ${errorMessage(e)}`);});return () => {isMounted.current = false;@@ -141,7 +142,7 @@ export function OAuthLoginModal({ provider, onClose, onSuccess }: Props) {} catch (e) {if (!isMounted.current) return;setPhase("error");- setErrorMsg(`Polling failed: ${e}`);+ setErrorMsg(`Polling failed: ${errorMessage(e)}`);if (pollTimer.current !== null) window.clearInterval(pollTimer.current);}}, 2000);@@ -173,7 +174,7 @@ export function OAuthLoginModal({ provider, onClose, onSuccess }: Props) {} catch (e) {if (!isMounted.current) return;setPhase("error");- setErrorMsg(`Submit failed: ${e}`);+ setErrorMsg(`Submit failed: ${errorMessage(e)}`);}};@@ -411,7 +412,7 @@ export function OAuthLoginModal({ provider, onClose, onSuccess }: Props) {.catch((e) => {if (!isMounted.current) return;setPhase("error");- setErrorMsg(`${t.common.retry} failed: ${e}`);+ setErrorMsg(`${t.common.retry} failed: ${errorMessage(e)}`);});}}>diff --git a/web/src/components/OAuthProvidersCard.tsx b/web/src/components/OAuthProvidersCard.tsxindex 19d95621cf6..db19636ebdc 100644--- a/web/src/components/OAuthProvidersCard.tsx+++ b/web/src/components/OAuthProvidersCard.tsx@@ -21,6 +21,7 @@ import { Badge } from "@nous-research/ui/ui/components/badge";import { ConfirmDialog } from "@nous-research/ui/ui/components/confirm-dialog";import { OAuthLoginModal } from "@/components/OAuthLoginModal";import { useI18n } from "@/i18n";+import { errorMessage } from "@/lib/api-error";interface Props {onError?: (msg: string) => void;@@ -66,7 +67,7 @@ export function OAuthProvidersCard({ onError, onSuccess }: Props) {api.getOAuthProviders().then((resp) => setProviders(resp.providers))- .catch((e) => onErrorRef.current?.(`Failed to load providers: ${e}`))+ .catch((e) => onErrorRef.current?.(`Failed to load providers: ${errorMessage(e)}`)).finally(() => setLoading(false));}, []);@@ -82,7 +83,7 @@ export function OAuthProvidersCard({ onError, onSuccess }: Props) {onSuccess?.(`${provider.name} ${t.oauth.disconnect.toLowerCase()}ed`);refresh();} catch (e) {- onError?.(`${t.oauth.disconnect} failed: ${e}`);+ onError?.(`${t.oauth.disconnect} failed: ${errorMessage(e)}`);} finally {setBusyId(null);}diff --git a/web/src/components/SkillEditorDialog.tsx b/web/src/components/SkillEditorDialog.tsxindex 9981fe79dc8..aa46f4ebf18 100644--- a/web/src/components/SkillEditorDialog.tsx+++ b/web/src/components/SkillEditorDialog.tsx@@ -11,6 +11,7 @@ import {DialogHeader,DialogTitle,} from "@nous-research/ui/ui/components/dialog";+import { errorMessage } from "@/lib/api-error";/* ------------------------------------------------------------------ *//* SkillEditorDialog — create or edit a SKILL.md from the dashboard */@@ -92,7 +93,7 @@ function EditorBody({api.getSkillContent(editName, profile || undefined).then((res) => !cancelled && setContent(res.content))- .catch((e) => !cancelled && setError(String(e)))+ .catch((e) => !cancelled && setError(errorMessage(e))).finally(() => !cancelled && setLoading(false));return () => {cancelled = true;@@ -128,7 +129,7 @@ function EditorBody({}onClose();} catch (e) {- setError(String(e));+ setError(errorMessage(e));} finally {setSaving(false);}diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.tsindex 5a82a0db5ad..5098f8b1983 100644--- a/web/src/i18n/en.ts+++ b/web/src/i18n/en.ts@@ -10,6 +10,8 @@ export const en: Translations = {delete: "Delete",refresh: "Refresh",retry: "Retry",+ loadFailed: "Could not load {what}. Check that the dashboard server is running and click Retry.",+ loadFailedDetails: "Details: {detail}",search: "Search...",loading: "Loading...",create: "Create",@@ -249,6 +251,11 @@ export const en: Translations = {},cron: {+ loadWhat: "cron jobs",+ // Script-only mode on, Script field empty. `no_agent` is the config key, not a term the+ // user has seen; name the field they must fill instead.+ scriptRequired:+ "Script-only jobs need a script path. Fill in the Script field or switch the job back to prompt mode.",confirmDeleteMessage:"This removes the job from the schedule. This cannot be undone.",confirmDeleteTitle: "Delete scheduled job?",@@ -372,7 +379,7 @@ export const en: Translations = {modelOptional: "Model (optional)",modelInherit: "Inherit from clone / default",modelLoading: "Loading models…",- modelNone: "No authenticated providers — set a key first",+ modelNone: "No model providers are set up yet. Add an API key under Keys or sign in to a provider under Models.",editModel: "Change model",modelSaved: "Model updated",modelSelect: "Select a model",@@ -438,11 +445,14 @@ export const en: Translations = {skills: {title: "Skills",searchPlaceholder: "Search skills and toolsets...",+ loadWhat: "skills",+ browseHub: "Browse skills hub",+ createSkill: "Create skill",enabledOf: "{enabled}/{total} enabled",all: "All",categories: "Categories",filters: "Filters",- noSkills: "No skills found. Skills are loaded from ~/.hermes/skills/",+ noSkills: "No skills installed yet. Browse the skills hub or create one here; from a terminal you can also run `hermes skills search <topic>`.",noSkillsMatch: "No skills match your search or filter.",skillCount: "{count} skill{s}",resultCount: "{count} result{s}",diff --git a/web/src/i18n/types.ts b/web/src/i18n/types.tsindex 92c12c1a733..59378fff171 100644--- a/web/src/i18n/types.ts+++ b/web/src/i18n/types.ts@@ -28,6 +28,9 @@ export interface Translations {delete: string;refresh: string;retry: string;+ /** Optional — English fallback until translated. "{what}" = the noun that failed to load. */+ loadFailed?: string;+ loadFailedDetails?: string;search: string;loading: string;create: string;@@ -266,6 +269,9 @@ export interface Translations {// ── Cron page ──cron: {+ /** Optional — English fallback until translated. */+ loadWhat?: string;+ scriptRequired?: string;confirmDeleteMessage: string;confirmDeleteTitle: string;newJob: string;@@ -453,6 +459,10 @@ export interface Translations {skills: {title: string;searchPlaceholder: string;+ /** Optional — English fallback until translated. */+ loadWhat?: string;+ browseHub?: string;+ createSkill?: string;enabledOf: string;all: string;categories: string;diff --git a/web/src/lib/api-error.test.ts b/web/src/lib/api-error.test.tsnew file mode 100644index 00000000000..99965319e7b--- /dev/null+++ b/web/src/lib/api-error.test.ts@@ -0,0 +1,112 @@+// @vitest-environment jsdom+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { fetchJSON } from "./api";+import { API_UNREACHABLE_MESSAGE, ApiError, errorMessage, extractDetail } from "./api-error";++vi.mock("./dashboard-auth-reload", () => ({+ attemptDashboardTokenReloadOnce: vi.fn(() => false),+ clearDashboardTokenReloadAttempt: vi.fn(),+}));++beforeEach(() => {+ Object.defineProperty(window, "__HERMES_SESSION_TOKEN__", {+ configurable: true,+ value: "tok",+ writable: true,+ });+ Object.defineProperty(window, "__HERMES_AUTH_REQUIRED__", {+ configurable: true,+ value: false,+ writable: true,+ });+});++afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++describe("fetchJSON error contract", () => {+ it("throws an ApiError whose message is the JSON detail, not the status or body", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn<typeof fetch>(+ async () =>+ new Response(JSON.stringify({ detail: "Server 'foo' not found" }), {+ headers: { "Content-Type": "application/json" },+ status: 404,+ }),+ ),+ );++ const err = await fetchJSON("/api/mcp/servers/foo").catch((e: unknown) => e);+ expect(err).toBeInstanceOf(ApiError);+ const apiErr = err as ApiError;+ expect(apiErr.message).toBe("Server 'foo' not found");+ expect(apiErr.message).not.toMatch(/404|detail|\{/);+ expect(apiErr.status).toBe(404);+ expect(apiErr.details).toContain("404");+ // The toast pattern `\`Error: ${e}\`` must no longer double-prefix.+ expect(`${errorMessage(apiErr)}`).not.toMatch(/^Error:/);+ });++ it("maps a detail-less status to a plain sentence with no HTTP code lead", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn<typeof fetch>(async () => new Response("", { status: 500 })),+ );+ const err = (await fetchJSON("/api/status").catch((e: unknown) => e)) as ApiError;+ expect(err.message).not.toMatch(/^\d{3}/);+ expect(err.message).toMatch(/internal error/i);+ });++ it("turns a network failure into the 'is hermes dashboard running' sentence", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn<typeof fetch>(async () => {+ throw new TypeError("Failed to fetch");+ }),+ );+ const err = (await fetchJSON("/api/status").catch((e: unknown) => e)) as ApiError;+ expect(err).toBeInstanceOf(ApiError);+ expect(err.message).toBe(API_UNREACHABLE_MESSAGE);+ expect(err.message).not.toContain("Failed to fetch");+ expect(err.status).toBe(0);+ expect(err.body).toContain("Failed to fetch");+ });++ it("logs status, path and body to the console so bug reports keep what the toast drops", async () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ vi.stubGlobal(+ "fetch",+ vi.fn<typeof fetch>(async () => new Response('{"detail":"nope"}', { status: 503 })),+ );+ await fetchJSON("/api/status").catch(() => null);++ const logged = warn.mock.calls.map((c) => c.map(String).join(" ")).join("\n");+ expect(logged).toContain("503");+ expect(logged).toContain("/api/status");+ expect(logged).toContain("nope");++ warn.mockClear();+ vi.stubGlobal(+ "fetch",+ vi.fn<typeof fetch>(async () => {+ throw new TypeError("Failed to fetch");+ }),+ );+ await fetchJSON("/api/status").catch(() => null);+ expect(warn.mock.calls.map((c) => c.map(String).join(" ")).join("\n")).toContain("Failed to fetch");+ });+});++describe("extractDetail", () => {+ it("joins FastAPI validation errors and ignores HTML bodies", () => {+ expect(+ extractDetail(JSON.stringify({ detail: [{ msg: "field required", loc: ["body", "x"] }] })),+ ).toBe("field required");+ expect(extractDetail("<html><body>502 Bad Gateway</body></html>")).toBeNull();+ expect(extractDetail("")).toBeNull();+ });+});diff --git a/web/src/lib/api-error.ts b/web/src/lib/api-error.tsnew file mode 100644index 00000000000..13ea59c5a6d--- /dev/null+++ b/web/src/lib/api-error.ts@@ -0,0 +1,106 @@+/**+ * User-facing error shape for the dashboard REST layer.+ *+ * `fetchJSON` used to throw `new Error("<status>: <raw body>")`, and ~40 toast+ * call sites interpolated the Error object (`Error: ${e}`), so users saw+ * `Error: Error: 404: {"detail":"Server 'foo' not found"}`. This module turns+ * that into a plain sentence (`Server 'foo' not found`) while keeping the+ * status and raw body on the error object for diagnostics.+ */++/** The dashboard's own backend could not be reached at all (fetch rejected). */+export const API_UNREACHABLE_MESSAGE =+ "Hermes dashboard cannot reach the Hermes service. Is `hermes dashboard` still running?";++/** Status → plain sentence, used when the body carries no usable `detail`. */+const STATUS_COPY: Record<number, string> = {+ 400: "The dashboard sent a request the server could not understand.",+ 401: "Your dashboard session has expired. Reload the page to sign in again.",+ 403: "You are not allowed to do that on this dashboard.",+ 404: "The server could not find what the dashboard asked for.",+ 409: "That change conflicts with the current state on the server.",+ 413: "That upload is too large for the server to accept.",+ 422: "Some of the entered values are not valid.",+ 429: "Too many requests. Wait a moment and try again.",+ 500: "The Hermes service hit an internal error.",+ 502: "The dashboard proxy could not reach the Hermes service.",+ 503: "The Hermes service is not ready yet. Try again in a moment.",+ 504: "The Hermes service took too long to respond.",+};++export function humanizeStatus(status: number): string {+ return STATUS_COPY[status] ?? `The Hermes service answered with an unexpected error (${status}).`;+}++/** Pull a human sentence out of a FastAPI-style error body, or null. */+export function extractDetail(body: string): string | null {+ const text = body.trim();+ if (!text) return null;+ if (text.startsWith("{") || text.startsWith("[")) {+ try {+ const parsed: unknown = JSON.parse(text);+ if (parsed && typeof parsed === "object") {+ const record = parsed as Record<string, unknown>;+ for (const key of ["detail", "message", "error"]) {+ const value = record[key];+ if (typeof value === "string" && value.trim()) return value.trim();+ // FastAPI validation errors: detail is a list of {msg, loc}.+ if (Array.isArray(value)) {+ const msgs = value+ .map((item) => (item && typeof item === "object" ? (item as { msg?: unknown }).msg : null))+ .filter((m): m is string => typeof m === "string");+ if (msgs.length) return msgs.join("; ");+ }+ }+ }+ return null;+ } catch {+ return null;+ }+ }+ if (text.startsWith("<")) return null; // HTML error page from a proxy+ return text.length <= 300 ? text : null;+}++export class ApiError extends Error {+ /** HTTP status; 0 when the request never reached the server. */+ readonly status: number;+ /** Raw response body (or the transport error text) for a Copy-details action. */+ readonly body: string;+ /** Request URL (path only), for diagnostics. */+ readonly url: string;++ constructor(message: string, init: { status: number; body: string; url: string }) {+ super(message);+ this.name = "ApiError";+ this.status = init.status;+ this.body = init.body;+ this.url = init.url;+ }++ /** Multi-line technical detail for a Copy-details action or console. */+ get details(): string {+ const head = this.status ? `HTTP ${this.status} ${this.url}` : `network failure ${this.url}`;+ return this.body ? `${head}\n${this.body}` : head;+ }+}++export function apiErrorFromResponse(status: number, body: string, url: string): ApiError {+ const detail = extractDetail(body);+ return new ApiError(detail ?? humanizeStatus(status), { status, body, url });+}++export function apiErrorFromNetworkFailure(cause: unknown, url: string): ApiError {+ const body = cause instanceof Error ? `${cause.name}: ${cause.message}` : String(cause);+ return new ApiError(API_UNREACHABLE_MESSAGE, { status: 0, body, url });+}++/**+ * The one way to turn a caught `unknown` into toast/inline text. Never yields+ * a `Error: Error:` double prefix because it reads `.message`, not `String(e)`.+ */+export function errorMessage(err: unknown): string {+ if (err instanceof Error) return err.message || err.name;+ if (typeof err === "string") return err;+ return String(err);+}diff --git a/web/src/lib/api.ts b/web/src/lib/api.tsindex 7463b6efb42..d65aa11d35e 100644--- a/web/src/lib/api.ts+++ b/web/src/lib/api.ts@@ -28,6 +28,7 @@ import {attemptDashboardTokenReloadOnce,clearDashboardTokenReloadAttempt,} from "@/lib/dashboard-auth-reload";+import { apiErrorFromNetworkFailure, apiErrorFromResponse } from "@/lib/api-error";// Ephemeral session token for protected endpoints.// Injected into index.html by the server — never fetched via API.@@ -119,15 +120,26 @@ export async function fetchJSON<T>(if (token) {setSessionHeader(headers, token);}- const res = await fetch(`${BASE}${url}`, {- ...init,- headers,- // ``credentials: 'include'`` so the cookie-auth path (gated mode) works- // for any fetch routed through here. Loopback mode is unaffected — the- // server doesn't read cookies and the legacy session-token header is- // already attached above.- credentials: init?.credentials ?? "include",- });+ let res: Response;+ try {+ res = await fetch(`${BASE}${url}`, {+ ...init,+ headers,+ // ``credentials: 'include'`` so the cookie-auth path (gated mode) works+ // for any fetch routed through here. Loopback mode is unaffected — the+ // server doesn't read cookies and the legacy session-token header is+ // already attached above.+ credentials: init?.credentials ?? "include",+ });+ } catch (cause) {+ // fetch() only rejects when the request never got a response: the+ // backend is down, the port is closed, or the network dropped. Tell the+ // user that in words instead of `TypeError: Failed to fetch`.+ const err = apiErrorFromNetworkFailure(cause, url);+ // The toast shows only the sentence; keep status/path/body in the console for bug reports.+ console.warn("[api]", err.details);+ throw err;+ }if (res.status === 401) {// Phase 6: the gated middleware emits a structured envelope so the// SPA can full-page-navigate to /login on session expiry. Parse it,@@ -185,7 +197,9 @@ export async function fetchJSON<T>(}if (!res.ok) {const text = await res.text().catch(() => res.statusText);- throw new Error(`${res.status}: ${text}`);+ const err = apiErrorFromResponse(res.status, text, url);+ console.warn("[api]", err.details);+ throw err;}return res.json();}@@ -213,7 +227,7 @@ export async function getWsTicket(): Promise<{ ticket: string; ttl_seconds: numbcredentials: "include",});if (!res.ok) {- throw new Error(`/api/auth/ws-ticket: HTTP ${res.status}`);+ throw apiErrorFromResponse(res.status, await res.text().catch(() => ""), "/api/auth/ws-ticket");}return res.json();}diff --git a/web/src/lib/chat-sidebar-banner.test.ts b/web/src/lib/chat-sidebar-banner.test.tsnew file mode 100644index 00000000000..317e42f8ac6--- /dev/null+++ b/web/src/lib/chat-sidebar-banner.test.ts@@ -0,0 +1,36 @@+import { describe, expect, it } from 'vitest'++import { SIDECAR_DISCONNECTED_MESSAGE, credentialWarning, sidecarErrorMessage } from './chat-sidebar-banner'++describe('credentialWarning', () => {+ it('rewrites the gateway probe into a sentence that names the provider and the fix', () => {+ const w = credentialWarning("No API key configured for provider 'openrouter'. First message will fail.")+ expect(w?.provider).toBe('openrouter')+ expect(w?.message).toContain('openrouter')+ expect(w?.message).toMatch(/Keys/)+ expect(w?.message).not.toContain('First message will fail')+ })++ it('passes unknown warnings through untouched and ignores empty input', () => {+ expect(credentialWarning('OAuth token for anthropic expires in 2 minutes')?.message).toBe(+ 'OAuth token for anthropic expires in 2 minutes'+ )+ expect(credentialWarning(undefined)).toBeNull()+ expect(credentialWarning('')).toBeNull()+ })+})++describe('sidecarErrorMessage', () => {+ it('collapses transport jargon into the side-panel sentence and keeps real errors', () => {+ for (const raw of [+ 'WebSocket connection failed',+ 'WebSocket closed',+ 'gateway not connected',+ 'Session token not available — page must be served by the Hermes dashboard server'+ ]) {+ expect(sidecarErrorMessage(raw)).toBe(SIDECAR_DISCONNECTED_MESSAGE)+ }+ expect(SIDECAR_DISCONNECTED_MESSAGE).toContain('Chat still works')+ expect(sidecarErrorMessage("Profile 'nope' not found")).toBe("Profile 'nope' not found")+ })+})diff --git a/web/src/lib/chat-sidebar-banner.ts b/web/src/lib/chat-sidebar-banner.tsnew file mode 100644index 00000000000..5b532b50007--- /dev/null+++ b/web/src/lib/chat-sidebar-banner.ts@@ -0,0 +1,52 @@+/**+ * Copy for the ChatSidebar banner: the sidecar (JSON-RPC over /api/ws) and+ * the credential probe the gateway sends in `session.info`.+ *+ * Pure helpers so the wording is testable without React.+ */++/** The side panel could not connect; the chat itself is unaffected. */+export const SIDECAR_DISCONNECTED_MESSAGE =+ 'The chat side panel (model and tool activity) could not connect. Chat still works. Click Reconnect side panel to try again.'++/** Transport-level texts the shared JSON-RPC client can throw. All mean "sidecar down". */+const SIDECAR_TRANSPORT_ERRORS = [+ 'WebSocket connection failed',+ 'WebSocket closed',+ 'gateway not connected',+ 'Session token not available',+ 'heartbeat acknowledgement timed out'+]++/**+ * Map a sidecar connect/RPC error to the banner sentence. Transport jargon+ * collapses to SIDECAR_DISCONNECTED_MESSAGE; anything else (a real gateway+ * error payload, e.g. a bad profile name) is shown as-is.+ */+export function sidecarErrorMessage(raw: string): string {+ return SIDECAR_TRANSPORT_ERRORS.some(needle => raw.includes(needle)) ? SIDECAR_DISCONNECTED_MESSAGE : raw+}++/** Parsed credential warning from the gateway's `_probe_credentials`. */+export interface CredentialWarning {+ provider: string | null+ message: string+}++const NO_KEY_RE = /No API key configured for provider '([^']+)'/++/**+ * Rewrite the gateway's "No API key configured for provider 'x'. First message+ * will fail." into a sentence that names the fix. Unknown warnings pass+ * through unchanged (provider null) so nothing is lost.+ */+export function credentialWarning(raw: string | undefined | null): CredentialWarning | null {+ if (!raw) return null+ const match = raw.match(NO_KEY_RE)+ if (!match) return { provider: null, message: raw }+ const provider = match[1]+ return {+ provider,+ message: `No API key set for ${provider}, so messages will fail. Add a key under Keys, or pick a different provider.`+ }+}diff --git a/web/src/lib/cron-job.ts b/web/src/lib/cron-job.tsindex de4fa9fc47f..abcbcd33512 100644--- a/web/src/lib/cron-job.ts+++ b/web/src/lib/cron-job.ts@@ -74,6 +74,16 @@ export function cronJobHasExecutionContent(return Boolean(asString(job.prompt).trim() || asString(job.script).trim() || skills.length);}+/** Focus a cron editor input by id (the editor renders `${idPrefix}-script`, etc.). */+export function focusCronField(id: string): void {+ if (typeof document === "undefined") return;+ const el = document.getElementById(id);+ if (el instanceof HTMLElement) {+ el.focus();+ el.scrollIntoView?.({ block: "center" });+ }+}+export function cronJobFormFromJob(job: CronJob): CronJobFormState {const storedRefs = splitCronList(job.context_from);// Raw store records carry the reserved "self" entry inside context_from;diff --git a/web/src/lib/events-reconnect.test.ts b/web/src/lib/events-reconnect.test.tsindex e059c7c225c..4fa7899506e 100644--- a/web/src/lib/events-reconnect.test.ts+++ b/web/src/lib/events-reconnect.test.ts@@ -106,8 +106,20 @@ describe("reconnect message copy", () => {expect(eventsReconnectingMessage(30_000)).toContain("30s");});- it("names the close code in the rejection message", () => {- expect(eventsRejectedMessage(4403)).toContain("4403");+ it("tells the user to reload on an auth rejection without printing the close code", () => {+ expect(eventsRejectedMessage(4403)).toMatch(/reload the page/i);+ expect(eventsRejectedMessage(4403)).not.toContain("4403");+ });++ it("never names the transport ('events feed', 'WebSocket') in user-facing copy", () => {+ for (const message of [+ EVENTS_DISCONNECTED_MESSAGE,+ eventsReconnectingMessage(1_000),+ eventsRejectedMessage(4401),+ eventsGaveUpMessage(),+ ]) {+ expect(message).not.toMatch(/events feed|websocket/i);+ }});it("does not reference the tools box removed in #51737", () => {diff --git a/web/src/lib/events-reconnect.ts b/web/src/lib/events-reconnect.tsindex 4714b357d87..fb99fef7496 100644--- a/web/src/lib/events-reconnect.ts+++ b/web/src/lib/events-reconnect.ts@@ -55,19 +55,34 @@ export function isEventsAuthRejection(code: number | undefined): boolean {// The sidebar's banner is shared with `info.credential_warning` and with the// JSON-RPC sidecar's errors, so the events socket may only clear a message it-// wrote itself. Everything this module can put in the banner is listed here.-export const EVENTS_DISCONNECTED_MESSAGE = 'events feed disconnected — the chat title may not update'+// wrote itself. Everything this module can put in the banner starts with+// EVENTS_FEED_PREFIX so `isEventsFeedMessage` can recognise it.+//+// "Live tool activity" is what the feed is to the user: the sidebar's tool+// list and the chat title. Never name the transport or print a close code —+// those go to the console (ChatSidebar logs them) for diagnosis.+const EVENTS_FEED_PREFIX = 'Live tool activity '++export const EVENTS_DISCONNECTED_MESSAGE = `${EVENTS_FEED_PREFIX}paused — the chat title may not update`export function eventsReconnectingMessage(delayMs: number): string {- return `events feed disconnected — reconnecting in ${Math.round(delayMs / 1000)}s…`+ return `${EVENTS_FEED_PREFIX}paused — reconnecting in ${Math.round(delayMs / 1000)}s…`}+/** Auth rejection (4401/4403): the login expired, only a reload mints a new one.+ * The code is logged by the caller; it never appears in user text. */export function eventsRejectedMessage(code: number): string {- return `events feed rejected (${code}) — reload the page`+ void code+ return `${EVENTS_FEED_PREFIX}stopped (your login expired). Reload the page to resume.`}export function eventsGaveUpMessage(): string {- return `events feed disconnected — gave up after ${EVENTS_MAX_RECONNECT_ATTEMPTS} attempts, reload the page`+ return `${EVENTS_FEED_PREFIX}stopped after ${EVENTS_MAX_RECONNECT_ATTEMPTS} reconnect attempts. Click Reconnect side panel, or reload the page.`+}++/** True for the auth-rejection message, which needs a Reload button rather than Reconnect. */+export function isEventsAuthRejectionMessage(message: string | null): boolean {+ return message === eventsRejectedMessage(4401)}/**@@ -80,5 +95,5 @@ export function isEventsFeedMessage(message: string | null): boolean {return false}- return message.startsWith('events feed ')+ return message.startsWith(EVENTS_FEED_PREFIX)}diff --git a/web/src/lib/load-error-copy.test.ts b/web/src/lib/load-error-copy.test.tsnew file mode 100644index 00000000000..052fdf15fb7--- /dev/null+++ b/web/src/lib/load-error-copy.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from "vitest";++import { en } from "@/i18n/en";+import { loadErrorCopy } from "./load-error-copy";++describe("loadErrorCopy", () => {+ it("fills the translated template with what failed and the detail line", () => {+ const copy = loadErrorCopy(en.common, en.cron.loadWhat!, "The Hermes service hit an internal error.");+ expect(copy.title).toContain("cron jobs");+ expect(copy.title).not.toContain("{what}");+ expect(copy.title).toContain(en.common.retry);+ expect(copy.details).toContain("internal error");+ expect(copy.details).not.toContain("{detail}");+ });++ it("omits the details line when there is no detail", () => {+ expect(loadErrorCopy(en.common, en.skills.loadWhat!, null).details).toBeNull();+ expect(loadErrorCopy(en.common, en.skills.loadWhat!, "").details).toBeNull();+ });++ it("keeps the page strings in the locale table rather than the component", () => {+ for (const key of [en.skills.browseHub, en.skills.createSkill, en.cron.scriptRequired]) {+ expect(typeof key).toBe("string");+ expect(key!.trim()).not.toBe("");+ }+ // The script-only message names the field, not the `no_agent` config key.+ expect(en.cron.scriptRequired).toContain("Script");+ expect(en.cron.scriptRequired).not.toContain("no_agent");+ });+});diff --git a/web/src/lib/load-error-copy.ts b/web/src/lib/load-error-copy.tsnew file mode 100644index 00000000000..a00938a4801--- /dev/null+++ b/web/src/lib/load-error-copy.ts@@ -0,0 +1,16 @@+import { en } from "@/i18n/en";++/** Fill the `{what}` / `{detail}` placeholders of the "could not load" card copy.+ * Kept out of the component so the copy shape is testable without rendering. */+export function loadErrorCopy(+ t: { loadFailed?: string; loadFailedDetails?: string },+ what: string,+ detail?: string | null,+): { title: string; details: string | null } {+ const loadFailed = t.loadFailed ?? en.common.loadFailed!;+ const loadFailedDetails = t.loadFailedDetails ?? en.common.loadFailedDetails!;+ return {+ title: loadFailed.replace("{what}", what),+ details: detail ? loadFailedDetails.replace("{detail}", detail) : null,+ };+}diff --git a/web/src/lib/pty-close-copy.test.ts b/web/src/lib/pty-close-copy.test.tsnew file mode 100644index 00000000000..9f8786d63e6--- /dev/null+++ b/web/src/lib/pty-close-copy.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from 'vitest'++import {+ PTY_GAVE_UP_BANNER,+ PTY_RECONNECTING_BANNER,+ PTY_SESSION_ENDED_MESSAGE,+ PTY_START_FAILED_MESSAGE,+ PTY_TOKEN_MISSING_BANNER,+ ptyReconnectExhausted,+ ptyRejectionBanner+} from './pty-close-copy'++describe('pty close copy', () => {+ it('offers a Reload action for the stale-token and missing-token cases without naming auth internals', () => {+ const stale = ptyRejectionBanner(4401)+ expect(stale?.action).toBe('reload')+ expect(stale?.text).toMatch(/reload the page/i)+ expect(stale?.text).not.toMatch(/auth failed|bad-token|4401/i)++ expect(PTY_TOKEN_MISSING_BANNER.action).toBe('reload')+ expect(PTY_TOKEN_MISSING_BANNER.text).not.toMatch(/session token/i)+ expect(PTY_TOKEN_MISSING_BANNER.text).toContain('hermes dashboard')+ })++ it('never prints a WebSocket close code in user-facing text', () => {+ const texts = [+ PTY_RECONNECTING_BANNER,+ PTY_GAVE_UP_BANNER.text,+ PTY_SESSION_ENDED_MESSAGE,+ ...[4401, 4403, 4404, 4408].map(code => ptyRejectionBanner(code)!.text)+ ]+ for (const text of texts) {+ expect(text).not.toMatch(/\b(code\s*)?\d{4}\b/)+ }+ // Transient drops and the agent's own exit are not rejections: the caller+ // must route them to the reconnect ladder / restart affordance instead.+ expect(ptyRejectionBanner(1006)).toBeNull()+ expect(ptyRejectionBanner(4410)).toBeNull()+ })++ it('says retries stopped and points at the server after the last attempt', () => {+ expect(ptyReconnectExhausted(5, 5)).toBe(true)+ expect(ptyReconnectExhausted(4, 5)).toBe(false)+ expect(PTY_GAVE_UP_BANNER.action).toBe('check-server')+ expect(PTY_GAVE_UP_BANNER.text).toContain('hermes dashboard')+ expect(PTY_SESSION_ENDED_MESSAGE).toMatch(/crashed/i)+ expect(PTY_SESSION_ENDED_MESSAGE).toMatch(/logs/i)+ })+})++describe('start-failed overlay copy', () => {+ it('stays neutral: close 1011 also means "no terminal support here", where retrying cannot help', () => {+ expect(PTY_START_FAILED_MESSAGE).toMatch(/printed above/)+ expect(PTY_START_FAILED_MESSAGE).not.toMatch(/fix it|Start new session/)+ expect(PTY_START_FAILED_MESSAGE).not.toMatch(/1011/)+ })+})diff --git a/web/src/lib/pty-close-copy.ts b/web/src/lib/pty-close-copy.tsnew file mode 100644index 00000000000..0ad3913e506--- /dev/null+++ b/web/src/lib/pty-close-copy.ts@@ -0,0 +1,71 @@+/**+ * User-facing copy for the dashboard chat (PTY) connection lifecycle.+ *+ * Pure: ChatPage owns the socket and state, this module owns the words and+ * the "which button goes with this failure" decision, so both can be tested+ * without xterm or a fake WebSocket. WebSocket close codes never appear in+ * user text — ChatPage logs them to the console instead.+ */++export type PtyBannerAction = 'reload' | 'check-server' | null++export interface PtyBanner {+ text: string+ action: PtyBannerAction+}++/** Chat tab opened without the injected login token (loopback mode only). */+export const PTY_TOKEN_MISSING_BANNER: PtyBanner = {+ text: "Chat can't connect because this page was opened without a login token. Reload the page, or start it again with `hermes dashboard` in a terminal.",+ action: 'reload'+}++/** Rejection close codes the server sends before any PTY exists. `reason` is logged, not shown. */+const REJECTION_BANNERS: Record<number, PtyBanner> = {+ 4401: {+ text: "This chat tab's login expired (the dashboard server was restarted). Reload the page to reconnect.",+ action: 'reload'+ },+ 4403: {+ text: 'The dashboard refused this chat connection because the page address does not match the server it was opened from. Open the dashboard from the address `hermes dashboard` printed.',+ action: null+ },+ 4404: {+ text: 'This Hermes server does not offer the terminal chat. Update Hermes (`hermes update`) and reload the page.',+ action: 'reload'+ },+ 4408: {+ text: 'This Hermes server only accepts chat from the machine it runs on. Open the dashboard on that machine, or start it with a public bind.',+ action: null+ }+}++export function ptyRejectionBanner(code: number): PtyBanner | null {+ return REJECTION_BANNERS[code] ?? null+}++/** Shown while the automatic reconnect ladder is running. No close code. */+export const PTY_RECONNECTING_BANNER = 'Chat connection interrupted. Reconnecting...'++/** Shown after the last automatic attempt failed (overlay + banner). */+export const PTY_GAVE_UP_BANNER: PtyBanner = {+ text: 'Lost connection to the Hermes dashboard server. If you stopped `hermes dashboard`, start it again; otherwise click Reconnect now.',+ action: 'check-server'+}++/** Overlay copy: the hermes --tui child exited; a crash looks identical to `/exit`. */+export const PTY_SESSION_ENDED_MESSAGE =+ 'Chat session ended. If you did not end it yourself, the agent may have crashed — open Logs to see why, or start a new session.'++/** Overlay copy when the server could not start the chat at all (close 1011; details are in the+ * terminal). Neutral on purpose: 1011 also covers "no terminal support on this platform"+ * (native Windows), where retrying cannot help, so the text must not promise a fix. */+export const PTY_START_FAILED_MESSAGE = 'Chat could not start. The reason is printed above.'++/** Terminal footer line replacing `[session ended (code N)]`. */+export const PTY_SESSION_ENDED_TERMINAL_LINE = '[chat session ended]'++/** True once the ladder has used its last attempt and that attempt also failed. */+export function ptyReconnectExhausted(attempt: number, maxAttempts: number): boolean {+ return attempt >= maxAttempts+}diff --git a/web/src/lib/pty-reconnect.test.ts b/web/src/lib/pty-reconnect.test.tsindex 4c4b6fd4903..995076d41b6 100644--- a/web/src/lib/pty-reconnect.test.ts+++ b/web/src/lib/pty-reconnect.test.ts@@ -36,6 +36,19 @@ describe('shouldReconnectPtyOnPageResume', () => {}})+ it('does not restart the ladder on focus/online after it gave up; only the Reconnect button does', () => {+ expect(+ shouldReconnectPtyOnPageResume({+ isActive: true,+ visibilityState: 'visible',+ online: true,+ socketReadyState: 3,+ ptyState: 'closed',+ reconnectGaveUp: true+ })+ ).toBe(false)+ })+it('does not reconnect an open socket on visible resume', () => {expect(shouldReconnectPtyOnPageResume({diff --git a/web/src/lib/pty-reconnect.ts b/web/src/lib/pty-reconnect.tsindex 71f34961214..4a6ce8cf7ab 100644--- a/web/src/lib/pty-reconnect.ts+++ b/web/src/lib/pty-reconnect.ts@@ -54,6 +54,8 @@ export interface PtyResumeReconnectInput {socketReadyState?: number | nullptyState: PtyConnectionStateconnectInFlight?: boolean+ /** The automatic ladder used its last attempt; only the explicit Reconnect button restarts it. */+ reconnectGaveUp?: boolean}const WS_CONNECTING = 0@@ -67,11 +69,17 @@ export function shouldReconnectPtyOnPageResume({online,socketReadyState,ptyState,- connectInFlight+ connectInFlight,+ reconnectGaveUp}: PtyResumeReconnectInput): boolean {if (!isActive || !online || visibilityState === 'hidden') {return false}+ // The overlay says retries stopped: a tab focus or network blip must not+ // silently restart the whole ladder behind it.+ if (reconnectGaveUp) {+ return false+ }if (ptyState === 'ended') {return false}diff --git a/web/src/lib/shared-gateway.test.ts b/web/src/lib/shared-gateway.test.tsindex 8427bec1ea6..8dc8abfcef5 100644--- a/web/src/lib/shared-gateway.test.ts+++ b/web/src/lib/shared-gateway.test.ts@@ -1,6 +1,8 @@import { describe, expect, it } from "vitest";+import { ApiError } from "./api-error";import {+ gatewayActionFailedMessage,servedProfileRefusal,sharedGatewayProfiles,} from "./shared-gateway";@@ -26,5 +28,32 @@ describe("servedProfileRefusal", () => {);expect(servedProfileRefusal(err)).toMatch(/^The default gateway already serves profile 'alpha'/);expect(servedProfileRefusal(new Error("500: boom"))).toBeNull();+ const apiErr = new ApiError("The default gateway already serves profile 'beta'", {+ status: 409,+ body: "",+ url: "/api/gateway/start",+ });+ expect(servedProfileRefusal(apiErr)).toMatch(/^The default gateway already serves profile 'beta'/);+ expect(+ servedProfileRefusal(new ApiError("boom", { status: 500, body: "", url: "/x" })),+ ).toBeNull();+ });+});++describe("gatewayActionFailedMessage", () => {+ it("does not double punctuation when the detail already ends a sentence", () => {+ const text = gatewayActionFailedMessage("restart", "Is `hermes dashboard` still running?");+ expect(text).not.toMatch(/[?!.]\./);+ expect(text).toMatch(/^Could not restart the gateway: /);+ expect(text).toContain("still running? Open Logs");+ });++ it("skips the Logs pointer when the dashboard itself is unreachable", () => {+ const unreachable = new ApiError("down", { status: 0, body: "", url: "/api/gateway/start" });+ expect(gatewayActionFailedMessage("start", "down", unreachable)).not.toContain("Logs");++ const serverError = new ApiError("boom", { status: 500, body: "", url: "/api/gateway/start" });+ expect(gatewayActionFailedMessage("start", "boom.", serverError)).toContain("Open Logs for details.");+ expect(gatewayActionFailedMessage("start", "boom.", serverError)).not.toContain("boom..");});});diff --git a/web/src/lib/shared-gateway.ts b/web/src/lib/shared-gateway.tsindex cbaba33bc52..c4e9873dd94 100644--- a/web/src/lib/shared-gateway.ts+++ b/web/src/lib/shared-gateway.ts@@ -1,4 +1,5 @@import type { StatusResponse } from "@/lib/api";+import { ApiError } from "@/lib/api-error";/** Profiles a gateway restart would blip when the managed profile is carried by the shared* multiplexer (default first). `null` for a standalone gateway or an older backend without@@ -23,9 +24,59 @@ export function sharedGatewayRestartedMessage(count: number): string {return `Shared gateway restarted (${count} ${count === 1 ? "bot" : "bots"})`;}-/** The REST layer throws `"<status>: <body>"`; a 409 on gateway start/stop for a served profile- * carries the multiplexer explanation in `detail`. Return it as a plain sentence, else null. */+/** Raw `gateway_state` values (gateway/status.py) → what they mean for the user. */+const GATEWAY_STATE_COPY: Record<string, string> = {+ running: "Running — messaging channels are online",+ starting: "Starting up",+ degraded: "Running with some channels offline — see Logs",+ stopped: "Stopped — messaging channels are offline",+ startup_failed: "Failed to start — see Logs",+};++/** Plain description of the gateway's state; null/unknown falls back to running/stopped. */+export function gatewayStateDescription(+ state: string | null | undefined,+ running: boolean | undefined,+): string {+ if (state && GATEWAY_STATE_COPY[state]) return GATEWAY_STATE_COPY[state];+ return running ? GATEWAY_STATE_COPY.running : GATEWAY_STATE_COPY.stopped;+}++/** True when the state points at Logs as the next step. */+export function gatewayStateNeedsLogs(state: string | null | undefined): boolean {+ return state === "startup_failed" || state === "degraded";+}++const GATEWAY_VERB_COPY: Record<"start" | "stop" | "restart", string> = {+ start: "Could not start the gateway",+ stop: "Could not stop the gateway",+ restart: "Could not restart the gateway",+};++/** Toast for a failed Start/Stop/Restart: lead with the outcome, then the detail, then the fix.+ * `error` (the caught value) decides whether the Logs pointer makes sense: when the dashboard+ * itself is unreachable (ApiError.status 0) the Logs page cannot load either, so it is omitted. */+export function gatewayActionFailedMessage(+ verb: "start" | "stop" | "restart",+ detail: string,+ error?: unknown,+): string {+ const trimmed = detail.trim().replace(/\.+$/, "");+ const ended = /[!?]$/.test(trimmed);+ const head = trimmed+ ? `${GATEWAY_VERB_COPY[verb]}: ${trimmed}${ended ? "" : "."}`+ : `${GATEWAY_VERB_COPY[verb]}.`;+ const unreachable = error instanceof ApiError && error.status === 0;+ return unreachable ? head : `${head} Open Logs for details.`;+}++/** A 409 on gateway start/stop for a served profile carries the multiplexer explanation in+ * `detail`, which `fetchJSON` already lifts into `ApiError.message`. Return it, else null. */export function servedProfileRefusal(error: unknown): string | null {+ if (error instanceof ApiError) {+ return error.status === 409 ? error.message : null;+ }+ // Pre-ApiError shape (`"409: {...}"`) from callers that still hand-roll fetch.const text = error instanceof Error ? error.message : String(error ?? "");if (!text.startsWith("409")) return null;const detail = text.match(/"detail"\s*:\s*"([^"]+)"/)?.[1];diff --git a/web/src/pages/AnalyticsPage.tsx b/web/src/pages/AnalyticsPage.tsxindex 2583be96980..f32a27713fa 100644--- a/web/src/pages/AnalyticsPage.tsx+++ b/web/src/pages/AnalyticsPage.tsx@@ -24,6 +24,7 @@ import { Card, CardContent, CardHeader, CardTitle } from "@nous-research/ui/ui/cimport { usePageHeader } from "@/contexts/usePageHeader";import { useI18n } from "@/i18n";import { PluginSlot } from "@/plugins";+import { errorMessage } from "@/lib/api-error";const PERIODS = [{ label: "7d", days: 7 },@@ -433,7 +434,7 @@ export default function AnalyticsPage() {api.getAnalytics(days).then(setData)- .catch((err) => setError(String(err)))+ .catch((err) => setError(errorMessage(err))).finally(() => setLoading(false));}, [days, showTokens]);diff --git a/web/src/pages/ChannelsPage.tsx b/web/src/pages/ChannelsPage.tsxindex e570af9e3f0..66c9676c8b8 100644--- a/web/src/pages/ChannelsPage.tsx+++ b/web/src/pages/ChannelsPage.tsx@@ -36,6 +36,7 @@ import type {import { useModalBehavior } from "@/hooks/useModalBehavior";import { usePageHeader } from "@/contexts/usePageHeader";import { cn, themedBody } from "@/lib/utils";+import { errorMessage } from "@/lib/api-error";// State → badge mapping. The backend emits a small, fixed vocabulary plus// whatever the live gateway runtime reports (connected/disconnected/fatal).@@ -166,7 +167,7 @@ export default function ChannelsPage() {setEnvPath(res.env_path || "~/.hermes/.env");setGatewayStartCommand(res.gateway_start_command || "hermes gateway start");})- .catch((e) => showToast(`Error: ${e}`, "error"));+ .catch((e) => showToast(`Could not load channels: ${errorMessage(e)}`, "error"));}, [showToast]);useEffect(() => {@@ -227,7 +228,7 @@ export default function ChannelsPage() {await load();if (result.hot_served) setTimeout(() => void load(), 4000);} catch (e) {- showToast(`Failed to save: ${e}`, "error");+ showToast(`Failed to save: ${errorMessage(e)}`, "error");} finally {setSaving(false);}@@ -248,7 +249,7 @@ export default function ChannelsPage() {if (result.hot_served) setTimeout(() => void load(), 4000);else setRestartNeeded(true);} catch (e) {- showToast(`Error: ${e}`, "error");+ showToast(`Could not update the channel: ${errorMessage(e)}`, "error");} finally {setTogglingId(null);}@@ -260,7 +261,7 @@ export default function ChannelsPage() {const res = await api.testMessagingPlatform(platform.id);showToast(`${platform.name}: ${res.message}`, res.ok ? "success" : "error");} catch (e) {- showToast(`Error: ${e}`, "error");+ showToast(`Could not test the channel: ${errorMessage(e)}`, "error");} finally {setTestingId(null);}@@ -275,7 +276,7 @@ export default function ChannelsPage() {// Give the gateway a moment to come up, then refresh status.setTimeout(() => void load(), 4000);} catch (e) {- showToast(`Failed to restart: ${e}`, "error");+ showToast(`Failed to restart: ${errorMessage(e)}`, "error");} finally {setRestarting(false);}diff --git a/web/src/pages/ChatPage.test.tsx b/web/src/pages/ChatPage.test.tsxindex 97a4f009a81..77b0d7d257b 100644--- a/web/src/pages/ChatPage.test.tsx+++ b/web/src/pages/ChatPage.test.tsx@@ -4,7 +4,11 @@ import { createRoot, type Root } from "react-dom/client";import { MemoryRouter } from "react-router";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { PTY_TICKET_TIMEOUT_MS } from "@/lib/pty-reconnect";+import {+ PTY_RECONNECT_MAX_ATTEMPTS,+ PTY_RECONNECT_MAX_MS,+ PTY_TICKET_TIMEOUT_MS,+} from "@/lib/pty-reconnect";class FakeFitAddon {fit() {}@@ -275,6 +279,96 @@ describe("ChatPage", () => {expect(maybeReloadForLoopbackWsAuthFailure).toHaveBeenCalledWith(4401);});+ it("explains an expired login in plain words with a Reload button when auto-reload is spent", async () => {+ const { default: ChatPage } = await import("./ChatPage");+ await render(+ <MemoryRouter initialEntries={["/chat"]}>+ <ChatPage isActive />+ </MemoryRouter>,+ );+ await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));++ await act(async () => {+ FakeWebSocket.instances[0].onclose?.({ code: 4401, reason: "auth: bad-token", wasClean: true });+ });++ const alert = container.querySelector('[role="alert"]');+ expect(alert?.textContent).toMatch(/login expired/i);+ expect(alert?.textContent).not.toMatch(/auth failed|bad-token|4401/i);+ const labels = Array.from(container.querySelectorAll("button")).map((b) => b.textContent?.trim());+ expect(labels).toContain("Reload page");+ });++ it("renders Start new session after the server could not start the chat (1011)", async () => {+ const { default: ChatPage } = await import("./ChatPage");+ await render(+ <MemoryRouter initialEntries={["/chat"]}>+ <ChatPage isActive />+ </MemoryRouter>,+ );+ await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));++ await act(async () => {+ FakeWebSocket.instances[0].onclose?.({ code: 1011, reason: "", wasClean: true });+ });++ expect(container.textContent).toMatch(/Chat could not start/);+ const labels = Array.from(container.querySelectorAll("button")).map((b) => b.textContent?.trim());+ expect(labels).toContain("Start new session");+ });++ it("offers Open logs when the agent process ended, since a crash looks like /exit", async () => {+ const { default: ChatPage } = await import("./ChatPage");+ await render(+ <MemoryRouter initialEntries={["/chat"]}>+ <ChatPage isActive />+ </MemoryRouter>,+ );+ await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));++ await act(async () => {+ FakeWebSocket.instances[0].onclose?.({ code: 4410, reason: "", wasClean: true });+ });++ expect(container.textContent).toMatch(/may have crashed/i);+ const labels = Array.from(container.querySelectorAll("button")).map((b) => b.textContent?.trim());+ expect(labels).toContain("Start new session");+ expect(labels).toContain("Open logs");+ });++ it("stops retrying after the ladder is spent and offers Check server status", async () => {+ vi.useFakeTimers();+ try {+ const { default: ChatPage } = await import("./ChatPage");+ await render(+ <MemoryRouter initialEntries={["/chat"]}>+ <ChatPage isActive />+ </MemoryRouter>,+ );+ await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));++ // Drop the socket abnormally; walk every scheduled retry to failure.+ for (let attempt = 0; attempt <= PTY_RECONNECT_MAX_ATTEMPTS; attempt += 1) {+ const sockets = FakeWebSocket.instances.length;+ await act(async () => {+ FakeWebSocket.instances[sockets - 1].onclose?.({ code: 1006, reason: "", wasClean: false });+ });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(PTY_RECONNECT_MAX_MS + 100);+ });+ }++ expect(container.textContent).not.toMatch(/code 1006/);+ expect(container.textContent).toMatch(/Lost connection to the Hermes dashboard server/);+ expect(container.textContent).toContain("hermes dashboard");+ const labels = Array.from(container.querySelectorAll("button")).map((b) => b.textContent?.trim());+ expect(labels).toContain("Reconnect now");+ expect(labels).toContain("Check server status");+ } finally {+ vi.useRealTimers();+ }+ });+it("attaches visualViewport keyboard-inset listeners only while the chat tab is active", async () => {// NS-434 follow-up: ChatPage stays mounted (hidden) on every dashboard// route. The keyboard-inset/scroll-pin listeners must only be live whilediff --git a/web/src/pages/ChatPage.tsx b/web/src/pages/ChatPage.tsxindex 5229e12094a..67140c0589a 100644--- a/web/src/pages/ChatPage.tsx+++ b/web/src/pages/ChatPage.tsx@@ -28,7 +28,7 @@ import { cn } from "@/lib/utils";import { Copy, PanelRight, RotateCcw, X } from "lucide-react";import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";import { createPortal } from "react-dom";-import { useSearchParams } from "react-router";+import { useNavigate, useSearchParams } from "react-router";import { ChatSidebar } from "@/components/ChatSidebar";import { ChatSessionList } from "@/components/ChatSessionList";@@ -80,9 +80,21 @@ import {uploadChatImage,} from "@/lib/chatImagePaste";import { maybeReloadForLoopbackWsAuthFailure } from "@/lib/dashboard-auth-reload";+import {+ PTY_GAVE_UP_BANNER,+ PTY_RECONNECTING_BANNER,+ PTY_SESSION_ENDED_MESSAGE,+ PTY_SESSION_ENDED_TERMINAL_LINE,+ PTY_START_FAILED_MESSAGE,+ PTY_TOKEN_MISSING_BANNER,+ ptyReconnectExhausted,+ ptyRejectionBanner,+ type PtyBannerAction,+} from "@/lib/pty-close-copy";import { PluginSlot } from "@/plugins";import { useTheme } from "@/themes";import { useProfileScope } from "@/contexts/useProfileScope";+import { errorMessage } from "@/lib/api-error";// Stable per-browser token identifying THIS chat tab's keep-alive PTY session.// Sent as ?attach=; lets a refresh/disconnect reattach to the same live process@@ -213,13 +225,28 @@ export default function ChatPage({ isActive = true }: { isActive?: boolean }) {// In gated (OAuth) mode the server intentionally omits the session token —// the dashboard API layer authenticates the WS via a single-use ticket,// so a missing token there is expected, not an error.- const [banner, setBanner] = useState<string | null>(() =>+ const tokenMissing =typeof window !== "undefined" &&!window.__HERMES_SESSION_TOKEN__ &&- !window.__HERMES_AUTH_REQUIRED__- ? "Session token unavailable. Open this page through `hermes dashboard`, not directly."- : null,+ !window.__HERMES_AUTH_REQUIRED__;+ const [banner, setBanner] = useState<string | null>(() =>+ tokenMissing ? PTY_TOKEN_MISSING_BANNER.text : null,);+ // Which one-click fix (if any) the banner offers next to its text.+ const [bannerAction, setBannerAction] = useState<PtyBannerAction>(() =>+ tokenMissing ? PTY_TOKEN_MISSING_BANNER.action : null,+ );+ // True after the automatic reconnect ladder used its last attempt: the+ // overlay then says so and offers "Check server status" alongside Reconnect.+ const [reconnectGaveUp, setReconnectGaveUp] = useState(false);+ const reconnectGaveUpRef = useRef(false);+ useEffect(() => {+ reconnectGaveUpRef.current = reconnectGaveUp;+ }, [reconnectGaveUp]);+ // Why ptyState is "ended": the agent process exited (/exit or crash), or the+ // server could not start it at all (close 1011; the reason is in the terminal).+ const [endedReason, setEndedReason] = useState<"exited" | "start-failed">("exited");+ const navigate = useNavigate();const [copyState, setCopyState] = useState<"idle" | "copied">("idle");const copyResetRef = useRef<ReturnType<typeof setTimeout> | null>(null);const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);@@ -241,7 +268,6 @@ export default function ChatPage({ isActive = true }: { isActive?: boolean }) {// Covers the blank terminal + blinking-cursor window so users don't think// chat is broken; clears as soon as there is something to show.const [resumeHydrating, setResumeHydrating] = useState(false);- const [lastCloseCode, setLastCloseCode] = useState<number | null>(null);// NS-504: when the agent process exits cleanly (the user typed `/exit`, or// started a new session that ended the current PTY child), the PTY socket// closes with a normal code. Before this fix the terminal just printed@@ -267,7 +293,8 @@ export default function ChatPage({ isActive = true }: { isActive?: boolean }) {ptyInputLineRef.current = "";mobileReplacementInputUntilRef.current = 0;setBanner(null);- setLastCloseCode(null);+ setBannerAction(null);+ setReconnectGaveUp(false);setPtyState("connecting");setReconnectNonce((n) => n + 1);}, [clearReconnectTimer]);@@ -279,7 +306,8 @@ export default function ChatPage({ isActive = true }: { isActive?: boolean }) {ptyInputLineRef.current = "";mobileReplacementInputUntilRef.current = 0;setBanner(null);- setLastCloseCode(null);+ setBannerAction(null);+ setReconnectGaveUp(false);setPtyState("connecting");setReconnectNonce((n) => n + 1);}, [clearReconnectTimer]);@@ -295,7 +323,8 @@ export default function ChatPage({ isActive = true }: { isActive?: boolean }) {mobileReplacementInputUntilRef.current = 0;setSearchParams(next, { replace: true });setBanner(null);- setLastCloseCode(null);+ setBannerAction(null);+ setReconnectGaveUp(false);setPtyState("connecting");setReconnectNonce((n) => n + 1);}, [clearReconnectTimer, searchParams, setSearchParams]);@@ -1153,11 +1182,22 @@ export default function ChatPage({ isActive = true }: { isActive?: boolean }) {if (reconnectTimerRef.current) {return;}- const attempt = Math.min(reconnectAttemptRef.current + 1, PTY_RECONNECT_MAX_ATTEMPTS);+ if (ptyReconnectExhausted(reconnectAttemptRef.current, PTY_RECONNECT_MAX_ATTEMPTS)) {+ // The last automatic attempt also failed: stop chasing a dead+ // backend and tell the user so, with the manual affordances.+ console.warn(`[chat] PTY reconnect gave up after ${PTY_RECONNECT_MAX_ATTEMPTS} attempts (last code=${code ?? "none"})`);+ setBanner(null);+ setBannerAction(null);+ reconnectGaveUpRef.current = true;+ setReconnectGaveUp(true);+ setPtyState("closed");+ return;+ }+ const attempt = reconnectAttemptRef.current + 1;reconnectAttemptRef.current = attempt;const delayMs = ptyReconnectDelayMs(attempt);setBanner(null);- setLastCloseCode(code);+ setBannerAction(null);setPtyState("reconnecting");reconnectTimerRef.current = setTimeout(() => {reconnectTimerRef.current = null;@@ -1198,7 +1238,7 @@ export default function ChatPage({ isActive = true }: { isActive?: boolean }) {url = await api.buildWsUrl("/api/pty", params);} catch (err) {if (unmounting || ticketSuperseded) return;- console.warn(`[chat] PTY ticket request failed: ${err}`);+ console.warn(`[chat] PTY ticket request failed: ${errorMessage(err)}`);failTicketAttempt();return;}@@ -1230,7 +1270,8 @@ export default function ChatPage({ isActive = true }: { isActive?: boolean }) {connectInFlightRef.current = false;reconnectAttemptRef.current = 0;setBanner(null);- setLastCloseCode(null);+ setBannerAction(null);+ setReconnectGaveUp(false);setPtyState("open");blockedInputNoticeRef.current = false;// Connected — cancel any pending reconnect from a prior transient drop.@@ -1359,57 +1400,34 @@ export default function ChatPage({ isActive = true }: { isActive?: boolean }) {// pty_ws in web_server.py); echo it verbatim alongside the close code.const why = ev.reason ? ` reason=${ev.reason}` : "";console.warn(`[chat] PTY WebSocket closed code=${ev.code}${why}`);- setLastCloseCode(ev.code);- if (ev.code === 4401) {- if (maybeReloadForLoopbackWsAuthFailure(ev.code)) {- return;- }- setPtyState("closed");- setBanner(- ev.reason- ? `Auth failed (${ev.reason}). Reload to refresh the session.`- : "Auth failed. Reload the page to refresh the session token.",- );- return;- }- if (ev.code === 4403) {- // Host/Origin mismatch (DNS-rebinding guard).- setPtyState("closed");- setBanner(- ev.reason- ? `Refused: ${ev.reason}.`- : "Refused: request host/origin doesn't match the dashboard.",- );+ if (ev.code === 4401 && maybeReloadForLoopbackWsAuthFailure(ev.code)) {return;}- if (ev.code === 4404) {+ // Server-side rejections (stale token, host mismatch, no PTY endpoint,+ // non-loopback client). `ev.reason` is a machine identifier — it went+ // to the console above; the user gets a sentence and, where a reload+ // fixes it, a Reload button.+ const rejection = ptyRejectionBanner(ev.code);+ if (rejection) {setPtyState("closed");- setBanner(- ev.reason- ? `Chat websocket unavailable: ${ev.reason}.`- : "Chat websocket unavailable on this server.",- );- return;- }- if (ev.code === 4408) {- setPtyState("closed");- setBanner(- ev.reason- ? `Refused: ${ev.reason}.`- : "Refused: your client isn't permitted (server bound to localhost only).",- );+ setBanner(rejection.text);+ setBannerAction(rejection.action);return;}if (ev.code === 1011) {- // Server already wrote an ANSI error frame.- setPtyState("closed");+ // The server could not start the chat (node missing, bad profile,+ // too many terminals open) and already printed why in red inside the+ // terminal. Render the restart affordance instead of a dead pane.+ setEndedReason("start-failed");+ setPtyState("ended");return;}// Keep-alive close-code contract (web_server.pty_ws + pty_session):// 4410 = the agent PROCESS exited (real end) → restart affordance.// 4409 = superseded by a newer tab attaching the same token → stay quiet.if (ev.code === 4410) {- term.write(`\r\n\x1b[90m[session ended]\x1b[0m\r\n`);+ term.write(`\r\n\x1b[90m${PTY_SESSION_ENDED_TERMINAL_LINE}\x1b[0m\r\n`);+ setEndedReason("exited");setPtyState("ended");return;}@@ -1428,9 +1446,8 @@ export default function ChatPage({ isActive = true }: { isActive?: boolean }) {// `/exit`, or started a new session). NS-504: surface an explicit// restart affordance instead of leaving a dead terminal that only a// full page refresh could recover.- term.write(- `\r\n\x1b[90m[session ended (code ${ev.code})]\x1b[0m\r\n`,- );+ term.write(`\r\n\x1b[90m${PTY_SESSION_ENDED_TERMINAL_LINE}\x1b[0m\r\n`);+ setEndedReason("exited");setPtyState("ended");};@@ -1671,6 +1688,7 @@ export default function ChatPage({ isActive = true }: { isActive?: boolean }) {socketReadyState,ptyState: ptyStateRef.current,connectInFlight: connectInFlightRef.current,+ reconnectGaveUp: reconnectGaveUpRef.current,})) {const now = Date.now();@@ -1726,11 +1744,7 @@ export default function ChatPage({ isActive = true }: { isActive?: boolean }) {// dashboard column uses `relative z-2`, which traps `position:fixed`// descendants below those layers (see Toast.tsx).const reconnectBanner =- ptyState === "reconnecting"- ? `Chat connection interrupted${- lastCloseCode ? ` (code ${lastCloseCode})` : ""- }. Reconnecting...`- : null;+ ptyState === "reconnecting" ? PTY_RECONNECTING_BANNER : null;const visibleBanner = banner ?? reconnectBanner;const showReconnectOverlay =ptyState === "reconnecting" || (ptyState === "closed" && !banner);@@ -1831,8 +1845,16 @@ export default function ChatPage({ isActive = true }: { isActive?: boolean }) {{mobileModelToolsPortal}{visibleBanner && (- <div className="border border-warning/50 bg-warning/10 text-warning px-3 py-2 text-xs tracking-wide">- {visibleBanner}+ <div+ role="alert"+ className="flex flex-wrap items-center gap-2 border border-warning/50 bg-warning/10 text-warning px-3 py-2 text-xs tracking-wide"+ >+ <span className="min-w-0 flex-1">{visibleBanner}</span>+ {banner && bannerAction === "reload" && (+ <Button size="sm" outlined onClick={() => window.location.reload()}>+ Reload page+ </Button>+ )}</div>)}@@ -1859,17 +1881,31 @@ export default function ChatPage({ isActive = true }: { isActive?: boolean }) {<div className="tracking-wide">{ptyState === "reconnecting"? "Chat is reconnecting."- : "Chat disconnected."}+ : reconnectGaveUp+ ? PTY_GAVE_UP_BANNER.text+ : "Chat disconnected."}+ </div>+ <div className="flex flex-wrap gap-2">+ <Button+ size="sm"+ outlined+ onClick={reconnectPty}+ prefix={<RotateCcw className="h-4 w-4" />}+ aria-label="Reconnect chat"+ >+ Reconnect now+ </Button>+ {ptyState === "closed" && reconnectGaveUp && (+ <Button+ size="sm"+ ghost+ onClick={() => navigate("/system")}+ aria-label="Check server status"+ >+ Check server status+ </Button>+ )}</div>- <Button- size="sm"- outlined- onClick={reconnectPty}- prefix={<RotateCcw className="h-4 w-4" />}- aria-label="Reconnect chat"- >- Reconnect now- </Button></div></div>)}@@ -1892,16 +1928,29 @@ export default function ChatPage({ isActive = true }: { isActive?: boolean }) {whole page to get a working chat back. */}{ptyState === "ended" && (<div className="absolute inset-0 z-30 flex flex-col items-center justify-center gap-3 bg-black/60">- <div className="text-sm tracking-wide text-white/80">- Session ended.+ <div className="max-w-[min(32rem,calc(100vw-3rem))] text-center text-sm tracking-wide text-white/80">+ {endedReason === "start-failed"+ ? PTY_START_FAILED_MESSAGE+ : PTY_SESSION_ENDED_MESSAGE}+ </div>+ <div className="flex flex-wrap justify-center gap-2">+ <Button+ onClick={startFreshPty}+ prefix={<RotateCcw className="h-4 w-4" />}+ aria-label="Start a new chat session"+ >+ Start new session+ </Button>+ {endedReason === "exited" && (+ <Button+ outlined+ onClick={() => navigate("/logs")}+ aria-label="Open logs"+ >+ Open logs+ </Button>+ )}</div>- <Button- onClick={startFreshPty}- prefix={<RotateCcw className="h-4 w-4" />}- aria-label="Start a new chat session"- >- Start new session- </Button></div>)}diff --git a/web/src/pages/ConfigPage.tsx b/web/src/pages/ConfigPage.tsxindex dcb88282002..1de8fcf6adf 100644--- a/web/src/pages/ConfigPage.tsx+++ b/web/src/pages/ConfigPage.tsx@@ -51,6 +51,7 @@ import { Badge } from "@nous-research/ui/ui/components/badge";import { useI18n } from "@/i18n";import { usePageHeader } from "@/contexts/usePageHeader";import { PluginSlot } from "@/plugins";+import { errorMessage } from "@/lib/api-error";/* ------------------------------------------------------------------ *//* Helpers */@@ -283,7 +284,7 @@ export default function ConfigPage() {await api.saveConfig(config);showToast(t.config.configSaved, "success");} catch (e) {- showToast(`${t.config.failedToSave}: ${e}`, "error");+ showToast(`${t.config.failedToSave}: ${errorMessage(e)}`, "error");} finally {setSaving(false);}@@ -299,7 +300,7 @@ export default function ConfigPage() {.then(setConfig).catch(() => {});} catch (e) {- showToast(`${t.config.failedToSaveYaml}: ${e}`, "error");+ showToast(`${t.config.failedToSaveYaml}: ${errorMessage(e)}`, "error");} finally {setYamlSaving(false);}diff --git a/web/src/pages/CronPage.tsx b/web/src/pages/CronPage.tsxindex 744354cbc31..38f64f4661d 100644--- a/web/src/pages/CronPage.tsx+++ b/web/src/pages/CronPage.tsx@@ -23,6 +23,7 @@ import {cronJobHasExecutionContent,cronJobFormFromJob,cronLastResult,+ focusCronField,type CronJobFormState,} from "@/lib/cron-job";import { DeleteConfirmDialog } from "@/components/DeleteConfirmDialog";@@ -46,11 +47,14 @@ import { Card, CardContent } from "@nous-research/ui/ui/components/card";import { Input } from "@nous-research/ui/ui/components/input";import { Label } from "@nous-research/ui/ui/components/label";import { useI18n } from "@/i18n";+import { en } from "@/i18n/en";import { usePageHeader } from "@/contexts/usePageHeader";import { PluginSlot } from "@/plugins";+import { LoadErrorNotice } from "@/components/LoadErrorNotice";import { Segmented } from "@nous-research/ui/ui/components/segmented";import { AutomationBlueprints } from "@/components/AutomationBlueprints";import { cn, themedBody } from "@/lib/utils";+import { errorMessage } from "@/lib/api-error";function formatTime(iso?: string | null): string {if (!iso) return "—";@@ -616,6 +620,9 @@ export default function CronPage() {const selectedProfileRef = useRef(selectedProfile);const jobsRequestGenerationRef = useRef(0);const jobsActiveRef = useRef(false);+ // Humanized error from the last GET /api/cron/jobs failure; renders a+ // persistent Retry notice instead of a vanishing toast.+ const [jobsLoadError, setJobsLoadError] = useState<string | null>(null);const loadJobs = useCallback((profile: string) => {if (!jobsActiveRef.current || selectedProfileRef.current !== profile) return;@@ -628,14 +635,17 @@ export default function CronPage() {if (jobsRequestGenerationRef.current === generation &&selectedProfileRef.current === profile- ) setJobs(nextJobs);+ ) {+ setJobs(nextJobs);+ setJobsLoadError(null);+ }})- .catch(() => {+ .catch((e: unknown) => {if (jobsRequestGenerationRef.current === generation &&selectedProfileRef.current === profile) {- showToast(t.common.loading, "error");+ setJobsLoadError(errorMessage(e));}}).finally(() => {@@ -644,7 +654,7 @@ export default function CronPage() {selectedProfileRef.current === profile) setLoading(false);});- }, [showToast, t.common.loading]);+ }, []);useEffect(() => {api@@ -706,7 +716,8 @@ export default function CronPage() {return;}if (payload.no_agent && !payload.script) {- showToast("no_agent jobs require a script", "error");+ showToast(t.cron.scriptRequired ?? en.cron.scriptRequired!, "error");+ focusCronField("cron-script");return;}setCreating(true);@@ -717,7 +728,7 @@ export default function CronPage() {setCreateModalOpen(false);loadJobs(selectedProfile);} catch (e) {- showToast(`${t.config.failedToSave}: ${e}`, "error");+ showToast(`${t.config.failedToSave}: ${errorMessage(e)}`, "error");} finally {setCreating(false);}@@ -734,7 +745,8 @@ export default function CronPage() {return;}if (payload.no_agent && !payload.script) {- showToast("no_agent jobs require a script", "error");+ showToast(t.cron.scriptRequired ?? en.cron.scriptRequired!, "error");+ focusCronField("edit-cron-script");return;}setSaving(true);@@ -748,7 +760,7 @@ export default function CronPage() {setEditJob(null);loadJobs(selectedProfile);} catch (e) {- showToast(`${t.config.failedToSave}: ${e}`, "error");+ showToast(`${t.config.failedToSave}: ${errorMessage(e)}`, "error");} finally {setSaving(false);}@@ -773,7 +785,7 @@ export default function CronPage() {}loadJobs(selectedProfile);} catch (e) {- showToast(`${t.status.error}: ${e}`, "error");+ showToast(`${t.status.error}: ${errorMessage(e)}`, "error");}};@@ -808,7 +820,7 @@ export default function CronPage() {triggerControllerRef.current === controller &&selectedProfileRef.current === viewProfile) {- showToast(`${t.status.error}: ${e}`, "error");+ showToast(`${t.status.error}: ${errorMessage(e)}`, "error");}}};@@ -826,7 +838,7 @@ export default function CronPage() {);loadJobs(selectedProfile);} catch (e) {- showToast(`${t.status.error}: ${e}`, "error");+ showToast(`${t.status.error}: ${errorMessage(e)}`, "error");throw e;}},@@ -870,6 +882,14 @@ export default function CronPage() {<PluginSlot name="cron:top" /><Toast toast={toast} />+ {jobsLoadError && (+ <LoadErrorNotice+ what={t.cron.loadWhat ?? en.cron.loadWhat!}+ detail={jobsLoadError}+ onRetry={() => loadJobs(selectedProfile)}+ />+ )}+<Segmentedvalue={view}onChange={(v) => setView(v as "jobs" | "blueprints")}@@ -1068,7 +1088,7 @@ export default function CronPage() {</div></div>- {jobs.length === 0 && (+ {jobs.length === 0 && !jobsLoadError && (<Card><CardContent className="flex flex-col items-center gap-3 py-8 text-center text-sm text-muted-foreground"><span>{t.cron.noJobs}</span>diff --git a/web/src/pages/EnvPage.tsx b/web/src/pages/EnvPage.tsxindex 78e2266fed8..afb1f9cf719 100644--- a/web/src/pages/EnvPage.tsx+++ b/web/src/pages/EnvPage.tsx@@ -39,6 +39,7 @@ import { Label } from "@nous-research/ui/ui/components/label";import { useI18n } from "@/i18n";import { usePageHeader } from "@/contexts/usePageHeader";import { PluginSlot } from "@/plugins";+import { errorMessage } from "@/lib/api-error";/* ------------------------------------------------------------------ *//* Provider grouping */@@ -711,7 +712,7 @@ export default function EnvPage() {});showToast(`${key} ${t.common.save.toLowerCase()}d`, "success");} catch (e) {- showToast(`${t.config.failedToSave} ${key}: ${e}`, "error");+ showToast(`${t.config.failedToSave} ${key}: ${errorMessage(e)}`, "error");} finally {setSaving(null);}@@ -736,7 +737,7 @@ export default function EnvPage() {});showToast(`${key} ${t.common.removed}`, "success");} catch (e) {- showToast(`${t.common.failedToRemove} ${key}: ${e}`, "error");+ showToast(`${t.common.failedToRemove} ${key}: ${errorMessage(e)}`, "error");throw e;} finally {setSaving(null);diff --git a/web/src/pages/FilesPage.tsx b/web/src/pages/FilesPage.tsxindex 02234809785..c288878efb8 100644--- a/web/src/pages/FilesPage.tsx+++ b/web/src/pages/FilesPage.tsx@@ -36,6 +36,7 @@ import { usePageHeader } from "@/contexts/usePageHeader";import { api } from "@/lib/api";import type { ManagedFileEntry, ManagedFilesResponse } from "@/lib/api";import { PluginSlot } from "@/plugins";+import { errorMessage } from "@/lib/api-error";const DATE_FORMAT = new Intl.DateTimeFormat(undefined, {dateStyle: "medium",@@ -108,7 +109,7 @@ export default function FilesPage() {setCurrentPath(result.path);setPathInput(result.path);} catch (e) {- setError(String(e));+ setError(errorMessage(e));} finally {setLoading(false);}@@ -182,7 +183,7 @@ export default function FilesPage() {showToast("Folder created", "success");await load();} catch (e) {- showToast(`Create failed: ${e}`, "error");+ showToast(`Create failed: ${errorMessage(e)}`, "error");} finally {setCreating(false);}@@ -198,7 +199,7 @@ export default function FilesPage() {showToast(`${files.length} file${files.length === 1 ? "" : "s"} uploaded`, "success");await load();} catch (e) {- showToast(`Upload failed: ${e}`, "error");+ showToast(`Upload failed: ${errorMessage(e)}`, "error");} finally {setUploading(false);if (fileInputRef.current) fileInputRef.current.value = "";@@ -241,7 +242,7 @@ export default function FilesPage() {const file = await api.readFile(entry.path);downloadDataUrl(file.data_url, file.name);} catch (e) {- showToast(`Download failed: ${e}`, "error");+ showToast(`Download failed: ${errorMessage(e)}`, "error");}};@@ -254,7 +255,7 @@ export default function FilesPage() {setPendingDelete(null);await load();} catch (e) {- showToast(`Delete failed: ${e}`, "error");+ showToast(`Delete failed: ${errorMessage(e)}`, "error");} finally {setDeleting(false);}diff --git a/web/src/pages/LogsPage.tsx b/web/src/pages/LogsPage.tsxindex 50163cad313..6fce66d270f 100644--- a/web/src/pages/LogsPage.tsx+++ b/web/src/pages/LogsPage.tsx@@ -6,6 +6,7 @@ import {useRef,} from "react";import { FileText, RefreshCw } from "lucide-react";+import { useSearchParams } from "react-router";import { api } from "@/lib/api";import { Badge } from "@nous-research/ui/ui/components/badge";import { Button } from "@nous-research/ui/ui/components/button";@@ -21,6 +22,7 @@ import { PluginSlot } from "@/plugins";// structured level token and falls back to word-boundary matching so payload// text like "parse_errors=0" can't render an INFO line red.import { classifyLine } from "@/lib/log-classify";+import { errorMessage } from "@/lib/api-error";const FILES = ["agent", "errors", "gateway"] as const;const LEVELS = ["ALL", "DEBUG", "INFO", "WARNING", "ERROR"] as const;@@ -45,8 +47,19 @@ const filterGroupClass =const segmentedClass ="w-fit max-w-full flex-wrap justify-start self-start";+type LogFile = (typeof FILES)[number];++function isLogFile(value: string | null): value is LogFile {+ return (FILES as readonly string[]).includes(value ?? "");+}+export default function LogsPage() {- const [file, setFile] = useState<(typeof FILES)[number]>("agent");+ // `?file=gateway` deep link (System page "Open logs" next to a failed gateway).+ const [searchParams] = useSearchParams();+ const requestedFile = searchParams.get("file");+ const [file, setFile] = useState<LogFile>(() =>+ isLogFile(requestedFile) ? requestedFile : "agent",+ );const [level, setLevel] = useState<(typeof LEVELS)[number]>("ALL");const [component, setComponent] =useState<(typeof COMPONENTS)[number]>("all");@@ -72,7 +85,7 @@ export default function LogsPage() {}}, 50);})- .catch((err) => setError(String(err)))+ .catch((err) => setError(errorMessage(err))).finally(() => setLoading(false));}, [file, lineCount, level, component]);diff --git a/web/src/pages/McpPage.tsx b/web/src/pages/McpPage.tsxindex 454411bf14e..773479abbba 100644--- a/web/src/pages/McpPage.tsx+++ b/web/src/pages/McpPage.tsx@@ -28,6 +28,7 @@ import {type McpTransport,} from "@/lib/mcp-server-create";import { completeMcpDashboardOAuth } from "@/lib/mcp-dashboard-oauth";+import { errorMessage } from "@/lib/api-error";function isHttpUrl(value: string): boolean {return /^https?:\/\//i.test(value.trim());@@ -98,7 +99,7 @@ export default function McpPage() {return api.getMcpServers().then((res) => setServers(res.servers))- .catch((e) => showToast(`Error: ${e}`, "error"));+ .catch((e) => showToast(`Could not load MCP servers: ${errorMessage(e)}`, "error"));}, [showToast]);const loadCatalog = useCallback(() => {@@ -108,7 +109,7 @@ export default function McpPage() {setCatalog(res.entries);setDiagnostics(res.diagnostics);})- .catch((e) => showToast(`Error: ${e}`, "error"));+ .catch((e) => showToast(`Could not load the MCP catalog: ${errorMessage(e)}`, "error"));}, [showToast]);useEffect(() => {@@ -158,7 +159,7 @@ export default function McpPage() {setCreateModalOpen(false);loadServers();} catch (e) {- showToast(`Failed to add: ${e}`, "error");+ showToast(`Could not add MCP server: ${errorMessage(e)}`, "error");} finally {setCreating(false);}@@ -175,7 +176,7 @@ export default function McpPage() {showToast(`${server.name}: ${result.error ?? "Failed"}`, "error");}} catch (e) {- showToast(`Error: ${e}`, "error");+ showToast(`Could not test the MCP server: ${errorMessage(e)}`, "error");} finally {setTesting(null);}@@ -196,7 +197,7 @@ export default function McpPage() {}));showToast(`${server.name}: OAuth authentication complete`, "success");} catch (e) {- showToast(`OAuth error: ${e}`, "error");+ showToast(`Could not sign in to the MCP server: ${errorMessage(e)}`, "error");} finally {setAuthenticating(null);}@@ -214,7 +215,7 @@ export default function McpPage() {"Enable/disable takes effect on the next gateway restart.",);} catch (e) {- showToast(`Error: ${e}`, "error");+ showToast(`Could not update the MCP server: ${errorMessage(e)}`, "error");} finally {setTogglingName(null);}@@ -233,7 +234,7 @@ export default function McpPage() {});loadServers();} catch (e) {- showToast(`Error: ${e}`, "error");+ showToast(`Could not remove the MCP server: ${errorMessage(e)}`, "error");throw e;}},@@ -256,7 +257,7 @@ export default function McpPage() {setInstallEnv({});await Promise.all([loadServers(), loadCatalog()]);} catch (e) {- showToast(`Failed to install: ${e}`, "error");+ showToast(`Could not install from the catalog: ${errorMessage(e)}`, "error");} finally {setInstallingName(null);}@@ -603,8 +604,22 @@ export default function McpPage() {{servers.length === 0 && (<Card>- <CardContent className="py-8 text-center text-sm text-muted-foreground">- No MCP servers configured.+ <CardContent className="flex flex-col items-center gap-3 py-8 text-center text-sm text-muted-foreground">+ <p>+ No MCP servers yet. MCP servers give the agent extra tools (GitHub, databases,+ browsers…). Pick one from the catalog below, or click Add Server at the top of the page.+ </p>+ <Button+ size="sm"+ onClick={() =>+ document+ .getElementById("mcp-catalog")+ ?.scrollIntoView({ behavior: "smooth", block: "start" })+ }+ prefix={<Package className="h-3.5 w-3.5" />}+ >+ Browse catalog+ </Button></CardContent></Card>)}@@ -747,7 +762,7 @@ export default function McpPage() {className="flex items-center gap-2 text-muted-foreground"><Package className="h-4 w-4" />- Catalog ({catalog.length})+ <span id="mcp-catalog">Catalog ({catalog.length})</span></H2></div>diff --git a/web/src/pages/ModelsPage.tsx b/web/src/pages/ModelsPage.tsxindex a4a6161e9e6..e9a2fb55913 100644--- a/web/src/pages/ModelsPage.tsx+++ b/web/src/pages/ModelsPage.tsx@@ -42,6 +42,7 @@ import { useI18n } from "@/i18n";import { PluginSlot } from "@/plugins";import { ModelPickerDialog } from "@/components/ModelPickerDialog";import { ModelReloadConfirm } from "@/components/ModelReloadConfirm";+import { errorMessage } from "@/lib/api-error";const PERIODS = [{ label: "7d", days: 7 },@@ -257,7 +258,7 @@ function UseAsMenu({onAssigned();setOpen(false);} catch (e) {- setError(e instanceof Error ? e.message : String(e));+ setError(errorMessage(e));} finally {setBusy(false);}@@ -751,7 +752,7 @@ function MoaModelsModal({onSaved(saved);onClose();} catch (e) {- setError(e instanceof Error ? e.message : String(e));+ setError(errorMessage(e));} finally {setBusy(false);}@@ -1161,7 +1162,7 @@ export default function ModelsPage() {setData(models);setAux(auxData);})- .catch((err) => setError(String(err)))+ .catch((err) => setError(errorMessage(err))).finally(() => setLoading(false));}, [days]);diff --git a/web/src/pages/PairingPage.tsx b/web/src/pages/PairingPage.tsxindex f11aed50833..1bbbc8e8ee7 100644--- a/web/src/pages/PairingPage.tsx+++ b/web/src/pages/PairingPage.tsx@@ -12,6 +12,7 @@ import { useConfirmDelete } from "@nous-research/ui/hooks/use-confirm-delete";import { Toast } from "@nous-research/ui/ui/components/toast";import { Card, CardContent } from "@nous-research/ui/ui/components/card";import { usePageHeader } from "@/contexts/usePageHeader";+import { errorMessage } from "@/lib/api-error";function getUserKey(user: PairingUser): string {return `${user.platform}:${user.user_id}`;@@ -63,7 +64,7 @@ export default function PairingPage() {showToast(`Approved: "${getUserLabel(user)}"`, "success");loadPairing();} catch (e) {- showToast(`Error: ${e}`, "error");+ showToast(`Could not approve the pairing request: ${errorMessage(e)}`, "error");} finally {setApproving(null);}@@ -77,7 +78,7 @@ export default function PairingPage() {showToast(`Cleared ${res.cleared} pending request(s)`, "success");loadPairing();} catch (e) {- showToast(`Error: ${e}`, "error");+ showToast(`Could not clear pending requests: ${errorMessage(e)}`, "error");} finally {setClearing(false);}@@ -96,7 +97,7 @@ export default function PairingPage() {);loadPairing();} catch (e) {- showToast(`Error: ${e}`, "error");+ showToast(`Could not revoke access: ${errorMessage(e)}`, "error");throw e;}},diff --git a/web/src/pages/ProfileBuilderPage.tsx b/web/src/pages/ProfileBuilderPage.tsxindex bafa20a2264..7e8b38e96d7 100644--- a/web/src/pages/ProfileBuilderPage.tsx+++ b/web/src/pages/ProfileBuilderPage.tsx@@ -23,6 +23,7 @@ import {type McpTransport,} from "@/lib/mcp-server-create";import { cn } from "@/lib/utils";+import { errorMessage } from "@/lib/api-error";// Profile name rule mirrors the backend (`^[a-z0-9][a-z0-9_-]{0,63}$`).const PROFILE_NAME_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/;@@ -270,7 +271,7 @@ export default function ProfileBuilderPage() {);navigate("/profiles");} catch (e) {- showToast(`Create failed: ${e}`, "error");+ showToast(`Create failed: ${errorMessage(e)}`, "error");} finally {setCreating(false);}diff --git a/web/src/pages/ProfilesPage.tsx b/web/src/pages/ProfilesPage.tsxindex cf39634ca27..d37db337d2b 100644--- a/web/src/pages/ProfilesPage.tsx+++ b/web/src/pages/ProfilesPage.tsx@@ -45,6 +45,7 @@ import { Checkbox } from "@nous-research/ui/ui/components/checkbox";import { useI18n } from "@/i18n";import { usePageHeader } from "@/contexts/usePageHeader";import { cn, themedBody } from "@/lib/utils";+import { errorMessage } from "@/lib/api-error";// Mirrors hermes_cli/profiles.py::_PROFILE_ID_RE so we can reject obviously// invalid names (uppercase, spaces, …) before round-tripping a doomed POST.@@ -300,7 +301,7 @@ export default function ProfilesPage() {modelInherit: p.modelInherit ?? "Inherit from clone / default",modelLoading: p.modelLoading ?? "Loading models…",modelNone:- p.modelNone ?? "No authenticated providers — set a key first",+ p.modelNone ?? "No model providers are set up yet. Add an API key under Keys or sign in to a provider under Models.",editModel: p.editModel ?? "Change model",modelSaved: p.modelSaved ?? "Model updated",modelSelect: p.modelSelect ?? "Select a model",@@ -399,7 +400,7 @@ export default function ProfilesPage() {setProfiles(res.profiles);setActiveInfo(active);})- .catch((e) => showToast(`${t.status.error}: ${e}`, "error"))+ .catch((e) => showToast(`${t.status.error}: ${errorMessage(e)}`, "error")).finally(() => setLoading(false));}, [showToast, t.status.error]);@@ -463,7 +464,7 @@ export default function ProfilesPage() {setCreateModalOpen(false);load();} catch (e) {- showToast(`${t.status.error}: ${e}`, "error");+ showToast(`${t.status.error}: ${errorMessage(e)}`, "error");} finally {setCreating(false);}@@ -488,7 +489,7 @@ export default function ProfilesPage() {setRenameTo("");load();} catch (e) {- showToast(`${t.status.error}: ${e}`, "error");+ showToast(`${t.status.error}: ${errorMessage(e)}`, "error");}};@@ -507,7 +508,7 @@ export default function ProfilesPage() {prev ? { ...prev, active } : { active, current: active },);} catch (e) {- showToast(`${t.status.error}: ${e}`, "error");+ showToast(`${t.status.error}: ${errorMessage(e)}`, "error");} finally {setSettingActive(null);}@@ -542,7 +543,7 @@ export default function ProfilesPage() {}} catch (e) {if (activeSoulRequest.current === name) {- showToast(`${t.status.error}: ${e}`, "error");+ showToast(`${t.status.error}: ${errorMessage(e)}`, "error");}}},@@ -557,7 +558,7 @@ export default function ProfilesPage() {activeSoulRequest.current = null;setEditingSoulFor(null);} catch (e) {- showToast(`${t.status.error}: ${e}`, "error");+ showToast(`${t.status.error}: ${errorMessage(e)}`, "error");} finally {setSoulSaving(false);}@@ -603,7 +604,7 @@ export default function ProfilesPage() {}} catch (e) {if (activeDescRequest.current === name) {- showToast(`${t.status.error}: ${e}`, "error");+ showToast(`${t.status.error}: ${errorMessage(e)}`, "error");}} finally {descSavingCount.current -= 1;@@ -637,7 +638,7 @@ export default function ProfilesPage() {}} catch (e) {if (activeDescRequest.current === name) {- showToast(`${t.status.error}: ${e}`, "error");+ showToast(`${t.status.error}: ${errorMessage(e)}`, "error");}} finally {describingCount.current -= 1;@@ -680,7 +681,7 @@ export default function ProfilesPage() {);setEditingModelFor(null);} catch (e) {- showToast(`${t.status.error}: ${e}`, "error");+ showToast(`${t.status.error}: ${errorMessage(e)}`, "error");} finally {setModelSaving(false);}@@ -707,7 +708,7 @@ export default function ProfilesPage() {const res = await api.getProfileSetupCommand(name);cmd = res.command;} catch (e) {- showToast(`${t.status.error}: ${e}`, "error");+ showToast(`${t.status.error}: ${errorMessage(e)}`, "error");return;}if (await copyTextToClipboard(cmd)) {@@ -725,7 +726,7 @@ export default function ProfilesPage() {showToast(`${t.profiles.deleted}: ${name}`, "success");load();} catch (e) {- showToast(`${t.status.error}: ${e}`, "error");+ showToast(`${t.status.error}: ${errorMessage(e)}`, "error");throw e;}},diff --git a/web/src/pages/SessionsPage.tsx b/web/src/pages/SessionsPage.tsxindex 8115cd5742e..7c71861dd9b 100644--- a/web/src/pages/SessionsPage.tsx+++ b/web/src/pages/SessionsPage.tsx@@ -74,6 +74,7 @@ import { useI18n } from "@/i18n";import { usePageHeader } from "@/contexts/usePageHeader";import { PluginSlot } from "@/plugins";import { isDashboardEmbeddedChatEnabled } from "@/lib/dashboard-flags";+import { apiErrorFromResponse, errorMessage } from "@/lib/api-error";const SOURCE_CONFIG: Record<string, { icon: typeof Terminal; color: string }> ={@@ -492,7 +493,7 @@ function SessionRow({if (!cancelled) setMessages(resp.messages);}).catch((err) => {- if (!cancelled) setError(String(err));+ if (!cancelled) setError(errorMessage(err));});return () => {cancelled = true;@@ -1084,7 +1085,7 @@ export default function SessionsPage() {loadStats();refreshEmptyCount();} catch (error) {- showToast(`Import failed: ${error}`, "error");+ showToast(`Import failed: ${errorMessage(error)}`, "error");} finally {setImportingSessions(false);if (importInputRef.current) importInputRef.current.value = "";@@ -1495,7 +1496,9 @@ export default function SessionsPage() {.__HERMES_SESSION_TOKEN__ ?? "",},});- if (!res.ok) throw new Error(`HTTP ${res.status}`);+ if (!res.ok) {+ throw apiErrorFromResponse(res.status, await res.text().catch(() => ""), res.url);+ }const blob = await res.blob();const url = URL.createObjectURL(blob);const a = document.createElement("a");diff --git a/web/src/pages/SkillsPage.tsx b/web/src/pages/SkillsPage.tsxindex 0d6ff4c013c..65598e90ba9 100644--- a/web/src/pages/SkillsPage.tsx+++ b/web/src/pages/SkillsPage.tsx@@ -42,6 +42,7 @@ import type {import { useProfileScope } from "@/contexts/useProfileScope";import { ToolsetConfigDrawer } from "@/components/ToolsetConfigDrawer";import { SkillEditorDialog } from "@/components/SkillEditorDialog";+import { LoadErrorNotice } from "@/components/LoadErrorNotice";import { useToast } from "@nous-research/ui/hooks/use-toast";import { Toast } from "@nous-research/ui/ui/components/toast";import { Card, CardContent, CardHeader, CardTitle } from "@nous-research/ui/ui/components/card";@@ -60,8 +61,10 @@ import {import { cn } from "@/lib/utils";import { Input } from "@nous-research/ui/ui/components/input";import { useI18n } from "@/i18n";+import { en } from "@/i18n/en";import { usePageHeader } from "@/contexts/usePageHeader";import { PluginSlot } from "@/plugins";+import { errorMessage } from "@/lib/api-error";/* ------------------------------------------------------------------ *//* Types & helpers */@@ -129,6 +132,10 @@ export default function SkillsPage() {const [skills, setSkills] = useState<SkillInfo[]>([]);const [toolsets, setToolsets] = useState<ToolsetInfo[]>([]);const [loading, setLoading] = useState(true);+ // Humanized error from the last skills/toolsets load; drives a persistent+ // Retry notice. `loadNonce` re-runs the load effect on Retry.+ const [loadError, setLoadError] = useState<string | null>(null);+ const [loadNonce, setLoadNonce] = useState(0);const [search, setSearch] = useState("");const [view, setView] = useState<"skills" | "toolsets" | "hub">("skills");const [activeCategory, setActiveCategory] = useState<string | null>(null);@@ -165,13 +172,14 @@ export default function SkillsPage() {if (cancelled) return;setSkills(s);setToolsets(tsets);+ setLoadError(null);})- .catch(() => !cancelled && showToast(t.common.loading, "error"))+ .catch((e: unknown) => !cancelled && setLoadError(errorMessage(e))).finally(() => !cancelled && setLoading(false));return () => {cancelled = true;};- }, [selectedProfile]);+ }, [selectedProfile, loadNonce]);/* ---- Toggle skill ---- */const handleToggleSkill = async (skill: SkillInfo) => {@@ -382,6 +390,17 @@ export default function SkillsPage() {<PluginSlot name="skills:top" /><Toast toast={toast} />+ {loadError && (+ <LoadErrorNotice+ what={t.skills.loadWhat ?? en.skills.loadWhat!}+ detail={loadError}+ onRetry={() => {+ setLoading(true);+ setLoadNonce((n) => n + 1);+ }}+ />+ )}+<div className="flex flex-col sm:flex-row sm:items-start gap-4"><aside aria-label={t.skills.title} className="sm:w-56 sm:shrink-0"><div className="sm:sticky sm:top-0">@@ -544,12 +563,24 @@ export default function SkillsPage() {</div></CardHeader><CardContent className="px-4 pb-4">- {activeSkills.length === 0 ? (- <p className="text-sm text-muted-foreground text-center py-8">- {skills.length === 0- ? t.skills.noSkills- : t.skills.noSkillsMatch}- </p>+ {loadError ? null : activeSkills.length === 0 ? (+ <div className="flex flex-col items-center gap-3 py-8 text-center">+ <p className="text-sm text-muted-foreground">+ {skills.length === 0+ ? t.skills.noSkills+ : t.skills.noSkillsMatch}+ </p>+ {skills.length === 0 && (+ <div className="flex flex-wrap justify-center gap-2">+ <Button size="sm" onClick={() => setView("hub")}>+ {t.skills.browseHub ?? en.skills.browseHub}+ </Button>+ <Button size="sm" outlined onClick={openCreateEditor}>+ {t.skills.createSkill ?? en.skills.createSkill}+ </Button>+ </div>+ )}+ </div>) : (<div className="grid gap-1">{activeSkills.map((skill) => (@@ -923,7 +954,7 @@ function HubBrowser({setTimedOut(r.timed_out || []);setInstalled((prev) => ({ ...prev, ...(r.installed || {}) }));} catch (e) {- showToast(`Hub search failed: ${e}`, "error");+ showToast(`Hub search failed: ${errorMessage(e)}`, "error");setResults([]);setSourceCounts({});setTimedOut([]);@@ -974,7 +1005,7 @@ function HubBrowser({setAction(res.name);setDetail(null);} catch (e) {- showToast(`Install failed: ${e}`, "error");+ showToast(`Install failed: ${errorMessage(e)}`, "error");}},[showToast, profile],@@ -988,7 +1019,7 @@ function HubBrowser({setActionRunning(true);setAction(res.name);} catch (e) {- showToast(`Update failed: ${e}`, "error");+ showToast(`Update failed: ${errorMessage(e)}`, "error");}}, [showToast, profile]);@@ -1362,7 +1393,7 @@ function SkillDetailDialog({.previewSkillFromHub(result.identifier).then((p) => !cancelled && setPreview(p)).catch((e) => {- if (!cancelled) showToast(`Preview failed: ${e}`, "error");+ if (!cancelled) showToast(`Preview failed: ${errorMessage(e)}`, "error");}).finally(() => !cancelled && setPreviewLoading(false));return () => {@@ -1377,7 +1408,7 @@ function SkillDetailDialog({const s = await api.scanSkillFromHub(result.identifier);setScan(s);} catch (e) {- showToast(`Scan failed: ${e}`, "error");+ showToast(`Scan failed: ${errorMessage(e)}`, "error");} finally {setScanning(false);}diff --git a/web/src/pages/SystemPage.tsx b/web/src/pages/SystemPage.tsxindex c431d38d86f..dc0bcb01f2f 100644--- a/web/src/pages/SystemPage.tsx+++ b/web/src/pages/SystemPage.tsx@@ -47,6 +47,9 @@ import { cn, themedBody } from "@/lib/utils";import { api } from "@/lib/api";import { copyTextToClipboard } from "@/lib/clipboard";import {+ gatewayStateNeedsLogs,+ gatewayStateDescription,+ gatewayActionFailedMessage,servedProfileRefusal,sharedGatewayProfiles,sharedGatewayRestartDescription,@@ -67,6 +70,7 @@ import type {DebugShareResponse,GatewayMigratePlan,} from "@/lib/api";+import { apiErrorFromResponse, errorMessage } from "@/lib/api-error";function formatBytes(n: number): string {if (n < 1024) return `${n} B`;@@ -324,7 +328,7 @@ export default function SystemPage() {setServedNotice(refusal);return false;}- showToast(`Gateway ${verb} failed: ${e}`, "error");+ showToast(gatewayActionFailedMessage(verb, errorMessage(e), e), "error");return false;}};@@ -360,7 +364,7 @@ export default function SystemPage() {showToast("Migrating to a single multiplexed gateway", "success");setTimeout(loadAll, 5000);} catch (e) {- showToast(`Gateway migration failed: ${e}`, "error");+ showToast(`Gateway migration failed: ${errorMessage(e)}`, "error");}};@@ -372,7 +376,7 @@ export default function SystemPage() {showToast(curator.paused ? "Curator resumed" : "Curator paused", "success");loadAll();} catch (e) {- showToast(`Curator toggle failed: ${e}`, "error");+ showToast(`Curator toggle failed: ${errorMessage(e)}`, "error");}};@@ -390,7 +394,7 @@ export default function SystemPage() {showToast(`Reset: ${res.deleted.join(", ") || "nothing"}`, "success");loadAll();} catch (e) {- showToast(`Reset failed: ${e}`, "error");+ showToast(`Reset failed: ${errorMessage(e)}`, "error");throw e;}},@@ -416,7 +420,7 @@ export default function SystemPage() {setCredLabel("");loadAll();} catch (e) {- showToast(`Failed to add credential: ${e}`, "error");+ showToast(`Failed to add credential: ${errorMessage(e)}`, "error");} finally {setAddingCred(false);}@@ -431,7 +435,7 @@ export default function SystemPage() {showToast("Credential removed", "success");loadAll();} catch (e) {- showToast(`Failed to remove: ${e}`, "error");+ showToast(`Failed to remove: ${errorMessage(e)}`, "error");throw e;}},@@ -446,7 +450,7 @@ export default function SystemPage() {setActiveAction(res.name);showToast(`${label} started`, "success");} catch (e) {- showToast(`${label} failed: ${e}`, "error");+ showToast(`${label} failed: ${errorMessage(e)}`, "error");}};@@ -458,7 +462,7 @@ export default function SystemPage() {setDownloadableBackupArchive(null);showToast("Backup started", "success");} catch (e) {- showToast(`Backup failed: ${e}`, "error");+ showToast(`Backup failed: ${errorMessage(e)}`, "error");}};@@ -482,7 +486,9 @@ export default function SystemPage() {setDownloadingBackup(true);try {const res = await api.downloadBackup(archive);- if (!res.ok) throw new Error(`HTTP ${res.status}`);+ if (!res.ok) {+ throw apiErrorFromResponse(res.status, await res.text().catch(() => ""), res.url);+ }const blob = await res.blob();const url = URL.createObjectURL(blob);const link = document.createElement("a");@@ -493,7 +499,7 @@ export default function SystemPage() {link.remove();URL.revokeObjectURL(url);} catch (e) {- showToast(`Download failed: ${e}`, "error");+ showToast(`Download failed: ${errorMessage(e)}`, "error");} finally {setDownloadingBackup(false);}@@ -515,7 +521,7 @@ export default function SystemPage() {showToast("Import started", "success");if (target.kind === "upload") clearImportFile();} catch (e) {- showToast(`Import failed: ${e}`, "error");+ showToast(`Import failed: ${errorMessage(e)}`, "error");} finally {setImportingBackup(false);}@@ -561,7 +567,7 @@ export default function SystemPage() {"success",);} catch (e) {- showToast(`Debug share failed: ${e}`, "error");+ showToast(`Debug share failed: ${errorMessage(e)}`, "error");} finally {setSharing(false);}@@ -591,7 +597,7 @@ export default function SystemPage() {}}} catch (e) {- showToast(`Update check failed: ${e}`, "error");+ showToast(`Update check failed: ${errorMessage(e)}`, "error");} finally {setCheckingUpdate(false);}@@ -623,7 +629,7 @@ export default function SystemPage() {setActiveAction(resp.name ?? "hermes-update");showToast("Update started", "success");} catch (e) {- showToast(`Update failed: ${e}`, "error");+ showToast(`Update failed: ${errorMessage(e)}`, "error");}};@@ -634,7 +640,7 @@ export default function SystemPage() {setActiveAction(res.name);showToast("Checkpoint prune started", "success");} catch (e) {- showToast(`Prune failed: ${e}`, "error");+ showToast(`Prune failed: ${errorMessage(e)}`, "error");throw e;}}, [showToast]),@@ -662,7 +668,7 @@ export default function SystemPage() {setHookModalOpen(false);loadAll();} catch (e) {- showToast(`Failed to create hook: ${e}`, "error");+ showToast(`Failed to create hook: ${errorMessage(e)}`, "error");} finally {setCreatingHook(false);}@@ -679,7 +685,7 @@ export default function SystemPage() {showToast("Hook removed", "success");loadAll();} catch (e) {- showToast(`Failed to remove hook: ${e}`, "error");+ showToast(`Failed to remove hook: ${errorMessage(e)}`, "error");throw e;}},@@ -1118,9 +1124,13 @@ export default function SystemPage() {{gatewayRunning ? "running" : "stopped"}</Badge><span className="text-sm text-muted-foreground">- {status?.gateway_state ?? "—"}- {status?.gateway_pid ? ` · pid ${status.gateway_pid}` : ""}+ {gatewayStateDescription(status?.gateway_state, gatewayRunning)}</span>+ {gatewayStateNeedsLogs(status?.gateway_state) && (+ <Link to="/logs?file=gateway" className="text-sm underline">+ Open logs+ </Link>+ )}</div><div className="flex items-center gap-2"><Buttondiff --git a/web/src/pages/WebhooksPage.tsx b/web/src/pages/WebhooksPage.tsxindex e44198de69f..6d1bf4cf48d 100644--- a/web/src/pages/WebhooksPage.tsx+++ b/web/src/pages/WebhooksPage.tsx@@ -27,6 +27,7 @@ import { Input } from "@nous-research/ui/ui/components/input";import { Label } from "@nous-research/ui/ui/components/label";import { usePageHeader } from "@/contexts/usePageHeader";import { cn, themedBody } from "@/lib/utils";+import { errorMessage } from "@/lib/api-error";interface CreatedWebhook {url: string;@@ -141,8 +142,8 @@ export default function WebhooksPage() {void watchRestartOutcome();} catch (e) {setRestartNeeded(true);- setRestartError(String(e));- showToast(`Failed to restart: ${e}`, "error");+ setRestartError(errorMessage(e));+ showToast(`Failed to restart: ${errorMessage(e)}`, "error");} finally {setRestarting(false);}@@ -168,7 +169,7 @@ export default function WebhooksPage() {showToast(`Webhooks enabled; gateway restart failed${detail}`, "error");}} catch (e) {- showToast(`Failed to enable webhooks: ${e}`, "error");+ showToast(`Failed to enable webhooks: ${errorMessage(e)}`, "error");} finally {setEnabling(false);}@@ -207,7 +208,7 @@ export default function WebhooksPage() {resetForm();loadWebhooks();} catch (e) {- showToast(`Failed to create: ${e}`, "error");+ showToast(`Failed to create: ${errorMessage(e)}`, "error");} finally {setCreating(false);}@@ -226,7 +227,7 @@ export default function WebhooksPage() {);loadWebhooks();} catch (e) {- showToast(`Error: ${e}`, "error");+ showToast(`Error: ${errorMessage(e)}`, "error");} finally {setTogglingName(null);}@@ -242,7 +243,7 @@ export default function WebhooksPage() {showToast(`Deleted: "${name}"`, "success");loadWebhooks();} catch (e) {- showToast(`Error: ${e}`, "error");+ showToast(`Error: ${errorMessage(e)}`, "error");throw e;}},