Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(agent): a throttled run waits the window out instead of dying inside it

Davidcea1adf6adb2
diff --git a/src/api/providers/openai-provider.ts b/src/api/providers/openai-provider.ts
index a1362cbf..78010e94 100644
--- a/src/api/providers/openai-provider.ts
+++ b/src/api/providers/openai-provider.ts
@@ -17,6 +17,7 @@ import { ProviderError } from './types'
import { parseSSEStream } from '../sse'
import { repairJson } from '../../lib/tool-call-repair'
import { signalCreditsExhausted } from '../../lib/credits-exhausted'
+import { parseRetryAfter } from '../../lib/http-status'
import { localFetch, localFetchStream, isPrivateOrLanHost, isDirectFetchAllowed, hostnameOf, ensureProxyAllowsHost } from '../backend'
import { ensureBuiltinEngineAlive, explainDeadEngine } from '../builtin-ensure'
@@ -1059,6 +1060,6 @@ export class OpenAIProvider implements ProviderClient {
"no need to restart LU."
}
- return new ProviderError(message, 'openai', code, res.status)
+ return new ProviderError(message, 'openai', code, res.status, undefined, parseRetryAfter(res))
}
}
diff --git a/src/api/providers/types.ts b/src/api/providers/types.ts
index 02333584..62af8a5a 100644
--- a/src/api/providers/types.ts
+++ b/src/api/providers/types.ts
@@ -234,6 +234,14 @@ export class ProviderError extends Error {
* state. See lib/sync-ollama-health.ts.
*/
readonly model?: string
+ /**
+ * How long the server said to wait, in milliseconds, from a `retry-after`
+ * header. Only a throttle sends one. Without it the retry site can only
+ * guess, and its guess (1.5 s then 3 s) is far shorter than the window a
+ * fixed-window limiter actually holds, so every attempt lands inside the
+ * same refusal. See lib/http-status retryDelayMs.
+ */
+ readonly retryAfterMs?: number
constructor(
message: string,
@@ -241,6 +249,7 @@ export class ProviderError extends Error {
code?: string,
status?: number,
model?: string,
+ retryAfterMs?: number,
) {
super(message)
this.name = 'ProviderError'
@@ -248,5 +257,6 @@ export class ProviderError extends Error {
this.code = code
this.status = status
this.model = model
+ this.retryAfterMs = retryAfterMs
}
}
diff --git a/src/hooks/__tests__/throttled-run-waits-it-out.test.ts b/src/hooks/__tests__/throttled-run-waits-it-out.test.ts
new file mode 100644
index 00000000..edfd1c39
--- /dev/null
+++ b/src/hooks/__tests__/throttled-run-waits-it-out.test.ts
@@ -0,0 +1,77 @@
+/**
+ * The wiring for the retry-after fix: the header has to be read where the
+ * error is built, honoured where the retry sleeps, and explained where the run
+ * gives up.
+ *
+ * Review 2026-08-14. Before this, all three were missing: parseError dropped
+ * the header, both retry sites slept on a hard-coded 1500 * attempt, and the
+ * outer catch had no 429 branch, so a burst-limited run ended on the generic
+ * "Agent error: too many requests".
+ *
+ * Run: npx vitest run src/hooks/__tests__/throttled-run-waits-it-out.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { fileURLToPath } from 'node:url'
+import { dirname, resolve } from 'node:path'
+
+const here = dirname(fileURLToPath(import.meta.url))
+const read = (rel: string) => readFileSync(resolve(here, rel), 'utf8')
+const agent = read('../useAgentChat.ts')
+const provider = read('../../api/providers/openai-provider.ts')
+const types = read('../../api/providers/types.ts')
+
+describe('the header survives the trip to the retry site', () => {
+ it('parseError puts it on the error it builds', () => {
+ expect(provider).toContain('parseRetryAfter(res)')
+ expect(provider).toContain("import { parseRetryAfter } from '../../lib/http-status'")
+ })
+
+ it('the error type carries it', () => {
+ expect(types).toMatch(/readonly retryAfterMs\?: number/)
+ })
+})
+
+describe('both retry sites honour it', () => {
+ it('neither sleeps on a hard-coded ladder any more', () => {
+ const code = agent
+ .split('\n')
+ .filter((l) => !l.trim().startsWith('//') && !l.trim().startsWith('*'))
+ .join('\n')
+ expect(code).not.toContain('setTimeout(r, 1500 * connRetries)')
+ expect(agent.match(/const wait = retryDelayMs\(thinkErr, connRetries\)/g)).toHaveLength(2)
+ expect(agent.match(/await new Promise\(\(r\) => setTimeout\(r, wait\)\)/g)).toHaveLength(2)
+ })
+
+ it('a long wait is announced, so a quiet minute does not read as a freeze', () => {
+ expect(agent).toContain('const announceWait = (err: unknown, ms: number) =>')
+ expect(agent).toContain('Rate limited by the server, which asked for')
+ // Only a wait the server asked for. The 1.5 s connection blip gets no line.
+ expect(agent).toContain("if (typeof asked !== 'number' || ms < 3000) return")
+ expect(agent.match(/announceWait\(thinkErr, wait\)/g)).toHaveLength(2)
+ })
+})
+
+describe('and giving up says when to come back', () => {
+ it('the 429 branch sits before the generic error line', () => {
+ const branch = agent.indexOf('} else if (httpStatusOf(err) === 429) {')
+ const generic = agent.indexOf("'\\n\\nAgent error: ' + errorMsg")
+ expect(branch).toBeGreaterThan(-1)
+ expect(branch).toBeLessThan(generic)
+ expect(agent).toContain('The server is limiting how many requests this account may send')
+ })
+
+ it('but an empty wallet is judged first, it answers 429 too', () => {
+ const credits = agent.indexOf("code === 'credits_exhausted'")
+ expect(credits).toBeGreaterThan(-1)
+ expect(credits).toBeLessThan(agent.indexOf('} else if (httpStatusOf(err) === 429) {'))
+ })
+
+ it('a throttle does not kill a /loop, unlike an empty wallet', () => {
+ const branch = agent.slice(
+ agent.indexOf('} else if (httpStatusOf(err) === 429) {'),
+ agent.indexOf('} else if (/failed to fetch'),
+ )
+ expect(branch).not.toContain('loopHalt =')
+ })
+})
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 0aa3885b..ae9ca0c1 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -70,7 +70,7 @@ import { PlanStaleness, planStalenessSteer } from '../lib/plan-staleness'
import { reasoningOnlyRound, REASONING_CONTINUE_BUDGET, REASONING_CONTINUE_STEER } from '../lib/reasoning-round'
import { useTodoStore } from '../stores/todoStore'
import { platformPromptLine } from '../lib/host-platform'
-import { httpStatusOf, isTerminalModelError } from '../lib/http-status'
+import { httpStatusOf, isTerminalModelError, retryDelayMs } from '../lib/http-status'
import { CREDITS_EXHAUSTED_MESSAGE } from '../lib/credits-exhausted'
// ── Standalone memory extraction (usable outside React hooks) ──
@@ -721,6 +721,21 @@ export function useAgentChat() {
compactBudget
) as ChatMessage[]
+ // Honouring a long `retry-after` means the run goes quiet for up to a
+ // minute, and a silent gap reads as a freeze (which is exactly the
+ // complaint the credits work came from). Only a wait the SERVER asked
+ // for gets a line; the 1.5 s connection-blip ladder is not worth one.
+ const announceWait = (err: unknown, ms: number) => {
+ const asked = (err as { retryAfterMs?: unknown } | null)?.retryAfterMs
+ if (typeof asked !== 'number' || ms < 3000) return
+ addBlock(convId!, assistantMessage.id, {
+ id: uuid(),
+ phase: 'reflection',
+ content: `Rate limited by the server, which asked for ${Math.round(ms / 1000)} seconds. Waiting, then carrying on.`,
+ timestamp: Date.now(),
+ })
+ }
+
if (strategy === 'native') {
// Show thinking indicator while model processes
const thinkingBlockId = uuid()
@@ -866,8 +881,10 @@ export function useAgentChat() {
const transient = thinkErr?.name !== 'AbortError' && !isTerminalModelError(thinkErr)
if (transient && connRetries < 2) {
connRetries++
- log.warn('agent.model_call_retry', { attempt: connRetries, err: String(thinkErr?.message || thinkErr) })
- await new Promise((r) => setTimeout(r, 1500 * connRetries))
+ const wait = retryDelayMs(thinkErr, connRetries)
+ log.warn('agent.model_call_retry', { attempt: connRetries, waitMs: wait, err: String(thinkErr?.message || thinkErr) })
+ announceWait(thinkErr, wait)
+ await new Promise((r) => setTimeout(r, wait))
continue
}
throw thinkErr
@@ -935,8 +952,10 @@ export function useAgentChat() {
const transient = thinkErr?.name !== 'AbortError' && !isTerminalModelError(thinkErr)
if (transient && connRetries < 2) {
connRetries++
- log.warn('agent.model_call_retry', { attempt: connRetries, provider: providerId, err: String(thinkErr?.message || thinkErr) })
- await new Promise((r) => setTimeout(r, 1500 * connRetries))
+ const wait = retryDelayMs(thinkErr, connRetries)
+ log.warn('agent.model_call_retry', { attempt: connRetries, provider: providerId, waitMs: wait, err: String(thinkErr?.message || thinkErr) })
+ announceWait(thinkErr, wait)
+ await new Promise((r) => setTimeout(r, wait))
continue
}
throw thinkErr
@@ -1796,6 +1815,22 @@ export function useAgentChat() {
(contentRef.current ? contentRef.current + '\n\n' : '') +
'Your LU Cloud session ended and could not be renewed, so the run stopped here. Sign in again in Settings, then carry on.' + planLine
)
+ } else if (httpStatusOf(err) === 429) {
+ // Reaching here means the wait above was already honoured and the
+ // window still had not cleared. "Agent error: too many requests" is
+ // true and useless; a burst guard clears on a clock, so say when.
+ // No loopHalt on purpose: a throttle passes, unlike an empty wallet,
+ // and killing a long /loop over one busy minute would be worse than
+ // letting its next round wait its turn.
+ const asked = (err as { retryAfterMs?: number })?.retryAfterMs
+ const when = typeof asked === 'number' && asked > 0
+ ? `about ${Math.ceil(asked / 1000)} seconds`
+ : 'a minute'
+ useChatStore.getState().updateMessageContent(
+ convId!, assistantMessage.id,
+ (contentRef.current ? contentRef.current + '\n\n' : '') +
+ `The server is limiting how many requests this account may send in a short window, and the run waited for it once already. Give it ${when}, then send your message again. Nothing was charged for the refused attempts.`
+ )
} else if (/failed to fetch|connection refused|connection reset|error sending request|proxy_localhost|network ?error|timed out|timeout|tcp connect|llama runner process|backend unreachable|HTTP 5\d\d/i.test(errorMsg)) {
// Connection-class failure — after the transient retries above this
// means the backend really dropped mid-run (crashed, was killed, or
diff --git a/src/lib/__tests__/retry-after.test.ts b/src/lib/__tests__/retry-after.test.ts
new file mode 100644
index 00000000..b4e7262d
--- /dev/null
+++ b/src/lib/__tests__/retry-after.test.ts
@@ -0,0 +1,78 @@
+/**
+ * A throttled run has to outlast the window that throttled it.
+ *
+ * Review 2026-08-14. isTerminalModelError deliberately leaves 429 retryable,
+ * and its docstring justifies that with the retry-after the server sends. The
+ * client never read that header: the only occurrence of the string in the
+ * whole desktop tree was the claim itself. The retry site waited 1.5 s and
+ * then 3 s, while LU Cloud's burst guard is a FIXED window (60 requests per
+ * 60 s) whose retry-after can be anything up to a full minute. Both attempts
+ * landed inside the same window that had just refused them, the loop threw
+ * after 4.5 s, and the user read "Agent error: too many requests" with nothing
+ * to do about it. The carve-out that exists to save a throttled run never
+ * saved one.
+ *
+ * Run: npx vitest run src/lib/__tests__/retry-after.test.ts
+ */
+import { describe, it, expect, vi, afterEach } from 'vitest'
+import { parseRetryAfter, retryDelayMs, MAX_RETRY_AFTER_MS } from '../http-status'
+import { ProviderError } from '../../api/providers/types'
+
+const headers = (value: string | null) => ({ headers: { get: () => value } })
+
+afterEach(() => vi.useRealTimers())
+
+describe('parseRetryAfter', () => {
+ it('reads whole seconds, which is what LU Cloud sends', () => {
+ expect(parseRetryAfter(headers('42'))).toBe(42_000)
+ expect(parseRetryAfter(headers(' 7 '))).toBe(7_000)
+ expect(parseRetryAfter(headers('0'))).toBe(0)
+ })
+
+ it('reads the HTTP-date shape too, so another provider is not ignored', () => {
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date('2026-08-14T10:00:00Z'))
+ expect(parseRetryAfter(headers('Fri, 14 Aug 2026 10:00:30 GMT'))).toBe(30_000)
+ // A date already in the past means "now", not a negative wait.
+ expect(parseRetryAfter(headers('Fri, 14 Aug 2026 09:59:00 GMT'))).toBe(0)
+ })
+
+ it('treats a missing or broken header as absent, never as zero', () => {
+ // Absent must fall back to the caller's own ladder. Returning 0 would turn
+ // a malformed header into a tight loop against the limiter.
+ for (const v of [null, '', 'soon', '-5']) {
+ expect(parseRetryAfter(headers(v))).toBeUndefined()
+ }
+ })
+})
+
+describe('retryDelayMs', () => {
+ const throttled = (ms?: number) =>
+ new ProviderError('too many requests', 'lu-cloud', 'rate_limit', 429, undefined, ms)
+
+ it('waits what the server asked for, instead of guessing far too short', () => {
+ expect(retryDelayMs(throttled(45_000), 1)).toBe(45_000)
+ // The old ladder for the same failure, for contrast.
+ expect(1500 * 1).toBeLessThan(retryDelayMs(throttled(45_000), 1))
+ })
+
+ it('keeps the old ladder when no header came', () => {
+ expect(retryDelayMs(throttled(undefined), 1)).toBe(1500)
+ expect(retryDelayMs(throttled(undefined), 2)).toBe(3000)
+ expect(retryDelayMs(new Error('Failed to fetch'), 2)).toBe(3000)
+ })
+
+ it('caps a wild number, a run must not freeze for minutes', () => {
+ expect(retryDelayMs(throttled(600_000), 1)).toBe(MAX_RETRY_AFTER_MS)
+ })
+
+ it('keeps a beat when the server says zero', () => {
+ expect(retryDelayMs(throttled(0), 1)).toBe(250)
+ })
+
+ it('ignores a nonsense value on the error', () => {
+ expect(retryDelayMs({ retryAfterMs: 'soon' }, 1)).toBe(1500)
+ expect(retryDelayMs({ retryAfterMs: Number.NaN }, 2)).toBe(3000)
+ expect(retryDelayMs({ retryAfterMs: -1 }, 1)).toBe(1500)
+ })
+})
diff --git a/src/lib/http-status.ts b/src/lib/http-status.ts
index fd12105b..3e41669b 100644
--- a/src/lib/http-status.ts
+++ b/src/lib/http-status.ts
@@ -48,6 +48,55 @@ export function httpStatusOf(err: unknown): number {
* and the provider throws `signed_out`, which IS terminal, so the dead end
* costs one backoff and then says the true thing.
*/
+/** Longest server-directed wait worth sitting through inside one run. */
+export const MAX_RETRY_AFTER_MS = 60_000
+
+/**
+ * The wait a throttling server asked for, in milliseconds, or undefined.
+ *
+ * `retry-after` comes in two shapes (RFC 9110): whole seconds, which is what
+ * LU Cloud sends, or an HTTP date. Both are read here so a provider that picks
+ * the other one still gets honoured. Anything unparseable or negative is
+ * treated as absent rather than as zero, so a broken header falls back to the
+ * caller's own backoff instead of hammering the server immediately.
+ */
+export function parseRetryAfter(res: { headers: { get(name: string): string | null } }): number | undefined {
+ const raw = res.headers.get('retry-after')
+ if (!raw) return undefined
+ const seconds = Number(raw.trim())
+ if (Number.isFinite(seconds)) return seconds >= 0 ? seconds * 1000 : undefined
+ const at = Date.parse(raw)
+ if (!Number.isFinite(at)) return undefined
+ const ms = at - Date.now()
+ return ms > 0 ? ms : 0
+}
+
+/**
+ * How long to wait before attempt number `attempt` (1-based).
+ *
+ * The server's own number wins whenever it sent one, and this is the whole
+ * point: LU Cloud's burst guard is a FIXED window (60 requests per 60 s), so
+ * `retry-after` can be anything up to a full minute, while the caller's ladder
+ * waited 1.5 s and then 3 s. Both retries therefore landed inside the very
+ * same window that had just refused them, and a throttled run died after 4.5 s
+ * with "too many requests" and no instruction. The 429 carve-out in
+ * isTerminalModelError only pays off if the wait is long enough to outlast the
+ * window it is waiting for.
+ *
+ * Capped at MAX_RETRY_AFTER_MS: a minute of silence is already a lot to ask,
+ * and beyond that the honest answer is to stop and tell the user when to come
+ * back rather than freeze the run.
+ */
+export function retryDelayMs(err: unknown, attempt: number): number {
+ const asked = (err as { retryAfterMs?: unknown } | null)?.retryAfterMs
+ if (typeof asked === 'number' && Number.isFinite(asked) && asked >= 0) {
+ // A server that says "0" means now; keep a beat so the retry is not a
+ // tight loop against a limiter that rounds down.
+ return Math.min(Math.max(asked, 250), MAX_RETRY_AFTER_MS)
+ }
+ return 1500 * attempt
+}
+
export function isTerminalModelError(err: unknown): boolean {
const e = err as { code?: unknown; provider?: unknown } | null
if (e?.code === 'credits_exhausted' || e?.code === 'signed_out') return true