The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(error-surface): 429 error card shows when the usage limit resets
teknium1645e9298b6de
diff --git a/agent/error_surface.py b/agent/error_surface.pyindex d03512c26e8..0ca6415b6d5 100644--- a/agent/error_surface.py+++ b/agent/error_surface.py@@ -173,7 +173,13 @@ def build_error_surface_from_result(result: Any, provider: str = "", model: strretryable = result.get("failure_retryable")if not isinstance(retryable, bool):retryable = reason not in _NON_RETRYABLE_REASONS- return _surface(_result_layer(reason, error_text, provider), reason, retryable, provider, model)+ surface = _surface(_result_layer(reason, error_text, provider), reason, retryable, provider, model)+ # When the provider named the moment its limit lifts (Retry-After / ``resets_at``,+ # ``agent/turn_recovery.py::_stamp_limit_reset``) the card can say "Limit resets at HH:mm"+ # next to Retry instead of leaving the user to guess (#98852). Epoch seconds.+ if isinstance(resets_at := result.get("failure_resets_at"), (int, float)) and not isinstance(resets_at, bool):+ surface["resets_at"] = float(resets_at)+ return surfaceexcept Exception: # pragma: no cover — never break the error pathlogger.debug("error_surface: result classification failed", exc_info=True)return None@@ -199,6 +205,11 @@ def build_error_surface_from_exception(classified = classify_api_error(exc, provider=provider, model=model, api_key=api_key)synthetic = {"error": classified.message or message, "failure_reason": classified.reason.value}+ from agent.agent_runtime_helpers import extract_api_error_context+ from agent.credential_pool import _parse_absolute_timestamp++ if (resets_at := _parse_absolute_timestamp(extract_api_error_context(exc).get("reset_at"))) is not None:+ synthetic["failure_resets_at"] = resets_atsurface = build_error_surface_from_result(synthetic, provider=provider, model=model)if surface is not None:surface["retryable"] = bool(classified.retryable)diff --git a/agent/turn_failure_copy.py b/agent/turn_failure_copy.pyindex fec973dd595..c0df3badba2 100644--- a/agent/turn_failure_copy.py+++ b/agent/turn_failure_copy.py@@ -9,6 +9,7 @@ trailing "Provider said:" / "Details:" line.from __future__ import annotations+import timefrom typing import Any, Dict, NamedTuple, Optional, Tuplefrom agent.error_classifier import FailoverReason@@ -310,6 +311,19 @@ def exhausted_copy(reason: str, *, label: str, attempts: int, summary: str) -> s)+def limit_reset_copy(resets_at: float, now: Optional[float] = None) -> str:+ """One chat/CLI line naming when the provider says the limit lifts (#98852): the Retry-After+ / ``resets_at`` the loop already honours for backoff, shown to the user instead of a bare+ "wait a minute". Local wall-clock time plus the remaining wait; empty once it has passed."""+ now = time.time() if now is None else now+ remaining = int(resets_at - now)+ if remaining <= 0:+ return ""+ hours, minutes = divmod((remaining + 59) // 60, 60)+ wait = f"{hours}h {minutes:02d}m" if hours else f"{minutes}m"+ return f"Limit resets at {time.strftime('%H:%M', time.localtime(resets_at))} (in {wait})."++def oauth_relogin_command(provider: Any) -> str:"""The exact re-login command for a rejected OAuth grant, naming the provider slug and the activenamed profile: a profile's credentials are its own (93889b770da), so a bare ``hermes auth`` fromdiff --git a/agent/turn_recovery.py b/agent/turn_recovery.pyindex 008b3b3649f..c8e5a8b6783 100644--- a/agent/turn_recovery.py+++ b/agent/turn_recovery.py@@ -28,8 +28,8 @@ from agent.message_sanitization import ()from agent.thinking_timeout_guidance import build_thinking_timeout_guidance, is_thinking_timeoutfrom agent.turn_failure_copy import (- CONTENT_POLICY_NEXT_STEPS, content_policy_copy, exhausted_copy, nonretryable_copy, provider_label_for,- site_copy, stamp_failure,+ CONTENT_POLICY_NEXT_STEPS, content_policy_copy, exhausted_copy, limit_reset_copy, nonretryable_copy,+ provider_label_for, site_copy, stamp_failure,)from agent.turn_retry_state import TurnRetryStatefrom hermes_constants import display_hermes_home@@ -664,6 +664,28 @@ def _failed_turn_result(final_response: str, messages: Any, api_call_count: int,}+def limit_reset_epoch(agent: Any, api_error: Exception) -> Optional[float]:+ """Epoch seconds when the provider says its limit lifts (Retry-After header, ``resets_at`` /+ ``retry_after`` body fields, "try again in N" text) — the same datum the backoff honours."""+ from agent.credential_pool import _parse_absolute_timestamp++ try:+ return _parse_absolute_timestamp(agent._extract_api_error_context(api_error).get("reset_at"))+ except Exception: # advisory only — never break the error path+ return None+++def _stamp_limit_reset(result: Dict[str, Any], agent: Any, api_error: Exception) -> None:+ """``failure_resets_at`` for structured clients (Desktop card: "Limit resets at HH:mm") and the+ same sentence appended to the chat text every plain surface (CLI/TUI/gateway) renders (#98852)."""+ resets_at = limit_reset_epoch(agent, api_error)+ if resets_at is None:+ return+ result["failure_resets_at"] = resets_at+ if line := limit_reset_copy(resets_at):+ result["final_response"] = f"{result['final_response']}\n\n{line}"++def _print_nonretryable_auth_guidance(agent: Any, classified: Any, *, status_code: Optional[int], provider: Any, base_url: Any, model: Any,) -> None:@@ -909,6 +931,7 @@ def nonretryable_client_error_result("failure_reason": classified.reason.value,"failure_retryable": bool(classified.retryable),})+ _stamp_limit_reset(result, agent, api_error)if _welcome_hint and (_kind := _welcome_surface_kind(classified)):# The card form: the desktop renders the sign-in as a button, so no "To sign in" tail._stamp_free_tier(result, _kind,@@ -1042,6 +1065,7 @@ def max_retries_exhausted_result(# Present only for billing walls: (provider, billing_url, is_nous, message)."billing_block": _billing_block,})+ _stamp_limit_reset(result, agent, api_error)if _free_tier_kind:_stamp_free_tier(result, _free_tier_kind, (_welcome_tier_guidance(classified, model=model, in_chat=True, door=False)diff --git a/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx b/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsxindex b84405ce012..72dbb5d8601 100644--- a/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx@@ -34,7 +34,13 @@ 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 { errorRecoveryPlan, type ErrorSurface, formatErrorDiagnostics, isOAuthReauthSurface } from '@/lib/error-surface'+import {+ errorRecoveryPlan,+ type ErrorSurface,+ formatErrorDiagnostics,+ formatLimitReset,+ isOAuthReauthSurface+} from '@/lib/error-surface'import { errorCardText } from '@/lib/error-surface-copy'import { triggerHaptic } from '@/lib/haptics'import {@@ -741,6 +747,9 @@ const ErrorRecoveryActions: FC = () => {}, [])const localFolders = Boolean(window.hermesDesktop?.logsRoot)+ // The provider's own reset moment (429 Retry-After / resets_at), so the user knows WHEN+ // Retry will work instead of guessing (#98852). Informational only: no automatic retry.+ const limitReset = formatLimitReset(surface?.resetsAt)return (<div className="flex flex-wrap items-center gap-1.5">@@ -788,6 +797,11 @@ const ErrorRecoveryActions: FC = () => {</button></ActionBarPrimitive.Reload>)}+ {plan.retry && limitReset && (+ <span className="px-1 text-xs text-muted-foreground" data-testid="error-limit-reset">+ {copy.errorLimitResets(limitReset)}+ </span>+ )}{plan.switchProvider && inRouter && (<SettingsLinkAction label={copy.errorSwitchProvider} to={`${SETTINGS_ROUTE}?tab=config:model`} />)}diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.tsindex bb826de0c80..57b1667bda1 100644--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@ -2871,6 +2871,7 @@ export const ar = defineLocale({streaming: 'خطأ في اتصال البث'},errorRetry: 'إعادة المحاولة',+ errorLimitResets: time => `يُعاد ضبط الحد عند ${time}`,errorStartNewSession: 'بدء جلسة جديدة',errorSwitchProvider: 'تبديل المزوّد',errorSignInAgain: provider => `تسجيل الدخول إلى ${provider} مجدداً`,diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 2b9922704c3..275df2ead7e 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -4156,6 +4156,7 @@ export const en: Translations = {errorGenericProvider: 'The AI service',errorToastTitle: "Hermes couldn't finish the reply",errorRetry: 'Retry',+ errorLimitResets: time => `Limit resets at ${time}`,errorStartNewSession: 'Start new session',errorSwitchProvider: 'Switch provider',errorChooseModel: 'Choose a model',diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.tsindex 8f34f3d4ea2..ca8701c90ed 100644--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@ -3338,6 +3338,7 @@ export const ja = defineLocale({streaming: 'ストリーミング接続のエラー'},errorRetry: '再試行',+ errorLimitResets: time => `制限は ${time} にリセットされます`,errorStartNewSession: '新しいセッションを開始',errorSwitchProvider: 'プロバイダーを切り替え',errorSignInAgain: provider => `${provider} に再度サインイン`,diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex 5ef1f54d12d..7cd6ea4d0f6 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -3547,6 +3547,7 @@ export interface Translations {/** Global toast title for a mid-turn gateway `error` event. */errorToastTitle: stringerrorRetry: string+ errorLimitResets: (time: string) => string/** Escape hatch when Retry would only reproduce SESSION_NOT_OWNED (#106217). */errorStartNewSession: stringerrorSwitchProvider: stringdiff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.tsindex 7d007222d5c..c8df286d8e0 100644--- a/apps/desktop/src/i18n/zh-hant.ts+++ b/apps/desktop/src/i18n/zh-hant.ts@@ -3293,6 +3293,7 @@ export const zhHant = defineLocale({streaming: '串流連線錯誤'},errorRetry: '重試',+ errorLimitResets: time => `限額將於 ${time} 重設`,errorStartNewSession: '開始新工作階段',errorSwitchProvider: '切換服務商',errorSignInAgain: provider => `重新登入 ${provider}`,diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex 76c33367243..162d5c3da20 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -4080,6 +4080,7 @@ export const zh = defineLocale({streaming: '流式连接错误'},errorRetry: '重试',+ errorLimitResets: time => `限额将于 ${time} 重置`,errorStartNewSession: '开始新会话',errorSwitchProvider: '切换服务商',errorSignInAgain: provider => `重新登录 ${provider}`,diff --git a/apps/desktop/src/lib/error-surface.test.ts b/apps/desktop/src/lib/error-surface.test.tsindex 9bab5937b7a..c5aee5dba0c 100644--- a/apps/desktop/src/lib/error-surface.test.ts+++ b/apps/desktop/src/lib/error-surface.test.ts@@ -2,7 +2,14 @@ import { describe, expect, it } from 'vitest'import { en } from '@/i18n/en'-import { ERROR_CODE_KEYS, errorRecoveryPlan, type ErrorSurface, formatErrorDiagnostics, parseErrorSurface } from './error-surface'+import {+ ERROR_CODE_KEYS,+ errorRecoveryPlan,+ type ErrorSurface,+ formatErrorDiagnostics,+ formatLimitReset,+ parseErrorSurface+} from './error-surface'import { errorCardText } from './error-surface-copy'describe('parseErrorSurface', () => {@@ -178,3 +185,30 @@ describe('free-tier refusals', () => {}})})++describe('limit reset (#98852)', () => {+ it('parses resets_at and renders "HH:mm (in Nh MMm)" while the reset is ahead', () => {+ const now = Date.UTC(2026, 0, 1, 12, 0, 0)+ const resetsAt = now / 1000 + 3600 + 5 * 60++ const surface = parseErrorSurface({ layer: 'provider', code: 'rate_limit', retryable: true, resets_at: resetsAt })++ expect(surface?.resetsAt).toBe(resetsAt)++ const at = new Date(resetsAt * 1000)+ const clock = `${String(at.getHours()).padStart(2, '0')}:${String(at.getMinutes()).padStart(2, '0')}`++ expect(formatLimitReset(surface?.resetsAt, now)).toBe(`${clock} (in 1h 05m)`)+ expect(en.assistant.thread.errorLimitResets(`${clock} (in 1h 05m)`)).toContain(clock)+ expect(formatErrorDiagnostics({ errorText: 'x', surface })).toContain('resets_at: ')+ })++ it('shows nothing once the reset has passed or when the backend sent none', () => {+ const now = Date.now()++ expect(formatLimitReset(now / 1000 - 60, now)).toBeNull()+ expect(formatLimitReset(undefined, now)).toBeNull()+ expect(parseErrorSurface({ layer: 'provider', code: 'rate_limit', retryable: true })?.resetsAt).toBeUndefined()+ expect(parseErrorSurface({ layer: 'provider', code: 'rate_limit', retryable: true, resets_at: 'soon' })?.resetsAt).toBeUndefined()+ })+})diff --git a/apps/desktop/src/lib/error-surface.ts b/apps/desktop/src/lib/error-surface.tsindex 189f29e642f..3ac1e2783a5 100644--- a/apps/desktop/src/lib/error-surface.ts+++ b/apps/desktop/src/lib/error-surface.ts@@ -84,6 +84,10 @@ export interface ErrorSurface {/** Free-tier codes: the backend's own plain sentence for this failure (it* names the wait, the model, the way forward). Shown as the card body. */message?: string+ /** Epoch seconds when the provider said its limit lifts (Retry-After header /+ * `resets_at` body field on a 429). Rendered as "Limit resets at HH:mm" next+ * to Retry. Absent when the provider named no reset or on older backends. */+ resetsAt?: number}/** Validate a wire payload into an ErrorSurface, or null when absent/garbled. */@@ -101,6 +105,7 @@ export function parseErrorSurface(value: unknown): ErrorSurface | null {model?: unknownprovider?: unknownprovider_label?: unknown+ resets_at?: unknownretryable?: unknown}@@ -119,10 +124,35 @@ export function parseErrorSurface(value: unknown): ErrorSurface | null {...(raw.auth_kind === 'oauth' || raw.auth_kind === 'api_key' ? { authKind: raw.auth_kind } : {}),...(typeof raw.provider_label === 'string' && raw.provider_label ? { providerLabel: raw.provider_label } : {}),...(typeof raw.api_key_env === 'string' && raw.api_key_env ? { apiKeyEnv: raw.api_key_env } : {}),- ...(typeof raw.message === 'string' && raw.message.trim() ? { message: raw.message.trim() } : {})+ ...(typeof raw.message === 'string' && raw.message.trim() ? { message: raw.message.trim() } : {}),+ ...(typeof raw.resets_at === 'number' && Number.isFinite(raw.resets_at) && raw.resets_at > 0+ ? { resetsAt: raw.resets_at }+ : {})}}+/** "HH:mm (in 1h 05m)" for a provider reset moment, or null once it has passed+ * (a Retry then simply works, so the hint disappears). `now` is injectable for tests. */+export function formatLimitReset(resetsAt: number | undefined, now: number = Date.now()): null | string {+ if (typeof resetsAt !== 'number' || !Number.isFinite(resetsAt)) {+ return null+ }++ const remainingMinutes = Math.ceil((resetsAt * 1000 - now) / 60_000)++ if (remainingMinutes <= 0) {+ return null+ }++ const at = new Date(resetsAt * 1000)+ const clock = `${String(at.getHours()).padStart(2, '0')}:${String(at.getMinutes()).padStart(2, '0')}`+ const hours = Math.floor(remainingMinutes / 60)+ const minutes = remainingMinutes % 60+ const wait = hours > 0 ? `${hours}h ${String(minutes).padStart(2, '0')}m` : `${minutes}m`++ return `${clock} (in ${wait})`+}+/** True when the Nous free tier refused or could not serve the turn: the way* forward is the free sign-in (or another provider), never an OAuth re-login. */export function isFreeTierSurface(surface: ErrorSurface | null | undefined): boolean {@@ -249,6 +279,7 @@ export function formatErrorDiagnostics(input: {input.surface ? `layer: ${input.surface.layer}` : null,input.surface ? `code: ${input.surface.code}` : null,input.surface ? `retryable: ${input.surface.retryable}` : null,+ input.surface?.resetsAt ? `resets_at: ${new Date(input.surface.resetsAt * 1000).toISOString()}` : null,provider ? `provider: ${provider}` : null,model ? `model: ${model}` : null,input.appVersion ? `app: ${input.appVersion}` : null,diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex b02d8f7428f..3f28a0dce45 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -3907,13 +3907,14 @@ export interface BillingBlock {message: stringunverified?: boolean | null}-/** ``agent/error_surface.py::_surface`` — advisory {layer, code, retryable} (+ identity, + auth hint). */+/** ``agent/error_surface.py::_surface`` — advisory {layer, code, retryable} (+ identity, + auth hint, + ``resets_at`` epoch seconds when the provider named when its limit lifts). */export interface ErrorSurface {layer: stringcode: stringretryable: booleanprovider?: string | nullmodel?: string | null+ resets_at?: number | null[key: string]: unknown}/** ``server._status_update`` and the direct emitters (goal / loop / heartbeat / process). */diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 2ec97f8dcfe..cbf74183c1c 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -10366,7 +10366,7 @@},"ErrorSurface": {"additionalProperties": true,- "description": "``agent/error_surface.py::_surface`` \u2014 advisory {layer, code, retryable} (+ identity, + auth hint).",+ "description": "``agent/error_surface.py::_surface`` \u2014 advisory {layer, code, retryable} (+ identity, + auth hint,\n+ ``resets_at`` epoch seconds when the provider named when its limit lifts).","properties": {"layer": {"title": "Layer",@@ -10403,6 +10403,18 @@],"default": null,"title": "Model"+ },+ "resets_at": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Resets At"}},"required": [diff --git a/tests/agent/test_error_surface.py b/tests/agent/test_error_surface.pyindex 9a4c12bde62..2ef491dfa70 100644--- a/tests/agent/test_error_surface.py+++ b/tests/agent/test_error_surface.py@@ -258,3 +258,32 @@ def test_free_tier_kinds_say_whether_a_later_send_can_succeed(kind, retryable):def test_a_free_tier_block_without_a_kind_is_ignored():surface = build_error_surface_from_result(_failed_result("auth_permanent", free_tier={}), provider="nous")assert surface["code"] == "auth_permanent" and surface["layer"] == LAYER_AUTH+++def test_rate_limit_reset_rides_the_surface():+ """#98852: a 429 whose Retry-After (or ``resets_at`` body field) names when the limit lifts+ surfaces that moment as ``resets_at`` (epoch seconds) so the card can say "Limit resets at+ HH:mm" next to Retry; a 429 without any reset signal carries no ``resets_at``."""+ import time++ import httpx+ import openai++ def _rate_limit(headers: dict, body: dict):+ request = httpx.Request("POST", "http://fake/v1/chat/completions")+ response = httpx.Response(429, headers=headers, request=request)+ return openai.RateLimitError("HTTP 429: The usage limit has been reached", response=response, body=body)++ before = time.time()+ exc = _rate_limit({"Retry-After": "3600"},+ {"error": {"message": "The usage limit has been reached", "type": "usage_limit_reached"}})+ surface = build_error_surface_from_exception(exc, provider="openai", model="gpt-5")+ assert surface["code"] == "rate_limit" and surface["retryable"] is True+ assert before + 3500 <= surface["resets_at"] <= time.time() + 3600++ result = {"error": "HTTP 429: The usage limit has been reached", "failure_reason": "rate_limit",+ "failure_retryable": True, "failure_resets_at": 1_800_000_000}+ assert build_error_surface_from_result(result, provider="openai")["resets_at"] == 1_800_000_000.0++ bare = _rate_limit({}, {"error": {"message": "Rate limit exceeded"}})+ assert "resets_at" not in build_error_surface_from_exception(bare, provider="openai", model="gpt-5")diff --git a/tui_gateway/contracts/events.py b/tui_gateway/contracts/events.pyindex 85c8b16881e..81b71d504ef 100644--- a/tui_gateway/contracts/events.py+++ b/tui_gateway/contracts/events.py@@ -143,13 +143,15 @@ class TurnStatus(WireEnum):class ErrorSurface(Payload):- """``agent/error_surface.py::_surface`` — advisory {layer, code, retryable} (+ identity, + auth hint)."""+ """``agent/error_surface.py::_surface`` — advisory {layer, code, retryable} (+ identity, + auth hint,+ + ``resets_at`` epoch seconds when the provider named when its limit lifts)."""layer: strcode: strretryable: boolprovider: str | None = Nonemodel: str | None = None+ resets_at: float | None = Nonemodel_config = Payload.model_config | {"extra": "allow"}diff --git a/website/docs/user-guide/desktop.md b/website/docs/user-guide/desktop.mdindex 077dad71ff8..1e3b11ba8cc 100644--- a/website/docs/user-guide/desktop.md+++ b/website/docs/user-guide/desktop.md@@ -533,6 +533,11 @@ generic error toast. The card offers recovery actions matched to the failure:- **Retry** — re-runs the failed turn in place (hidden when retrying woulddeterministically reproduce the failure, e.g. a content-policy rejection).+ When a rate-limit or usage-limit response names when the limit lifts+ (`Retry-After` header or a `resets_at` field), the card shows **Limit resets+ at HH:mm (in 1h 05m)** next to Retry so you know when a retry will work; the+ CLI/TUI print the same line under the error. The hint is informational — the+ turn is not retried automatically.- **Switch provider** — jumps to Settings → Models for provider, endpoint,auth, and billing failures.- **Open logs** — opens `HERMES_HOME/logs` in your file manager. On a remote