Skip to content

The agent that grows with you

feat(desktop): failed turns name the failing layer with recovery actions

Teknium98f6fc549a33
diff --git a/agent/error_surface.py b/agent/error_surface.py
new file mode 100644
index 00000000000..0f20b799005
--- /dev/null
+++ b/agent/error_surface.py
@@ -0,0 +1,223 @@
+"""Structured error-surface descriptors for UI clients (Desktop/TUI).
+
+Maps the internal failure taxonomy (``agent.error_classifier.FailoverReason``
+values carried in turn results as ``failure_reason``, or raw exceptions from
+the turn dispatcher) onto a small, stable wire descriptor:
+
+ {"layer": <ui layer>, "code": <specific code>, "retryable": <bool>}
+
+The *layer* names which part of the stack failed, so clients can say
+"Provider error" / "Gateway error" instead of toasting an opaque string and
+leaving the user to guess whether the model, the gateway, or the app froze:
+
+ provider — the model/provider API rejected or failed the call
+ endpoint — a user-configured custom/local endpoint failed (transport)
+ streaming — the provider's SSE/stream connection dropped mid-turn
+ auth — authentication/authorization failed
+ billing — credits/quota wall (clients usually have a richer
+ billing_block descriptor; this is the fallback signal)
+ gateway — the local gateway/agent runtime itself errored
+ runtime — agent initialization / local environment failure
+ disk — local disk full / persistence failure
+
+This module is intentionally dependency-light and NEVER raises: surfacing
+diagnostics must not be able to break the error path it describes. Clients
+treat the descriptor as advisory — an absent or partial descriptor falls
+back to today's string-sniffing behavior (older backends keep working).
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any, Optional
+
+logger = logging.getLogger(__name__)
+
+# UI layers (wire values — stable contract with desktop/TUI clients).
+LAYER_PROVIDER = "provider"
+LAYER_ENDPOINT = "endpoint"
+LAYER_STREAMING = "streaming"
+LAYER_AUTH = "auth"
+LAYER_BILLING = "billing"
+LAYER_GATEWAY = "gateway"
+LAYER_RUNTIME = "runtime"
+LAYER_DISK = "disk"
+
+# failure_reason (FailoverReason.value) → UI layer. Reasons not listed fall
+# back to LAYER_PROVIDER: every FailoverReason is produced by classifying a
+# provider API call, so "the provider call failed" is the honest default.
+_REASON_TO_LAYER = {
+ "auth": LAYER_AUTH,
+ "auth_permanent": LAYER_AUTH,
+ "billing": LAYER_BILLING,
+ "billing_unverified": LAYER_BILLING,
+}
+
+# Transport-ish reasons: the failure is between us and the base_url, not a
+# verdict the provider returned. On a custom/local endpoint these point at
+# the user's endpoint config, so they surface as LAYER_ENDPOINT there.
+_TRANSPORT_REASONS = {
+ "timeout",
+ "ssl_cert_verification",
+}
+
+# Reasons that are deterministic for the request — a bare "Retry" repeats the
+# same failure, so clients shouldn't lead with it.
+_NON_RETRYABLE_REASONS = {
+ "auth_permanent",
+ "billing",
+ "content_policy_blocked",
+ "provider_policy_blocked",
+ "model_not_found",
+ "ssl_cert_verification",
+}
+
+# Providers whose base_url is user-supplied rather than a known vendor —
+# transport failures against these are endpoint-config problems.
+_CUSTOM_ENDPOINT_PROVIDERS = {
+ "custom",
+ "local",
+ "llama.cpp",
+ "llamacpp",
+ "ollama",
+ "lmstudio",
+ "vllm",
+}
+
+# Message fragments that mark a mid-stream connection drop. Deliberately
+# narrow: these strings come from our own retry-exhaustion summaries and the
+# OpenAI SDK's stream-abort errors.
+_STREAM_DROP_FRAGMENTS = (
+ "stream connection",
+ "peer closed connection",
+ "incomplete chunked read",
+ "connection broken",
+ "stream ended prematurely",
+ "sse",
+ "mid-stream",
+)
+
+# Exception modules that indicate the failure came from an API/transport call
+# (vs. a bug in our own dispatcher code, which is a gateway-layer failure).
+_API_EXC_MODULE_PREFIXES = (
+ "openai",
+ "httpx",
+ "httpcore",
+ "anthropic",
+ "ssl",
+ "socket",
+ "urllib",
+)
+
+
+def _is_custom_endpoint(provider: Optional[str]) -> bool:
+ p = (provider or "").strip().lower()
+ return p in _CUSTOM_ENDPOINT_PROVIDERS or p.startswith("custom:")
+
+
+def _looks_like_stream_drop(message: str) -> bool:
+ msg = message.lower()
+ return any(fragment in msg for fragment in _STREAM_DROP_FRAGMENTS)
+
+
+def _surface(layer: str, code: str, retryable: bool) -> dict:
+ return {"layer": layer, "code": code, "retryable": bool(retryable)}
+
+
+def build_error_surface_from_result(
+ result: Any, provider: str = "", model: str = ""
+) -> Optional[dict]:
+ """Descriptor for a returned-error turn result (``failed=True`` dicts).
+
+ Reads the ``failure_reason`` the conversation loop already stamps
+ (a ``FailoverReason.value``) plus the error text, and maps them onto a
+ UI layer. Returns None when the result carries no failure signal.
+ """
+ try:
+ if not isinstance(result, dict):
+ return None
+ error_text = str(result.get("error") or "")
+ reason = str(result.get("failure_reason") or "").strip()
+ if not error_text and not reason:
+ return None
+
+ # Disk-full wins outright: the fix (free space) is unrelated to the
+ # provider stack, and hermes_state owns the pattern list.
+ try:
+ from hermes_state import is_disk_full_error
+
+ if error_text and is_disk_full_error(error_text):
+ return _surface(LAYER_DISK, "disk_full", False)
+ except Exception: # pragma: no cover - defensive import guard
+ pass
+
+ if result.get("billing_block") or reason in ("billing", "billing_unverified"):
+ return _surface(LAYER_BILLING, reason or "billing", False)
+
+ if not reason:
+ # Failed result without a classified reason (legacy paths).
+ if _looks_like_stream_drop(error_text):
+ return _surface(LAYER_STREAMING, "stream_drop", True)
+ return _surface(LAYER_PROVIDER, "unknown", True)
+
+ layer = _REASON_TO_LAYER.get(reason)
+ if layer is None:
+ if reason in _TRANSPORT_REASONS and _is_custom_endpoint(provider):
+ layer = LAYER_ENDPOINT
+ elif _looks_like_stream_drop(error_text):
+ layer = LAYER_STREAMING
+ else:
+ layer = LAYER_PROVIDER
+ return _surface(layer, reason, reason not in _NON_RETRYABLE_REASONS)
+ except Exception: # pragma: no cover — never break the error path
+ logger.debug("error_surface: result classification failed", exc_info=True)
+ return None
+
+
+def build_error_surface_from_exception(
+ exc: BaseException, provider: str = "", model: str = ""
+) -> Optional[dict]:
+ """Descriptor for an exception that escaped the turn dispatcher.
+
+ API/transport exceptions are classified through the real
+ ``classify_api_error`` pipeline (same taxonomy as the retry loop);
+ anything else is a gateway-layer failure — a bug or environment problem
+ in our own dispatcher, not a provider verdict.
+ """
+ try:
+ message = str(exc) or type(exc).__name__
+
+ try:
+ from hermes_state import is_disk_full_error
+
+ if is_disk_full_error(exc):
+ return _surface(LAYER_DISK, "disk_full", False)
+ except Exception: # pragma: no cover - defensive import guard
+ pass
+
+ exc_module = type(exc).__module__ or ""
+ api_like = exc_module.split(".")[0] in _API_EXC_MODULE_PREFIXES or hasattr(
+ exc, "status_code"
+ )
+
+ if not api_like or not isinstance(exc, Exception):
+ return _surface(LAYER_GATEWAY, type(exc).__name__, True)
+
+ from agent.error_classifier import classify_api_error
+
+ classified = classify_api_error(exc, provider=provider, model=model)
+ reason = classified.reason.value
+
+ synthetic = {
+ "error": classified.message or message,
+ "failure_reason": reason,
+ }
+ surface = build_error_surface_from_result(
+ synthetic, provider=provider, model=model
+ )
+ if surface is not None:
+ surface["retryable"] = bool(classified.retryable)
+ return surface
+ except Exception: # pragma: no cover — never break the error path
+ logger.debug("error_surface: exception classification failed", exc_info=True)
+ return None
diff --git a/apps/desktop/electron/fs-ipc.ts b/apps/desktop/electron/fs-ipc.ts
index ff25db2013e..61a3cb7db22 100644
--- a/apps/desktop/electron/fs-ipc.ts
+++ b/apps/desktop/electron/fs-ipc.ts
@@ -98,6 +98,12 @@ export function registerFsIpc({
ipcMain.handle('hermes:fs:desktopPluginsRoot', async () => localPluginsRoot('desktop-plugins'))
+ // The LOCAL logs root (`<HERMES_HOME>/logs`, profile-aware) — the error
+ // card's "Open Logs" action reveals agent.log/gateway.log without the user
+ // knowing where HERMES_HOME lives. Same Electron-local resolution as the
+ // plugin roots: valid in every connection mode, created on demand.
+ ipcMain.handle('hermes:fs:logsRoot', async () => localPluginsRoot('logs'))
+
// The LOCAL agent-plugin root (`<HERMES_HOME>/plugins`), same Electron-local
// resolution as above. This is the desktop half of a UNIFIED plugin package:
// an agent plugin may ship `desktop/plugin.js` alongside its Python code (the
diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.ts
index 7d8dac57af5..7eac06bd52e 100644
--- a/apps/desktop/electron/preload.ts
+++ b/apps/desktop/electron/preload.ts
@@ -269,6 +269,7 @@ contextBridge.exposeInMainWorld('hermesDesktop', {
revealPath: targetPath => ipcRenderer.invoke('hermes:fs:reveal', targetPath),
openDir: dirPath => ipcRenderer.invoke('hermes:fs:openDir', dirPath),
desktopPluginsRoot: () => ipcRenderer.invoke('hermes:fs:desktopPluginsRoot'),
+ logsRoot: () => ipcRenderer.invoke('hermes:fs:logsRoot'),
agentPluginsRoot: () => ipcRenderer.invoke('hermes:fs:agentPluginsRoot'),
renamePath: (targetPath, newName) => ipcRenderer.invoke('hermes:fs:rename', targetPath, newName),
writeTextFile: (filePath, content) => ipcRenderer.invoke('hermes:fs:writeText', filePath, content),
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts
index 5efba27561a..43be63e1905 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts
@@ -4,6 +4,7 @@ import { burstVibeHearts } from '@/components/chat/vibe-hearts'
import { translateNow } from '@/i18n'
import { coerceGatewayText, coerceThinkingText } from '@/lib/chat-runtime'
import { playCompletionSound } from '@/lib/completion-sound'
+import { parseErrorSurface } from '@/lib/error-surface'
import { triggerHaptic } from '@/lib/haptics'
import { billingCtaLabel, clearBillingBlock, runBillingRecovery, setBillingBlock } from '@/store/billing-block'
import { clearClarifyRequest } from '@/store/clarify'
@@ -335,13 +336,15 @@ export function handleMessageStreamEvent(ctx: GatewayEventContext): boolean {
const finalText = coerceGatewayText(payload?.text) || coerceGatewayText(payload?.rendered)
// Terminal error frames (status "error") carry the failure in
- // structured fields: `error` is the message, and `partial` marks
- // `text` as streamed output to keep rather than the error string.
+ // structured fields: `error` is the message, `partial` marks
+ // `text` as streamed output to keep rather than the error string, and
+ // `error_surface` (newer gateways) names the failing layer for the card.
const failure =
payload?.status === 'error'
? {
error: coerceGatewayText(payload.error).trim() || finalText || 'Hermes reported an error',
- partial: Boolean(payload.partial)
+ partial: Boolean(payload.partial),
+ surface: parseErrorSurface(payload.error_surface)
}
: undefined
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/index.ts b/apps/desktop/src/app/session/hooks/use-message-stream/index.ts
index b7eeae2a17a..36cec7c71d1 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/index.ts
@@ -17,6 +17,7 @@ import {
sealOpenToolParts,
upsertToolPart
} from '@/lib/chat-messages'
+import type { ErrorSurface } from '@/lib/error-surface'
import {
dedupeGeneratedImageEchoesInParts,
generatedImageEchoSources,
@@ -561,7 +562,7 @@ export function useMessageStream({
sessionId: string,
text: string,
responsePreviewed?: boolean,
- failure?: { error: string; partial: boolean },
+ failure?: { error: string; partial: boolean; surface?: ErrorSurface | null },
occurredAt = Date.now() / 1000
) => {
let shouldHydrate = false
@@ -616,7 +617,8 @@ export function useMessageStream({
parts: completeOpenTimelineParts(message.parts, occurredAt),
pending: false,
interim: false,
- ...(durationS !== undefined ? { durationS } : {})
+ ...(durationS !== undefined ? { durationS } : {}),
+ ...(completionError && failure?.surface ? { errorSurface: failure.surface } : {})
}
if (completionError && !keepFailedPartialText) {
@@ -641,7 +643,8 @@ export function useMessageStream({
completedAt: occurredAt,
branchGroupId: state.pendingBranchGroup ?? undefined,
...(durationS !== undefined ? { durationS } : {}),
- ...(completionError && { error: completionError })
+ ...(completionError && { error: completionError }),
+ ...(completionError && failure?.surface ? { errorSurface: failure.surface } : {})
})
const prev = state.messages
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/terminal-error-frame.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/terminal-error-frame.test.tsx
index 303cf10a2e2..8ecefe8e090 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/terminal-error-frame.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/terminal-error-frame.test.tsx
@@ -78,4 +78,38 @@ describe('terminal error message.complete frames', () => {
const bubble = lastAssistant()
expect(bubble?.error).toBe('Error: something broke')
})
+
+ it('attaches the structured error_surface descriptor to the failed bubble', async () => {
+ mountStream()
+ await start()
+ await delta('…')
+
+ await completeWithError({
+ text: 'Error: rate limited',
+ error: 'rate limited',
+ error_surface: { layer: 'provider', code: 'rate_limit', retryable: true },
+ recoverable: true
+ })
+
+ const bubble = lastAssistant()
+ expect(bubble?.error).toBe('rate limited')
+ expect(bubble?.errorSurface).toEqual({ layer: 'provider', code: 'rate_limit', retryable: true })
+ })
+
+ it('ignores a garbled error_surface payload (older/foreign backends)', async () => {
+ mountStream()
+ await start()
+ await delta('…')
+
+ await completeWithError({
+ text: 'Error: kaput',
+ error: 'kaput',
+ error_surface: { layer: 'not-a-layer', code: 42 },
+ recoverable: true
+ })
+
+ const bubble = lastAssistant()
+ expect(bubble?.error).toBe('kaput')
+ expect(bubble?.errorSurface).toBeUndefined()
+ })
})
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
index 6474b93431f..79c02e844c2 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
@@ -3,6 +3,7 @@ import { getSession } from '@/hermes'
import { assistantTextPart, type ChatMessage, chatMessageText, textPart } from '@/lib/chat-messages'
import { normalizePersonalityValue } from '@/lib/chat-runtime'
import { embeddedImageUrls, textWithoutEmbeddedImages } from '@/lib/embedded-images'
+import { parseErrorSurface } from '@/lib/error-surface'
import { reconcileApprovalModeForProfile } from '@/store/approval-mode'
import { requestDesktopOnboardingForCredentialWarning } from '@/store/onboarding'
import { $activeGatewayProfile, $profiles, normalizeProfileKey } from '@/store/profile'
@@ -146,6 +147,9 @@ const COMPARED_FIELDS = [
'role',
'pending',
'error',
+ // Structured failure layer — drives the error card's title and action row,
+ // so a change (e.g. resume replay attaching the descriptor) must repaint.
+ 'errorSurface',
'hidden',
'branchGroupId',
'interim',
@@ -254,6 +258,11 @@ export function chatMessagesEquivalent(a: ChatMessage, b: ChatMessage): boolean
a.role !== b.role ||
a.pending !== b.pending ||
a.error !== b.error ||
+ // Structural compare — the descriptor arrives as a fresh object per
+ // resume/replay, so identity comparison would repaint forever.
+ (a.errorSurface?.layer ?? null) !== (b.errorSurface?.layer ?? null) ||
+ (a.errorSurface?.code ?? null) !== (b.errorSurface?.code ?? null) ||
+ (a.errorSurface?.retryable ?? null) !== (b.errorSurface?.retryable ?? null) ||
a.hidden !== b.hidden ||
a.branchGroupId !== b.branchGroupId ||
a.timestamp !== b.timestamp ||
@@ -742,6 +751,7 @@ export function appendLiveSessionProjection(messages: ChatMessage[], projection:
// the terminal frame may have been lost to a disconnect) — surface the
// failure on the projected row instead of rendering the partial as healthy.
const inflightError = projection.inflight?.error?.trim() ?? ''
+ const inflightErrorSurface = parseErrorSurface(projection.inflight?.error_surface)
const queuedUser = projection.queued?.user?.trim() ?? ''
if (
@@ -904,7 +914,8 @@ export function appendLiveSessionProjection(messages: ChatMessage[], projection:
role: 'assistant',
parts: inflightAssistant ? [assistantTextPart(inflightAssistant)] : [],
pending: inflightStreaming,
- ...(inflightError ? { error: inflightError } : {})
+ ...(inflightError ? { error: inflightError } : {}),
+ ...(inflightError && inflightErrorSurface ? { errorSurface: inflightErrorSurface } : {})
})
}
diff --git a/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx b/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx
index f2cfdc09c11..1358327876c 100644
--- a/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx
@@ -8,8 +8,10 @@ import {
} from '@assistant-ui/react'
import { useStore } from '@nanostores/react'
import { type FC, type ReactNode, useCallback, useMemo, useState } from 'react'
+import { useNavigate } from 'react-router'
import { useSessionView } from '@/app/chat/session-view'
+import { SETTINGS_ROUTE } from '@/app/routes'
import { ChangedFilesCard } from '@/components/assistant-ui/thread/changed-files-card'
import {
contentHasVisibleText,
@@ -28,6 +30,7 @@ import { PreviewAttachment } from '@/components/chat/preview-attachment'
import { Codicon } from '@/components/ui/codicon'
import { CopyButton } from '@/components/ui/copy-button'
import { useI18n } from '@/i18n'
+import { type ErrorSurface, formatErrorDiagnostics } from '@/lib/error-surface'
import { triggerHaptic } from '@/lib/haptics'
import { AudioLines, GitForkIcon, Loader2Icon, RefreshCwIcon, SmilePlusIcon, VolumeXIcon, XIcon } from '@/lib/icons'
import { extractPreviewTargets } from '@/lib/preview-targets'
@@ -36,6 +39,7 @@ import { useEnterAnimation } from '@/lib/use-enter-animation'
import { cn } from '@/lib/utils'
import { playSpeechText, stopVoicePlayback } from '@/lib/voice-playback'
import { notifyError } from '@/store/notifications'
+import { $currentModel } from '@/store/session'
import { $voicePlayback } from '@/store/voice-playback'
// Stable empty identity for the settled-parts selector — a fresh [] per render
@@ -224,20 +228,26 @@ const AssistantMessageBody: FC<AssistantMessageProps & { collapsedNotice?: null
<AssistantPreviewEmbeds />
<MessagePrimitive.Error>
<ErrorPrimitive.Root
- className="mt-1.5 flex items-start gap-1.5 text-[0.78rem] leading-5 text-[color-mix(in_srgb,var(--dt-destructive)_78%,var(--ui-text-secondary))]"
+ className="mt-1.5 flex flex-col gap-1.5 rounded-lg border border-[color-mix(in_srgb,var(--dt-destructive)_35%,transparent)] bg-[color-mix(in_srgb,var(--dt-destructive)_7%,transparent)] px-3 py-2 text-[0.78rem] leading-5 text-[color-mix(in_srgb,var(--dt-destructive)_78%,var(--ui-text-secondary))]"
role="alert"
>
- <ErrorPrimitive.Message className="min-w-0 flex-1" />
- {onDismissError && (
- <TooltipIconButton
- className="-my-0.5 shrink-0 text-current opacity-70 hover:opacity-100"
- onClick={() => onDismissError(messageId)}
- side="top"
- tooltip={t.assistant.thread.dismissError}
- >
- <XIcon className="size-3.5" />
- </TooltipIconButton>
- )}
+ <div className="flex items-start gap-1.5">
+ <div className="min-w-0 flex-1">
+ <ErrorLayerLabel />
+ <ErrorPrimitive.Message className="min-w-0" />
+ </div>
+ {onDismissError && (
+ <TooltipIconButton
+ className="-my-0.5 shrink-0 text-current opacity-70 hover:opacity-100"
+ onClick={() => onDismissError(messageId)}
+ side="top"
+ tooltip={t.assistant.thread.dismissError}
+ >
+ <XIcon className="size-3.5" />
+ </TooltipIconButton>
+ )}
+ </div>
+ <ErrorRecoveryActions />
</ErrorPrimitive.Root>
</MessagePrimitive.Error>
</div>
@@ -433,6 +443,103 @@ const StreamingMarker: FC = () => {
)
}
+// ── Layered error card pieces ────────────────────────────────────────────
+//
+// The gateway stamps failed turns with a structured {layer, code, retryable}
+// descriptor (metadata.custom.errorSurface — see agent/error_surface.py).
+// These leaves render the layer label + recovery actions. Older backends
+// never send the descriptor: the label falls back to a generic title and the
+// action row still offers Retry / Open Logs / Copy diagnostics, so nothing
+// regresses on version skew.
+
+const ErrorLayerLabel: FC = () => {
+ const { t } = useI18n()
+ const surface = useAuiState(s => s.message.metadata?.custom?.errorSurface as ErrorSurface | undefined)
+
+ const labels = t.assistant.thread.errorLayers
+ const label = (surface && labels[surface.layer]) || labels.generic
+
+ return <div className="font-medium">{label}</div>
+}
+
+const ErrorRecoveryActions: FC = () => {
+ const { t } = useI18n()
+ const copy = t.assistant.thread
+ const surface = useAuiState(s => s.message.metadata?.custom?.errorSurface as ErrorSurface | undefined)
+
+ const errorText = useAuiState(s => {
+ const status = s.message.status as { error?: unknown; type?: string } | undefined
+
+ return status?.type === 'incomplete' && typeof status.error === 'string' ? status.error : ''
+ })
+
+ const navigate = useNavigate()
+ const model = useStore($currentModel)
+
+ // Retry = assistant-ui reload (same wiring as the footer's refresh action):
+ // re-runs the failed turn's prompt in place. Suppressed when the classifier
+ // says the failure is deterministic (retrying reproduces it).
+ const retryable = !surface || surface.retryable
+
+ // Switch Provider deep-links Settings → Models for the layers where the fix
+ // is provider/endpoint/auth config, not a retry.
+ const showSwitchProvider = surface != null && ['auth', 'billing', 'endpoint', 'provider'].includes(surface.layer)
+
+ const openLogs = useCallback(async () => {
+ try {
+ const root = await window.hermesDesktop?.logsRoot?.()
+
+ if (!root) {
+ notifyError(new Error('logs root unavailable'), copy.errorOpenLogsFailed)
+
+ return
+ }
+
+ const result = await window.hermesDesktop?.openDir?.(root)
+
+ if (result && !result.ok) {
+ notifyError(new Error(result.error || 'open failed'), copy.errorOpenLogsFailed)
+ }
+ } catch (error) {
+ notifyError(error, copy.errorOpenLogsFailed)
+ }
+ }, [copy.errorOpenLogsFailed])
+
+ const diagnosticsText = useCallback(
+ () =>
+ formatErrorDiagnostics({
+ errorText,
+ model: model || undefined,
+ surface
+ }),
+ [errorText, model, surface]
+ )
+
+ return (
+ <div className="flex flex-wrap items-center gap-1.5">
+ {retryable && (
+ <ActionBarPrimitive.Reload asChild>
+ <button className="aui-error-action" onClick={() => triggerHaptic('submit')} type="button">
+ <RefreshCwIcon className="size-3" />
+ {copy.errorRetry}
+ </button>
+ </ActionBarPrimitive.Reload>
+ )}
+ {showSwitchProvider && (
+ <button className="aui-error-action" onClick={() => navigate(`${SETTINGS_ROUTE}?tab=config:model`)} type="button">
+ {copy.errorSwitchProvider}
+ </button>
+ )}
+ {window.hermesDesktop?.logsRoot && (
+ <button className="aui-error-action" onClick={() => void openLogs()} type="button">
+ {copy.errorOpenLogs}
+ </button>
+ )}
+ <CopyButton appearance="inline" className="aui-error-action" label={copy.errorCopyDiagnostics} text={diagnosticsText} />
+ </div>
+ )
+}
+
const AssistantActionBar: FC<MessageActionProps> = ({ messageId, getMessageText, onBranchInNewChat }) => {
const { t } = useI18n()
const copy = t.assistant.thread
diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.ts
index 98db0b39b37..f0038c367ec 100644
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@ -297,6 +297,8 @@ declare global {
// resolved by Electron independently of the connected backend (#66899).
// Created on demand; returns the normalized absolute path.
desktopPluginsRoot?: () => Promise<string>
+ /** LOCAL `<HERMES_HOME>/logs` (profile-aware) — error card "Open Logs". */
+ logsRoot?: () => Promise<string>
// Local AGENT-plugin root (<HERMES_HOME>/plugins), same Electron-local
// resolution. The disk door also scans it for `<name>/desktop/plugin.js`
// so one agent-plugin package can ship a desktop UI half. Optional:
diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.ts
index d59c83f71f4..86eaa3b2297 100644
--- a/apps/desktop/src/i18n/ar.ts
+++ b/apps/desktop/src/i18n/ar.ts
@@ -2434,6 +2434,22 @@ export const ar = defineLocale({
branchNewChat: 'تفريع إلى محادثة جديدة',
react: 'تفاعل',
dismissError: 'تجاهل الخطأ',
+ errorLayers: {
+ auth: 'خطأ في المصادقة',
+ billing: 'نفاد الرصيد',
+ disk: 'القرص ممتلئ',
+ endpoint: 'خطأ في نقطة النهاية المخصصة',
+ gateway: 'خطأ في البوابة',
+ generic: 'فشلت الجولة',
+ provider: 'خطأ من المزوّد',
+ runtime: 'خطأ في بيئة التشغيل المحلية',
+ streaming: 'خطأ في اتصال البث'
+ },
+ errorRetry: 'إعادة المحاولة',
+ errorSwitchProvider: 'تبديل المزوّد',
+ errorOpenLogs: 'فتح السجلات',
+ errorOpenLogsFailed: 'تعذّر فتح مجلد السجلات',
+ errorCopyDiagnostics: 'نسخ التشخيصات',
filesChanged: count => `${count} ملفات تم تغييرها`,
reviewChanges: 'مراجعة',
readAloudFailed: 'فشلت القراءة بصوت عال',
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index d8926ce09df..5870321a6a5 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -3079,6 +3079,22 @@ export const en: Translations = {
branchNewChat: 'Branch in new chat',
react: 'React',
dismissError: 'Dismiss error',
+ errorLayers: {
+ auth: 'Authentication error',
+ billing: 'Out of credits',
+ disk: 'Disk full',
+ endpoint: 'Custom endpoint error',
+ gateway: 'Gateway error',
+ generic: 'Turn failed',
+ provider: 'Provider error',
+ runtime: 'Local runtime error',
+ streaming: 'Streaming connection error'
+ },
+ errorRetry: 'Retry',
+ errorSwitchProvider: 'Switch provider',
+ errorOpenLogs: 'Open logs',
+ errorOpenLogsFailed: 'Could not open the logs folder',
+ errorCopyDiagnostics: 'Copy diagnostics',
filesChanged: count => (count === 1 ? '1 file changed' : `${count} files changed`),
reviewChanges: 'Review',
readAloudFailed: 'Read aloud failed',
diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.ts
index 5868fca013b..e1a492ecb88 100644
--- a/apps/desktop/src/i18n/ja.ts
+++ b/apps/desktop/src/i18n/ja.ts
@@ -2731,6 +2731,22 @@ export const ja = defineLocale({
branchNewChat: '新しいチャットでブランチ',
react: 'リアクション',
dismissError: 'エラーを閉じる',
+ errorLayers: {
+ auth: '認証エラー',
+ billing: 'クレジット不足',
+ disk: 'ディスク容量不足',
+ endpoint: 'カスタムエンドポイントのエラー',
+ gateway: 'ゲートウェイのエラー',
+ generic: 'ターンが失敗しました',
+ provider: 'プロバイダーのエラー',
+ runtime: 'ローカルランタイムのエラー',
+ streaming: 'ストリーミング接続のエラー'
+ },
+ errorRetry: '再試行',
+ errorSwitchProvider: 'プロバイダーを切り替え',
+ errorOpenLogs: 'ログを開く',
+ errorOpenLogsFailed: 'ログフォルダを開けませんでした',
+ errorCopyDiagnostics: '診断情報をコピー',
filesChanged: count => `${count} 件のファイルを変更`,
reviewChanges: 'レビュー',
readAloudFailed: '読み上げに失敗しました',
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index 61ef0bbc041..dc8151982ea 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -2648,6 +2648,24 @@ export interface Translations {
branchNewChat: string
react: string
dismissError: string
+ /** Layer titles for the structured error card (agent/error_surface.py).
+ * `generic` is the fallback when the backend sent no descriptor. */
+ errorLayers: {
+ auth: string
+ billing: string
+ disk: string
+ endpoint: string
+ gateway: string
+ generic: string
+ provider: string
+ runtime: string
+ streaming: string
+ }
+ errorRetry: string
+ errorSwitchProvider: string
+ errorOpenLogs: string
+ errorOpenLogsFailed: string
+ errorCopyDiagnostics: string
filesChanged: (count: number) => string
reviewChanges: string
readAloudFailed: string
diff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.ts
index b2317b4ea15..378a90662af 100644
--- a/apps/desktop/src/i18n/zh-hant.ts
+++ b/apps/desktop/src/i18n/zh-hant.ts
@@ -2641,6 +2641,22 @@ export const zhHant = defineLocale({
branchNewChat: '在新聊天中分支',
react: '回應',
dismissError: '关闭错误',
+ errorLayers: {
+ auth: '認證錯誤',
+ billing: '額度不足',
+ disk: '磁碟已滿',
+ endpoint: '自訂端點錯誤',
+ gateway: '閘道錯誤',
+ generic: '本輪失敗',
+ provider: '模型服務商錯誤',
+ runtime: '本機執行環境錯誤',
+ streaming: '串流連線錯誤'
+ },
+ errorRetry: '重試',
+ errorSwitchProvider: '切換服務商',
+ errorOpenLogs: '開啟日誌',
+ errorOpenLogsFailed: '無法開啟日誌資料夾',
+ errorCopyDiagnostics: '複製診斷資訊',
filesChanged: count => `${count} 個檔案已變更`,
reviewChanges: '檢視',
readAloudFailed: '朗讀失敗',
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index 66585070a42..5cdbc9db259 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -3243,6 +3243,22 @@ export const zh: Translations = {
branchNewChat: '在新对话中分支',
react: '回应',
dismissError: '关闭错误',
+ errorLayers: {
+ auth: '认证错误',
+ billing: '额度不足',
+ disk: '磁盘已满',
+ endpoint: '自定义端点错误',
+ gateway: '网关错误',
+ generic: '本轮失败',
+ provider: '模型服务商错误',
+ runtime: '本地运行时错误',
+ streaming: '流式连接错误'
+ },
+ errorRetry: '重试',
+ errorSwitchProvider: '切换服务商',
+ errorOpenLogs: '打开日志',
+ errorOpenLogsFailed: '无法打开日志文件夹',
+ errorCopyDiagnostics: '复制诊断信息',
filesChanged: count => `${count} 个文件已更改`,
reviewChanges: '查看',
readAloudFailed: '朗读失败',
diff --git a/apps/desktop/src/lib/chat-messages/types.ts b/apps/desktop/src/lib/chat-messages/types.ts
index 0706a730850..8620b85853a 100644
--- a/apps/desktop/src/lib/chat-messages/types.ts
+++ b/apps/desktop/src/lib/chat-messages/types.ts
@@ -1,6 +1,7 @@
import type { ThreadMessageLike } from '@assistant-ui/react'
import { type BillingBlock } from '@hermes/shared'
+import type { ErrorSurface } from '@/lib/error-surface'
import type { MessageReaction, SessionMessage, UsageStats } from '@/types/hermes'
export interface TimelinePartMetadata {
@@ -21,6 +22,10 @@ export type ChatMessage = {
completedAt?: number
pending?: boolean
error?: string
+ /** Structured layer descriptor for a failed turn (parsed error_surface).
+ * Drives the error card's layer label + actions; absent on older
+ * backends, where the card falls back to generic copy. */
+ errorSurface?: ErrorSurface
branchGroupId?: string
hidden?: boolean
/** Sealed mid-turn commentary (`message.interim`) — rendered without the
@@ -59,6 +64,10 @@ export type GatewayEventPayload = {
result?: unknown
summary?: string
error?: string | boolean
+ // message.complete with status "error" — structured {layer, code, retryable}
+ // descriptor naming which stack layer failed (agent/error_surface.py).
+ // Absent on older gateways; consumers must fall back to string heuristics.
+ error_surface?: unknown
inline_diff?: string
duration_s?: number
todos?: unknown
diff --git a/apps/desktop/src/lib/chat-runtime.ts b/apps/desktop/src/lib/chat-runtime.ts
index 8bf133b674a..211912dad60 100644
--- a/apps/desktop/src/lib/chat-runtime.ts
+++ b/apps/desktop/src/lib/chat-runtime.ts
@@ -484,6 +484,8 @@ export function toRuntimeMessage(message: ChatMessage): ThreadMessage {
...timelineMeta,
...(message.completedAt !== undefined ? { timelineCompletedAt: message.completedAt } : {}),
...(message.durationS !== undefined ? { durationS: message.durationS } : {}),
+ // Structured failure layer for the error card (see lib/error-surface).
+ ...(message.errorSurface ? { errorSurface: message.errorSurface } : {}),
...reactionMeta
}
}
diff --git a/apps/desktop/src/lib/error-surface.test.ts b/apps/desktop/src/lib/error-surface.test.ts
new file mode 100644
index 00000000000..ea7f9bd87d8
--- /dev/null
+++ b/apps/desktop/src/lib/error-surface.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, it } from 'vitest'
+
+import { formatErrorDiagnostics, parseErrorSurface } from './error-surface'
+
+describe('parseErrorSurface', () => {
+ it('accepts a valid descriptor', () => {
+ expect(parseErrorSurface({ layer: 'streaming', code: 'stream_drop', retryable: true })).toEqual({
+ layer: 'streaming',
+ code: 'stream_drop',
+ retryable: true
+ })
+ })
+
+ it('accepts every documented layer', () => {
+ for (const layer of ['provider', 'endpoint', 'streaming', 'auth', 'billing', 'gateway', 'runtime', 'disk']) {
+ expect(parseErrorSurface({ layer, code: 'x', retryable: false })?.layer).toBe(layer)
+ }
+ })
+
+ it('rejects unknown layers and non-objects', () => {
+ expect(parseErrorSurface({ layer: 'blockchain', code: 'x', retryable: true })).toBeNull()
+ expect(parseErrorSurface('provider')).toBeNull()
+ expect(parseErrorSurface(null)).toBeNull()
+ expect(parseErrorSurface(undefined)).toBeNull()
+ expect(parseErrorSurface(7)).toBeNull()
+ })
+
+ it('defaults code and retryable when missing', () => {
+ expect(parseErrorSurface({ layer: 'gateway' })).toEqual({ layer: 'gateway', code: 'unknown', retryable: true })
+ })
+
+ it('honors retryable=false', () => {
+ expect(parseErrorSurface({ layer: 'auth', code: 'auth_permanent', retryable: false })?.retryable).toBe(false)
+ })
+})
+
+describe('formatErrorDiagnostics', () => {
+ it('includes layer, code, model and error', () => {
+ const text = formatErrorDiagnostics({
+ errorText: 'boom',
+ model: 'anthropic/claude-opus-4.6',
+ surface: { layer: 'provider', code: 'rate_limit', retryable: true }
+ })
+
+ expect(text).toContain('layer: provider')
+ expect(text).toContain('code: rate_limit')
+ expect(text).toContain('model: anthropic/claude-opus-4.6')
+ expect(text).toContain('error: boom')
+ })
+
+ it('omits absent fields without leaving blank lines', () => {
+ const text = formatErrorDiagnostics({ errorText: 'boom' })
+
+ expect(text).not.toContain('layer:')
+ expect(text).not.toContain('model:')
+ expect(text.split('\n').every(line => line.trim().length > 0)).toBe(true)
+ })
+})
diff --git a/apps/desktop/src/lib/error-surface.ts b/apps/desktop/src/lib/error-surface.ts
new file mode 100644
index 00000000000..2297afa023c
--- /dev/null
+++ b/apps/desktop/src/lib/error-surface.ts
@@ -0,0 +1,71 @@
+// Structured turn-error descriptor forwarded by the gateway (see
+// agent/error_surface.py). Names WHICH layer of the stack failed so the error
+// card can say "Provider error" / "Gateway error" and offer layer-appropriate
+// recovery actions, instead of toasting an opaque string.
+//
+// Advisory contract: older backends never send this — every consumer must
+// keep working when it is absent (legacy string-sniffing stays as fallback).
+
+export const ERROR_SURFACE_LAYERS = [
+ 'provider',
+ 'endpoint',
+ 'streaming',
+ 'auth',
+ 'billing',
+ 'gateway',
+ 'runtime',
+ 'disk'
+] as const
+
+export type ErrorSurfaceLayer = (typeof ERROR_SURFACE_LAYERS)[number]
+
+export interface ErrorSurface {
+ layer: ErrorSurfaceLayer
+ /** Specific failure code (a FailoverReason value or site-specific code). */
+ code: string
+ /** False when retrying unchanged reproduces the same failure. */
+ retryable: boolean
+}
+
+/** Validate a wire payload into an ErrorSurface, or null when absent/garbled. */
+export function parseErrorSurface(value: unknown): ErrorSurface | null {
+ if (!value || typeof value !== 'object') {
+ return null
+ }
+
+ const raw = value as { code?: unknown; layer?: unknown; retryable?: unknown }
+ const layer = typeof raw.layer === 'string' ? (raw.layer as ErrorSurfaceLayer) : null
+
+ if (!layer || !ERROR_SURFACE_LAYERS.includes(layer)) {
+ return null
+ }
+
+ return {
+ layer,
+ code: typeof raw.code === 'string' && raw.code ? raw.code : 'unknown',
+ retryable: raw.retryable !== false
+ }
+}
+
+/** Plain-text diagnostics blob for the error card's "Copy diagnostics". */
+export function formatErrorDiagnostics(input: {
+ appVersion?: string
+ errorText: string
+ model?: string
+ provider?: string
+ surface?: ErrorSurface | null
+}): string {
+ const lines = [
+ '── Hermes error diagnostics ──',
+ `time: ${new Date().toISOString()}`,
+ input.surface ? `layer: ${input.surface.layer}` : null,
+ input.surface ? `code: ${input.surface.code}` : null,
+ input.surface ? `retryable: ${input.surface.retryable}` : null,
+ input.provider ? `provider: ${input.provider}` : null,
+ input.model ? `model: ${input.model}` : null,
+ input.appVersion ? `app: ${input.appVersion}` : null,
+ `error: ${input.errorText}`
+ ]
+
+ return lines.filter((line): line is string => Boolean(line)).join('\n')
+}
diff --git a/apps/desktop/src/styles.css b/apps/desktop/src/styles.css
index 396ed175d9d..8bf309d4ea0 100644
--- a/apps/desktop/src/styles.css
+++ b/apps/desktop/src/styles.css
@@ -2107,6 +2107,28 @@ button[data-slot='aui_msg-reactions']:not([data-reacted])[data-state='open'] {
pointer-events: auto;
}
+/* Failed-turn error card actions (Retry · Switch provider · Open logs ·
+ Copy diagnostics) — compact pill buttons tinted to the card's destructive
+ palette. Stylesheet-owned so the CopyButton inline appearance picks the
+ same look via the shared class. */
+.aui-error-action {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.3rem;
+ border: 1px solid color-mix(in srgb, var(--dt-destructive) 30%, transparent);
+ border-radius: 9999px;
+ background: transparent;
+ padding: 0.1rem 0.55rem;
+ font-size: 0.72rem;
+ line-height: 1.1rem;
+ color: color-mix(in srgb, var(--dt-destructive) 80%, var(--ui-text-secondary));
+ cursor: pointer;
+}
+
+.aui-error-action:hover {
+ background: color-mix(in srgb, var(--dt-destructive) 10%, transparent);
+}
+
.group:hover button[data-slot='aui_msg-reactions']:not([data-reacted]):hover,
button[data-slot='aui_msg-reactions']:not([data-reacted])[data-state='open'] {
opacity: 1;
diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.ts
index 783ee945e5d..2c80596c6ac 100644
--- a/apps/desktop/src/types/hermes.ts
+++ b/apps/desktop/src/types/hermes.ts
@@ -638,6 +638,9 @@ export interface SessionResumeResponse {
/** Retained failed turn: the error the terminal frame carried (the frame
* itself may have been lost to a disconnect). */
error?: string
+ /** Structured {layer, code, retryable} descriptor for the retained failed
+ * turn (see agent/error_surface.py). Omitted by older gateways. */
+ error_surface?: unknown
recoverable?: boolean
status?: string
streaming?: boolean
diff --git a/tests/agent/test_error_surface.py b/tests/agent/test_error_surface.py
new file mode 100644
index 00000000000..e17dcfd4746
--- /dev/null
+++ b/tests/agent/test_error_surface.py
@@ -0,0 +1,167 @@
+"""Tests for agent/error_surface.py — turn-error → UI layer descriptors."""
+
+from __future__ import annotations
+
+import pytest
+
+from agent.error_surface import (
+ LAYER_AUTH,
+ LAYER_BILLING,
+ LAYER_DISK,
+ LAYER_ENDPOINT,
+ LAYER_GATEWAY,
+ LAYER_PROVIDER,
+ LAYER_STREAMING,
+ build_error_surface_from_exception,
+ build_error_surface_from_result,
+)
+
+
+# ── build_error_surface_from_result ──────────────────────────────────────
+
+
+def _failed_result(reason: str = "", error: str = "provider exploded", **extra) -> dict:
+ result = {"completed": False, "failed": True, "error": error}
+ if reason:
+ result["failure_reason"] = reason
+ result.update(extra)
+ return result
+
+
+def test_result_none_for_non_dict():
+ assert build_error_surface_from_result("boom") is None
+ assert build_error_surface_from_result(None) is None
+
+
+def test_result_none_for_healthy_result():
+ assert (
+ build_error_surface_from_result({"completed": True, "final_response": "hi"})
+ is None
+ )
+
+
+def test_result_auth_reasons_map_to_auth_layer():
+ surface = build_error_surface_from_result(_failed_result("auth"))
+ assert surface == {"layer": LAYER_AUTH, "code": "auth", "retryable": True}
+
+ surface = build_error_surface_from_result(_failed_result("auth_permanent"))
+ assert surface["layer"] == LAYER_AUTH
+ assert surface["retryable"] is False
+
+
+def test_result_billing_block_wins():
+ surface = build_error_surface_from_result(
+ _failed_result("rate_limit", billing_block={"provider": "nous"})
+ )
+ assert surface["layer"] == LAYER_BILLING
+ assert surface["retryable"] is False
+
+
+def test_result_billing_reason_without_block():
+ surface = build_error_surface_from_result(_failed_result("billing"))
+ assert surface == {"layer": LAYER_BILLING, "code": "billing", "retryable": False}
+
+
+def test_result_provider_default_for_classified_reasons():
+ for reason in (
+ "rate_limit",
+ "server_error",
+ "overloaded",
+ "unknown",
+ "format_error",
+ ):
+ surface = build_error_surface_from_result(_failed_result(reason))
+ assert surface["layer"] == LAYER_PROVIDER, reason
+ assert surface["code"] == reason
+
+
+def test_result_non_retryable_reasons():
+ for reason in (
+ "content_policy_blocked",
+ "model_not_found",
+ "ssl_cert_verification",
+ ):
+ surface = build_error_surface_from_result(_failed_result(reason))
+ assert surface["retryable"] is False, reason
+
+
+def test_result_timeout_on_custom_endpoint_is_endpoint_layer():
+ surface = build_error_surface_from_result(
+ _failed_result("timeout"), provider="custom"
+ )
+ assert surface["layer"] == LAYER_ENDPOINT
+
+ # Same reason on a vendor provider stays provider-layer.
+ surface = build_error_surface_from_result(
+ _failed_result("timeout"), provider="anthropic"
+ )
+ assert surface["layer"] == LAYER_PROVIDER
+
+
+def test_result_stream_drop_text_maps_to_streaming():
+ surface = build_error_surface_from_result(
+ _failed_result(error="The provider's stream connection keeps dropping")
+ )
+ assert surface["layer"] == LAYER_STREAMING
+ assert surface["code"] == "stream_drop"
+ assert surface["retryable"] is True
+
+
+def test_result_unclassified_failure_defaults_to_provider_unknown():
+ surface = build_error_surface_from_result(_failed_result(error="something odd"))
+ assert surface == {"layer": LAYER_PROVIDER, "code": "unknown", "retryable": True}
+
+
+def test_result_disk_full_wins_over_reason():
+ surface = build_error_surface_from_result(
+ _failed_result(
+ "server_error", error="OSError: [Errno 28] No space left on device"
+ )
+ )
+ assert surface["layer"] == LAYER_DISK
+ assert surface["retryable"] is False
+
+
+# ── build_error_surface_from_exception ───────────────────────────────────
+
+
+def test_exception_non_api_is_gateway_layer():
+ surface = build_error_surface_from_exception(KeyError("history"))
+ assert surface["layer"] == LAYER_GATEWAY
+ assert surface["code"] == "KeyError"
+ assert surface["retryable"] is True
+
+
+def test_exception_disk_full_is_disk_layer():
+ surface = build_error_surface_from_exception(OSError(28, "No space left on device"))
+ assert surface["layer"] == LAYER_DISK
+
+
+def test_exception_with_status_code_routes_through_classifier():
+ class FakeAPIError(Exception):
+ status_code = 429
+
+ surface = build_error_surface_from_exception(
+ FakeAPIError("rate limited"), provider="openrouter"
+ )
+ # 429 → rate_limit → provider layer via the real classifier.
+ assert surface["layer"] == LAYER_PROVIDER
+ assert surface["code"] in ("rate_limit", "upstream_rate_limit")
+
+
+def test_exception_auth_status_routes_to_auth_layer():
+ class FakeAuthError(Exception):
+ status_code = 401
+
+ surface = build_error_surface_from_exception(FakeAuthError("invalid api key"))
+ assert surface["layer"] == LAYER_AUTH
+
+
+def test_exception_never_raises_on_weird_input():
+ class Hostile(Exception):
+ @property
+ def status_code(self): # pragma: no cover - exercised via classifier
+ raise RuntimeError("hostile attribute")
+
+ # Must not raise, whatever it returns.
+ build_error_surface_from_exception(Hostile("x"))
diff --git a/tests/tui_gateway/test_failed_turn_retention.py b/tests/tui_gateway/test_failed_turn_retention.py
index 064a1fdf730..455fcc22d50 100644
--- a/tests/tui_gateway/test_failed_turn_retention.py
+++ b/tests/tui_gateway/test_failed_turn_retention.py
@@ -171,6 +171,62 @@ def test_returned_error_result_retains_snapshot_and_emits_terminal_frame(
assert session["running"] is False
+def test_returned_error_result_carries_error_surface(emits, turn_env):
+ """A classified failure_reason rides the terminal frame AND the retained
+ snapshot as a structured {layer, code, retryable} descriptor, so the
+ desktop names the failing layer instead of sniffing the message."""
+ agent = types.SimpleNamespace(
+ session_id="session-key",
+ provider="openrouter",
+ model="test/model",
+ run_conversation=lambda *a, **k: {
+ "final_response": "",
+ "error": "Rate limit exceeded",
+ "failed": True,
+ "failure_reason": "rate_limit",
+ },
+ clear_interrupt=lambda: None,
+ )
+ session = _session(agent=agent, running=True)
+ server._start_inflight_turn(session, "do the thing")
+
+ server._run_prompt_submit("rid", "sid", session, "do the thing")
+
+ payload = _events(emits, "message.complete")[0]
+ assert payload["error_surface"] == {
+ "layer": "provider",
+ "code": "rate_limit",
+ "retryable": True,
+ }
+
+ snapshot = server._inflight_snapshot(session)
+ assert snapshot is not None
+ assert snapshot["error_surface"]["layer"] == "provider"
+
+
+def test_returned_error_without_reason_omits_no_frame(emits, turn_env):
+ """Legacy result dicts (no failure_reason) still get a best-effort
+ descriptor — never a crash, never a missing terminal frame."""
+ agent = types.SimpleNamespace(
+ session_id="session-key",
+ run_conversation=lambda *a, **k: {
+ "final_response": "",
+ "error": "something odd",
+ "failed": True,
+ },
+ clear_interrupt=lambda: None,
+ )
+ session = _session(agent=agent, running=True)
+ server._start_inflight_turn(session, "go")
+
+ server._run_prompt_submit("rid", "sid", session, "go")
+
+ payload = _events(emits, "message.complete")[0]
+ assert payload["status"] == "error"
+ assert payload["error_surface"]["layer"] == "provider"
+ assert payload["error_surface"]["code"] == "unknown"
+
+
def test_completed_turn_still_clears_inflight(emits, turn_env):
agent = types.SimpleNamespace(
session_id="session-key",
@@ -225,6 +281,10 @@ def test_exception_closes_turn_with_terminal_complete_and_partial(emits, turn_en
assert snapshot["error"] == "connection reset mid-stream"
assert session["running"] is False
+ # Dispatcher-side exceptions (not API errors) classify as gateway-layer.
+ assert payload["error_surface"]["layer"] == "gateway"
+ assert snapshot["error_surface"]["layer"] == "gateway"
+
# ── Resume replay (the reason retention exists) ───────────────────────
diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.py
index fa0dcd949f3..a9773bfe46b 100644
--- a/tui_gateway/methods_prompt.py
+++ b/tui_gateway/methods_prompt.py
@@ -786,6 +786,9 @@ def _(rid, params: dict) -> dict:
sid,
session,
(err.get("error") or {}).get("message", "agent initialization failed"),
+ # Agent construction never reached the provider: this is a
+ # local-runtime failure (env/config/venv), not an API error.
+ error_surface={"layer": "runtime", "code": "agent_init_failed", "retryable": True},
)
with session["history_lock"]:
session["running"] = False
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index ff08824ea30..48d8039c53e 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -7902,7 +7902,9 @@ def _clear_inflight_turn(session: dict) -> None:
session["inflight_turn"] = None
-def _fail_inflight_turn(session: dict, error: Any) -> None:
+def _fail_inflight_turn(
+ session: dict, error: Any, error_surface: Optional[dict] = None
+) -> None:
"""Mark the in-flight turn terminal-error but keep it replayable.
Normal completion clears ``inflight_turn`` because the response is now in
@@ -7926,6 +7928,13 @@ def _fail_inflight_turn(session: dict, error: Any) -> None:
turn["error"] = message or "turn failed"
turn["status"] = "error"
turn["recoverable"] = True
+ if error_surface:
+ # Structured {layer, code, retryable} descriptor — replayed to
+ # resuming clients via the resume snapshot so a reconnect renders the
+ # same layered error card the live frame carried.
+ turn["error_surface"] = dict(error_surface)
+ else:
+ turn.pop("error_surface", None)
turn["streaming"] = False
turn["updated_at"] = now
session["inflight_turn"] = turn
@@ -8485,10 +8494,15 @@ def _inflight_snapshot(session: dict) -> dict | None:
snapshot["error"] = error
snapshot["status"] = str(turn.get("status") or "error")
snapshot["recoverable"] = bool(turn.get("recoverable"))
+ surface = turn.get("error_surface")
+ if isinstance(surface, dict) and surface:
+ snapshot["error_surface"] = surface
return snapshot
-def _emit_terminal_turn_error(sid: str, session: dict, error: Any) -> None:
+def _emit_terminal_turn_error(
+ sid: str, session: dict, error: Any, error_surface: Optional[dict] = None
+) -> None:
"""Close a failed turn with a terminal ``message.complete`` frame.
Emits the same ``status: "error"`` frame shape the returned-error path in
@@ -8496,15 +8510,33 @@ def _emit_terminal_turn_error(sid: str, session: dict, error: Any) -> None:
uniform), and retains the failed turn via ``_fail_inflight_turn`` so a
client that missed this frame (disconnect window) can recover it from
``session.resume``'s ``inflight`` payload.
+
+ ``error_surface`` lets callers that already know the failing layer (e.g.
+ agent-init failures = local runtime) pass it explicitly; exception
+ callers leave it None and the classifier derives it here.
"""
+ agent = session.get("agent")
+ # Classify the failure into a {layer, code, retryable} descriptor so the
+ # desktop can say "Provider error" / "Gateway error" with matching
+ # recovery actions instead of a generic toast. Never raises (advisory).
+ if error_surface is None and isinstance(error, BaseException):
+ try:
+ from agent.error_surface import build_error_surface_from_exception
+
+ error_surface = build_error_surface_from_exception(
+ error,
+ provider=str(getattr(agent, "provider", "") or ""),
+ model=str(getattr(agent, "model", "") or ""),
+ )
+ except Exception:
+ error_surface = None
with session["history_lock"]:
- _fail_inflight_turn(session, error)
+ _fail_inflight_turn(session, error, error_surface=error_surface)
turn = session.get("inflight_turn") or {}
message = str(turn.get("error") or "turn failed")
partial = str(turn.get("assistant") or "")
cols = int(session.get("cols", 80))
text = partial or f"Error: {message}"
- agent = session.get("agent")
payload = {
"text": text,
"usage": _get_usage(agent) if agent is not None else {},
@@ -8512,6 +8544,8 @@ def _emit_terminal_turn_error(sid: str, session: dict, error: Any) -> None:
"error": message,
"recoverable": True,
}
+ if error_surface:
+ payload["error_surface"] = error_surface
if partial:
payload["partial"] = True
try:
@@ -11233,6 +11267,25 @@ def _run_prompt_submit(
rendered = render_message(raw, cols)
if rendered:
payload["rendered"] = rendered
+ # Structured layer descriptor ({layer, code, retryable}) so
+ # clients can name WHICH part of the stack failed (provider /
+ # streaming / auth / gateway / …) and offer layer-appropriate
+ # recovery actions instead of sniffing the message string.
+ # Advisory: older clients ignore it, absence falls back to
+ # string heuristics on newer clients. Computed before the retain
+ # below so resume replay carries the same descriptor.
+ _error_surface = None
+ if status == "error":
+ try:
+ from agent.error_surface import build_error_surface_from_result
+
+ _error_surface = build_error_surface_from_result(
+ result,
+ provider=str(getattr(agent, "provider", "") or ""),
+ model=str(getattr(agent, "model", "") or ""),
+ )
+ except Exception:
+ _error_surface = None
with session["history_lock"]:
if status == "error":
# Returned-error result (provider 4xx, budget, etc.): retain
@@ -11242,6 +11295,7 @@ def _run_prompt_submit(
_fail_inflight_turn(
session,
result.get("error") if isinstance(result, dict) else raw,
+ error_surface=_error_surface,
)
turn_error_retained = True
else:
@@ -11251,6 +11305,8 @@ def _run_prompt_submit(
(result.get("error") if isinstance(result, dict) else "") or raw
)
payload["recoverable"] = True
+ if _error_surface:
+ payload["error_surface"] = _error_surface
_retire_turn_marker(session, marker_key)
_emit("message.complete", sid, payload)
diff --git a/website/docs/user-guide/desktop.md b/website/docs/user-guide/desktop.md
index bb3d561474d..ea4ca3b93ee 100644
--- a/website/docs/user-guide/desktop.md
+++ b/website/docs/user-guide/desktop.md
@@ -409,6 +409,26 @@ another profile's agent plugins without switching the whole app (the backend
## Troubleshooting
+### Failed turns name the failing layer
+
+When a turn fails, the chat renders an error card that names **which layer
+failed** — provider/model, custom endpoint, streaming connection,
+authentication, billing, gateway, local runtime, or disk — instead of a
+generic error toast. The card offers recovery actions matched to the failure:
+
+- **Retry** — re-runs the failed turn in place (hidden when retrying would
+ deterministically reproduce the failure, e.g. a content-policy rejection).
+- **Switch provider** — jumps to Settings → Models for provider, endpoint,
+ auth, and billing failures.
+- **Open logs** — opens `HERMES_HOME/logs` in your file manager.
+- **Copy diagnostics** — copies a compact plain-text summary (layer, code,
+ provider/model, error message) you can paste into a bug report or Discord.
+
+The layer comes from the same error classifier the agent's retry loop uses,
+so it reflects the real failure semantics, not a guess from the message text.
+Older backends that predate the descriptor still render the card with a
+generic title and the Retry / Open logs / Copy diagnostics actions.
+
Boot logs land in `HERMES_HOME/logs/desktop.log` (it includes backend output and recent Python tracebacks) — check it first if the app reports a boot failure. You can also tail it from the CLI:
```bash