Skip to content

The agent that grows with you

feat(desktop): 429 usage-limit card can schedule one retry for when the limit resets

teknium16e1f5c971393
diff --git a/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsx b/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsx
index 20c7da63822..d1b5ee8176e 100644
--- a/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsx
@@ -5,7 +5,7 @@
// AssistantMessage's action bar hide the button entirely when no handler is
// supplied, matching how onDismissError/onRestoreToMessage already behave.
import { AssistantRuntimeProvider, type ThreadMessage, useExternalStoreRuntime } from '@assistant-ui/react'
-import { cleanup, render, screen, waitFor } from '@testing-library/react'
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { MemoryRouter, useLocation } from 'react-router'
import { afterEach, describe, expect, it, vi } from 'vitest'
@@ -170,15 +170,18 @@ function LocationProbe() {
function Harness({
assistant = assistantMessage(),
- onBranchInNewChat
+ onBranchInNewChat,
+ onReload
}: {
assistant?: ThreadMessage
onBranchInNewChat?: (messageId: string) => void
+ onReload?: () => Promise<void>
}) {
const runtime = useExternalStoreRuntime<ThreadMessage>({
messages: [userMessage(), assistant],
isRunning: false,
- onNew: async () => {}
+ onNew: async () => {},
+ ...(onReload ? { onReload } : {})
})
return (
@@ -305,6 +308,66 @@ describe('code-keyed error card copy and actions', () => {
})
})
+describe('scheduled retry at the usage-limit reset (#98852)', () => {
+ const rateLimited = (resetsAt: number) =>
+ failedMessage(
+ { code: 'rate_limit', layer: 'provider', provider: 'openai', resetsAt, retryable: true },
+ 'HTTP 429: {"error":{"message":"Rate limit reached"}}'
+ )
+
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ it('fires the same reload as Retry exactly once, at resets_at and not before', async () => {
+ const onReload = vi.fn(async () => {})
+ const resetsAt = Math.floor(Date.now() / 1000) + 600
+
+ render(<Harness assistant={rateLimited(resetsAt)} onReload={onReload} />)
+
+ const arm = await screen.findByRole('button', { name: /^Retry when the limit resets \(\d\d:\d\d\)$/ })
+
+ vi.useFakeTimers()
+ fireEvent.click(arm)
+
+ expect(screen.getByTestId('error-retry-scheduled').textContent).toMatch(/Retrying at \d\d:\d\d — in \d+m \d\ds/)
+ expect(screen.queryByRole('button', { name: /^Retry when the limit resets/ })).toBeNull()
+
+ await act(async () => vi.advanceTimersByTime(resetsAt * 1000 - Date.now() - 1_000))
+ expect(onReload).not.toHaveBeenCalled()
+
+ await act(async () => vi.advanceTimersByTime(1_000))
+ expect(onReload).toHaveBeenCalledTimes(1)
+
+ await act(async () => vi.advanceTimersByTime(3_600_000))
+ expect(onReload).toHaveBeenCalledTimes(1)
+ })
+
+ it('never fires after Cancel or unmount, and hides the button once the reset has passed', async () => {
+ const onReload = vi.fn(async () => {})
+ const resetsAt = Math.floor(Date.now() / 1000) + 600
+
+ const view = render(<Harness assistant={rateLimited(resetsAt)} onReload={onReload} />)
+ const armName = /^Retry when the limit resets/
+
+ fireEvent.click(await screen.findByRole('button', { name: armName }))
+ vi.useFakeTimers()
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
+ expect(screen.queryByTestId('error-retry-scheduled')).toBeNull()
+
+ fireEvent.click(screen.getByRole('button', { name: armName }))
+ view.unmount()
+
+ await act(async () => vi.advanceTimersByTime(3_600_000))
+ expect(onReload).not.toHaveBeenCalled()
+ vi.useRealTimers()
+
+ render(<Harness assistant={rateLimited(Math.floor(Date.now() / 1000) - 60)} onReload={onReload} />)
+ expect(await screen.findByRole('button', { name: 'Retry' })).toBeTruthy()
+ expect(screen.queryByRole('button', { name: armName })).toBeNull()
+ })
+})
+
describe('rejected API key recovery', () => {
it('names the key as the problem and deep-links Settings → Keys to that env var', async () => {
render(
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 c1fb350e84c..75773f88e9b 100644
--- a/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx
+++ b/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx
@@ -3,12 +3,13 @@ import {
BranchPickerPrimitive,
ErrorPrimitive,
MessagePrimitive,
+ useAui,
useAuiState,
useMessageRuntime,
useThreadRuntime
} from '@assistant-ui/react'
import { useStore } from '@nanostores/react'
-import { type FC, type ReactNode, useCallback, useContext, useMemo, useState } from 'react'
+import { type FC, type ReactNode, useCallback, useContext, useEffect, useMemo, useState } from 'react'
import { useInRouterContext, useNavigate } from 'react-router'
import { requestModelMenuToggle } from '@/app/chat/composer/focus'
@@ -38,9 +39,12 @@ import { useI18n } from '@/i18n'
import {
errorRecoveryPlan,
type ErrorSurface,
+ formatCountdown,
formatErrorDiagnostics,
formatLimitReset,
- isOAuthReauthSurface
+ formatResetClock,
+ isOAuthReauthSurface,
+ scheduledRetryDelayMs
} from '@/lib/error-surface'
import { errorCardText } from '@/lib/error-surface-copy'
import { triggerHaptic } from '@/lib/haptics'
@@ -674,6 +678,86 @@ const CompressConversationAction: FC<{ label: string }> = ({ label }) => {
)
}
+// One client-side retry of THIS turn at the provider's own reset moment (#98852,
+// option B): arm → visible countdown + Cancel → fires `message().reload()` — the
+// exact call behind the Retry button — exactly once. Nothing persists: closing
+// the app, switching sessions or unmounting the card drops the timer, and a
+// retry that 429s again just shows the card (and this button) again.
+const ScheduledRetryAction: FC<{ resetsAt: number }> = ({ resetsAt }) => {
+ const { t } = useI18n()
+ const copy = t.assistant.thread
+ const aui = useAui()
+
+ // Armed once the user clicks; `fireAt` is the wall-clock ms the timer targets.
+ const [fireAt, setFireAt] = useState<null | number>(null)
+ const [now, setNow] = useState(() => Date.now())
+
+ // A manual Retry, a new message, or a later turn all make firing wrong: the
+ // reload would regenerate a message that is no longer the tail. Same gate
+ // `useActionBarReload` applies to the Retry button itself.
+ const stale = useAuiState(s => s.thread.isRunning || s.thread.isDisabled || !s.message.isLast)
+
+ useEffect(() => {
+ if (fireAt === null || stale) {
+ return
+ }
+
+ const timer = window.setTimeout(
+ () => {
+ setFireAt(null)
+ aui.message().reload()
+ },
+ Math.max(0, fireAt - Date.now())
+ )
+ const tick = window.setInterval(() => setNow(Date.now()), 1000)
+
+ return () => {
+ window.clearTimeout(timer)
+ window.clearInterval(tick)
+ }
+ }, [aui, fireAt, stale])
+
+ useEffect(() => {
+ if (stale) {
+ setFireAt(null)
+ }
+ }, [stale])
+
+ const delay = scheduledRetryDelayMs(resetsAt, now)
+
+ if (fireAt !== null) {
+ return (
+ <span className="inline-flex items-center gap-1.5" data-testid="error-retry-scheduled">
+ <span className="px-1 text-xs text-muted-foreground">
+ {copy.errorRetryScheduled(formatResetClock(resetsAt), formatCountdown(fireAt - now))}
+ </span>
+ <button className="aui-error-action" onClick={() => setFireAt(null)} type="button">
+ {copy.errorRetryScheduledCancel}
+ </button>
+ </span>
+ )
+ }
+
+ if (delay === null || stale) {
+ return null
+ }
+
+ return (
+ <button
+ className="aui-error-action"
+ onClick={() => {
+ triggerHaptic('submit')
+ setNow(Date.now())
+ setFireAt(resetsAt * 1000)
+ }}
+ type="button"
+ >
+ <RefreshCwIcon className="size-3" />
+ {copy.errorRetryAtReset(formatResetClock(resetsAt))}
+ </button>
+ )
+}
+
const ErrorRecoveryActions: FC = () => {
const { t } = useI18n()
const copy = t.assistant.thread
@@ -829,6 +913,7 @@ const ErrorRecoveryActions: FC = () => {
{copy.errorLimitResets(limitReset)}
</span>
)}
+ {plan.retry && surface?.resetsAt !== undefined && <ScheduledRetryAction resetsAt={surface.resetsAt} />}
{plan.switchProvider && inRouter && <SwitchProviderAction label={copy.errorSwitchProvider} />}
{localFolders && (
<button className="aui-error-action" onClick={() => void openLogs()} type="button">
diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.ts
index 3683da78c09..b231af3c61c 100644
--- a/apps/desktop/src/i18n/ar.ts
+++ b/apps/desktop/src/i18n/ar.ts
@@ -2874,6 +2874,9 @@ export const ar = defineLocale({
},
errorRetry: 'إعادة المحاولة',
errorLimitResets: time => `يُعاد ضبط الحد عند ${time}`,
+ errorRetryAtReset: time => `إعادة المحاولة عند إعادة ضبط الحد (${time})`,
+ errorRetryScheduled: (time, wait) => `ستتم إعادة المحاولة عند ${time} — بعد ${wait}`,
+ errorRetryScheduledCancel: 'إلغاء',
errorStartNewSession: 'بدء جلسة جديدة',
errorSwitchProvider: 'تبديل المزوّد',
errorSignInAgain: provider => `تسجيل الدخول إلى ${provider} مجدداً`,
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index be746cba1bf..892510ea1b0 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -4162,6 +4162,9 @@ export const en: Translations = {
errorToastTitle: "Hermes couldn't finish the reply",
errorRetry: 'Retry',
errorLimitResets: time => `Limit resets at ${time}`,
+ errorRetryAtReset: time => `Retry when the limit resets (${time})`,
+ errorRetryScheduled: (time, wait) => `Retrying at ${time} — in ${wait}`,
+ errorRetryScheduledCancel: 'Cancel',
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.ts
index baada064dd2..420b757692a 100644
--- a/apps/desktop/src/i18n/ja.ts
+++ b/apps/desktop/src/i18n/ja.ts
@@ -3349,6 +3349,9 @@ export const ja = defineLocale({
},
errorRetry: '再試行',
errorLimitResets: time => `制限は ${time} にリセットされます`,
+ errorRetryAtReset: time => `制限のリセット時に再試行(${time})`,
+ errorRetryScheduled: (time, wait) => `${time} に再試行 — 残り ${wait}`,
+ errorRetryScheduledCancel: 'キャンセル',
errorStartNewSession: '新しいセッションを開始',
errorSwitchProvider: 'プロバイダーを切り替え',
errorSignInAgain: provider => `${provider} に再度サインイン`,
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index b2b5c2c2dea..b8ca0c6cf76 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -3548,6 +3548,11 @@ export interface Translations {
errorToastTitle: string
errorRetry: string
errorLimitResets: (time: string) => string
+ /** Arms ONE client-side retry of this turn at the 429's `resets_at` (#98852). */
+ errorRetryAtReset: (time: string) => string
+ /** Countdown shown while that retry is armed; `wait` is "12m 03s". */
+ errorRetryScheduled: (time: string, wait: string) => string
+ errorRetryScheduledCancel: string
/** Escape hatch when Retry would only reproduce SESSION_NOT_OWNED (#106217). */
errorStartNewSession: string
errorSwitchProvider: string
diff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.ts
index 286635f6722..5ee1164a5b8 100644
--- a/apps/desktop/src/i18n/zh-hant.ts
+++ b/apps/desktop/src/i18n/zh-hant.ts
@@ -3304,6 +3304,9 @@ export const zhHant = defineLocale({
},
errorRetry: '重試',
errorLimitResets: time => `限額將於 ${time} 重設`,
+ errorRetryAtReset: time => `限額重設後重試(${time})`,
+ errorRetryScheduled: (time, wait) => `將於 ${time} 重試 — 還剩 ${wait}`,
+ errorRetryScheduledCancel: '取消',
errorStartNewSession: '開始新工作階段',
errorSwitchProvider: '切換服務商',
errorSignInAgain: provider => `重新登入 ${provider}`,
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index b4916c3c364..c24defc3f32 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -4091,6 +4091,9 @@ export const zh = defineLocale({
},
errorRetry: '重试',
errorLimitResets: time => `限额将于 ${time} 重置`,
+ errorRetryAtReset: time => `限额重置后重试(${time})`,
+ errorRetryScheduled: (time, wait) => `将于 ${time} 重试 — 还剩 ${wait}`,
+ errorRetryScheduledCancel: '取消',
errorStartNewSession: '开始新会话',
errorSwitchProvider: '切换服务商',
errorSignInAgain: provider => `重新登录 ${provider}`,
diff --git a/apps/desktop/src/lib/error-surface.ts b/apps/desktop/src/lib/error-surface.ts
index 422d6f58b2c..5e67a570af8 100644
--- a/apps/desktop/src/lib/error-surface.ts
+++ b/apps/desktop/src/lib/error-surface.ts
@@ -134,6 +134,13 @@ export function parseErrorSurface(value: unknown): ErrorSurface | null {
}
}
+/** "HH:mm" for a provider reset moment, in the user's local clock. */
+export function formatResetClock(resetsAt: number): string {
+ const at = new Date(resetsAt * 1000)
+
+ return `${String(at.getHours()).padStart(2, '0')}:${String(at.getMinutes()).padStart(2, '0')}`
+}
+
/** "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 {
@@ -147,13 +154,39 @@ export function formatLimitReset(resetsAt: number | undefined, now: number = Dat
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})`
+ return `${formatResetClock(resetsAt)} (in ${wait})`
+}
+
+/** Browsers clamp `setTimeout` delays to a signed 32-bit millisecond count and
+ * fire anything larger immediately — a reset that far out gets no schedule
+ * button at all rather than an instant (and pointless) retry. */
+const MAX_TIMER_DELAY_MS = 2 ** 31 - 1
+
+/** Milliseconds until the card may fire its one scheduled retry, or null when
+ * the reset already passed (Retry works now) or is too far out to time. */
+export function scheduledRetryDelayMs(resetsAt: number | undefined, now: number = Date.now()): null | number {
+ if (typeof resetsAt !== 'number' || !Number.isFinite(resetsAt)) {
+ return null
+ }
+
+ const delay = resetsAt * 1000 - now
+
+ return delay > 0 && delay <= MAX_TIMER_DELAY_MS ? delay : null
+}
+
+/** "12m 03s" / "1h 05m 03s" for the live countdown on a scheduled retry. */
+export function formatCountdown(remainingMs: number): string {
+ const totalSeconds = Math.max(0, Math.ceil(remainingMs / 1000))
+ const hours = Math.floor(totalSeconds / 3600)
+ const minutes = Math.floor((totalSeconds % 3600) / 60)
+ const seconds = totalSeconds % 60
+ const tail = `${String(minutes).padStart(2, '0')}m ${String(seconds).padStart(2, '0')}s`
+
+ return hours > 0 ? `${hours}h ${tail}` : tail.replace(/^0/, '')
}
/** True when the Nous free tier refused or could not serve the turn: the way
diff --git a/website/docs/user-guide/desktop.md b/website/docs/user-guide/desktop.md
index c39597b06b5..7b7fb00194a 100644
--- a/website/docs/user-guide/desktop.md
+++ b/website/docs/user-guide/desktop.md
@@ -541,8 +541,12 @@ generic error toast. The card offers recovery actions matched to the failure:
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.
+ CLI/TUI print the same line under the error. The hint itself is
+ informational, but the card also offers **Retry when the limit resets
+ (HH:mm)**: click it and the app retries that turn once at the reset time
+ with a live countdown and a **Cancel** control. The schedule lives only in
+ the open window — switching sessions, sending another message, or closing
+ the app drops it, and nothing retries unattended.
- **Switch provider** — for provider, endpoint, auth, and billing failures,
opens the composer's live model menu so you can move **this chat** to another
provider/model right away (Settings → Models only changes the default for new