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.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(agent): a refused call ends the run at once and says why
purple7110df26870f
diff --git a/src/components/layout/CreditsExhaustedModal.tsx b/src/components/layout/CreditsExhaustedModal.tsxindex 29348665..22d261f3 100644--- a/src/components/layout/CreditsExhaustedModal.tsx+++ b/src/components/layout/CreditsExhaustedModal.tsx@@ -23,7 +23,7 @@ export function CreditsExhaustedModal() {<Modal open={open} onClose={() => setOpen(false)} title="You're out of credits"><div className="space-y-4"><p className="text-sm text-gray-600 dark:text-gray-300">- Your plan credits for this billing period are used up — they refill on+ Your plan credits for this billing period are used up. They refill onyour next renewal date. Top-up credits are one-time, never expire, andare only used after your plan credits.</p>diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex 45450fd3..7713a1b4 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -70,6 +70,8 @@ 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 { CREDITS_EXHAUSTED_MESSAGE } from '../lib/credits-exhausted'// ── Standalone memory extraction (usable outside React hooks) ──@@ -826,7 +828,7 @@ export function useAgentChat() {log.warn('agent.vision_feedback_healed', { model: modelToUse })continue}- if (thinkErr?.message?.includes('does not support thinking') || thinkErr?.statusCode === 400) {+ if (thinkErr?.message?.includes('does not support thinking') || httpStatusOf(thinkErr) === 400) {turn = await streamOllamaChatWithTools(modelToUse,agentMessages,@@ -847,10 +849,10 @@ export function useAgentChat() {)break}- // Retry ONLY transient failures. A 4xx (e.g. context overflow) is- // deterministic — retrying just repeats it, so let it surface.- const sc = typeof thinkErr?.statusCode === 'number' ? thinkErr.statusCode : 0- const transient = thinkErr?.name !== 'AbortError' && !(sc >= 400 && sc < 500)+ // Retry ONLY transient failures. A deterministic client error+ // (context overflow, empty wallet) repeats itself, so it has to+ // surface at once instead of costing the user two backoffs.+ 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) })@@ -909,12 +911,11 @@ export function useAgentChat() {log.warn('agent.vision_feedback_healed', { model: modelToUse, provider: providerId })continue}- if (thinkErr?.message?.includes('does not support thinking') || thinkErr?.statusCode === 400) {+ if (thinkErr?.message?.includes('does not support thinking') || httpStatusOf(thinkErr) === 400) {turn = await streamProviderTurn(provider, modelToUse, agentMessages, { ...streamOpts, thinking: undefined as unknown as boolean }, onLiveContent, () => {})break}- const sc = typeof thinkErr?.statusCode === 'number' ? thinkErr.statusCode : 0- const transient = thinkErr?.name !== 'AbortError' && !(sc >= 400 && sc < 500)+ 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) })@@ -1745,6 +1746,20 @@ export function useAgentChat() {convId!, assistantMessage.id,`This model does not support thinking mode. Disable the Think button or switch to a compatible model (Qwen 3, DeepSeek-R1, Gemma 4).`)+ } else if ((err as { code?: string })?.code === 'credits_exhausted') {+ // No retry fixes an empty wallet, and on a long run this line is the+ // only thing left on screen once the dialog is dismissed. Name where+ // the plan stopped, so "it froze" reads as "it was refused" (Morgan,+ // 2026-08-10), and say how to resume without paying twice.+ const todos = useTodoStore.getState().getTodos(convId!)+ const done = todos.filter((t) => t.status === 'completed').length+ const planLine = todos.length+ ? `\n\nThe plan stopped at ${done} of ${todos.length}. Everything finished so far stays in this chat. Once you top up, send a new message naming only what is still left, rather than the original prompt, so the finished steps are not paid for twice.`+ : ''+ useChatStore.getState().updateMessageContent(+ convId!, assistantMessage.id,+ (contentRef.current ? contentRef.current + '\n\n' : '') + CREDITS_EXHAUSTED_MESSAGE + planLine+ )} 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, ordiff --git a/src/hooks/useChat.ts b/src/hooks/useChat.tsindex 9a43e387..f4406743 100644--- a/src/hooks/useChat.ts+++ b/src/hooks/useChat.ts@@ -31,6 +31,7 @@ import type { ImageAttachment, Message } from "../types/chat"import { isGroupChat, groupSystemPrompt, groupHistory, stripImpersonatedSpeakers } from "../lib/group-chat"import { emptyAnswerExplanation } from "../lib/answer-notes"import { log } from "../lib/logger"+import { CREDITS_EXHAUSTED_MESSAGE } from '../lib/credits-exhausted'/*** Pull the most recent media generation (image/video) out of an assistant@@ -764,6 +765,14 @@ export function useChat() {assistantMessage.id,MULTIMODAL_UNSUPPORTED_MESSAGE)+ // An empty wallet gets the same plain explanation everywhere, next to+ // the dialog that offers the top-up (lib/credits-exhausted.ts).+ } else if ((err as { code?: string })?.code === 'credits_exhausted') {+ useChatStore.getState().updateMessageContent(+ convId!,+ assistantMessage.id,+ (contentRef.current ? contentRef.current + '\n\n' : '') + CREDITS_EXHAUSTED_MESSAGE+ )// Show user-friendly message for thinking errors} else if (errorMsg.includes('does not support thinking')) {useChatStore.getState().updateMessageContent(diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.tsindex 1bf4bf58..339ca62d 100644--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@ -47,6 +47,8 @@ import { finalStripThinkingTags, splitOrphanCloser, splitUnclosedThink } from '.import { openPlanGap, planReconcileSteer, PLAN_RECONCILE_BUDGET } from '../lib/plan-reconcile'import { PlanStaleness, planStalenessSteer } from '../lib/plan-staleness'import { useTodoStore } from '../stores/todoStore'+import { httpStatusOf } from '../lib/http-status'+import { CREDITS_EXHAUSTED_MESSAGE } from '../lib/credits-exhausted'import { streamOllamaChatWithTools } from '../lib/ollama-stream-tools'import { extractToolCallsWithRanges, stripRanges } from '../lib/tool-call-repair'import { canonicalToolName } from '../lib/loose-tool-parse'@@ -950,11 +952,11 @@ export function useCodex() {} catch (thinkErr: any) {void diagLog('streamWithTools-catch', {iter: i,- statusCode: thinkErr?.statusCode,+ status: httpStatusOf(thinkErr),messageHead: (thinkErr?.message || String(thinkErr)).slice(0, 400),name: thinkErr?.name,})- if (thinkErr?.statusCode === 400 || thinkErr?.message?.includes('does not support thinking')) {+ if (httpStatusOf(thinkErr) === 400 || thinkErr?.message?.includes('does not support thinking')) {turn = await streamWithTools(modelToUse, messages, tools,{ temperature: 0.1, thinking: undefined, maxTokens: chatOptions.maxTokens, contextWindow: numCtx, signal: abort.signal },@@ -1056,7 +1058,7 @@ export function useCodex() {try {turn = await streamProviderTurn(provider, modelToUse, messages, streamOpts, liveContent, liveThinking)} catch (thinkErr: any) {- if (thinkErr?.message?.includes('does not support thinking') || thinkErr?.statusCode === 400) {+ if (thinkErr?.message?.includes('does not support thinking') || httpStatusOf(thinkErr) === 400) {turn = await streamProviderTurn(provider, modelToUse, messages, { ...streamOpts, thinking: undefined as unknown as boolean }, liveContent, () => {})} else {throw thinkErr@@ -1912,13 +1914,14 @@ export function useCodex() {void diagLog('outer-catch', {name: (err as Error)?.name,message: (err as Error)?.message?.slice(0, 400),- statusCode: (err as any)?.statusCode,+ status: httpStatusOf(err),})if ((err as Error).name !== 'AbortError') {const e = err as anyconst parts: string[] = []if (e?.code) parts.push(`[${e.code}]`)- if (typeof e?.statusCode === 'number') parts.push(`HTTP ${e.statusCode}`)+ const status = httpStatusOf(e)+ if (status) parts.push(`HTTP ${status}`)parts.push(e?.message || String(err) || 'Coding Agent error')const msg = parts.join(' ')// Surface common causes so the user can see WHY it failed instead of@@ -1933,6 +1936,16 @@ export function useCodex() {} else if (/timed out/i.test(msg)) {hint = '\n\nHint: a tool call exceeded its time budget. For long builds, raise the command timeout, split the work, or run it via shell_execute_background.'}+ // An empty wallet is not a crash and no retry fixes it. Replace the+ // status-code line with the plain explanation the other surfaces use.+ if (e?.code === 'credits_exhausted') {+ fullContent += `\n\n${CREDITS_EXHAUSTED_MESSAGE}\n\nThe work finished so far stays in this chat. Once you top up, send a new message naming only what is still left.`+ useChatStore.getState().updateMessageContent(convId, assistantMsg.id, fullContent)+ codexStore.addEvent(convId, {+ id: uuid(), type: 'error', content: 'Out of credits.', timestamp: Date.now(),+ })+ return+ }fullContent += `\n\nError: ${msg}${hint}`useChatStore.getState().updateMessageContent(convId, assistantMsg.id, fullContent)codexStore.addEvent(convId, {diff --git a/src/lib/__tests__/http-status.test.ts b/src/lib/__tests__/http-status.test.tsnew file mode 100644index 00000000..034e1e72--- /dev/null+++ b/src/lib/__tests__/http-status.test.ts@@ -0,0 +1,61 @@+// The retry guard reads the status off whichever field the transport used.+//+// Morgan, 2026-08-10: an out-of-credits agent run "was still cycling". It was+// not. The guard "never retry a deterministic 4xx" read `statusCode`, which+// only the Ollama path sets, so on the cloud path (ProviderError, `.status`)+// the refusal fell through to the transient branch and was retried twice with+// 1.5 s and 3 s of backoff before anything reached the screen.+import { describe, it, expect } from 'vitest'+import { httpStatusOf, isTerminalModelError } from '../http-status'+import { ProviderError } from '../../api/providers/types'++describe('httpStatusOf', () => {+ it('reads the cloud transport, which carries `status` (ProviderError)', () => {+ expect(httpStatusOf(new ProviderError('out of credits', 'openai', 'credits_exhausted', 429))).toBe(429)+ })++ it('reads the Ollama transport, which carries `statusCode`', () => {+ expect(httpStatusOf(Object.assign(new Error('HTTP 400: nope'), { statusCode: 400 }))).toBe(400)+ })++ it('is 0 for everything that carries no status at all', () => {+ for (const e of [null, undefined, 'boom', new Error('Failed to fetch'), {}, { status: '429' }, { status: Number.NaN }]) {+ expect(httpStatusOf(e)).toBe(0)+ }+ })+})++describe('isTerminalModelError', () => {+ it('an empty wallet is terminal, whatever the status says', () => {+ expect(isTerminalModelError(new ProviderError('out of credits', 'openai', 'credits_exhausted', 429))).toBe(true)+ })++ it('REGRESSION: the same refusal was NOT terminal while the guard read statusCode', () => {+ // The exact object the cloud path threw. Reading `statusCode` alone yields+ // undefined, so the old rule classified it as transient and retried it.+ const err = new ProviderError('out of credits', 'openai', 'credits_exhausted', 429)+ expect((err as unknown as { statusCode?: number }).statusCode).toBeUndefined()+ expect(isTerminalModelError(err)).toBe(true)+ })++ it('a deterministic 4xx is terminal on both transports', () => {+ expect(isTerminalModelError(new ProviderError('context overflow', 'openai', undefined, 400))).toBe(true)+ expect(isTerminalModelError(Object.assign(new Error('x'), { statusCode: 404 }))).toBe(true)+ expect(isTerminalModelError(new ProviderError('bad key', 'openai', 'auth', 401))).toBe(true)+ })++ it('NEGATIVE CONTROL: a throttle is NOT terminal, so a burst still retries', () => {+ // LU Cloud answers 429 for three things. Two of them (the per-user burst+ // guard and an upstream provider throttle) pass retry-after and clear on+ // their own; only the empty wallet is final. Treating every 429 as+ // terminal would turn a two-second wait into a failed run.+ expect(isTerminalModelError(new ProviderError('too many requests', 'openai', 'rate_limit', 429))).toBe(false)+ expect(isTerminalModelError(Object.assign(new Error('rate limited'), { statusCode: 429 }))).toBe(false)+ })++ it('server trouble and network trouble stay retryable', () => {+ expect(isTerminalModelError(new ProviderError('bad gateway', 'openai', undefined, 502))).toBe(false)+ expect(isTerminalModelError(new ProviderError('overloaded', 'anthropic', undefined, 529))).toBe(false)+ expect(isTerminalModelError(new Error('Failed to fetch'))).toBe(false)+ })+})diff --git a/src/lib/credits-exhausted.ts b/src/lib/credits-exhausted.tsindex 0cd9c4f2..52dde15b 100644--- a/src/lib/credits-exhausted.ts+++ b/src/lib/credits-exhausted.ts@@ -15,3 +15,17 @@ export function signalCreditsExhausted(): void {window.dispatchEvent(new Event(CREDITS_EXHAUSTED_EVENT))}}++/**+ * What the transcript says. The dialog above opens on top of the answer, but a+ * dismissed dialog leaves nothing behind, and on a long agent run the last line+ * in the chat is the only thing the user still reads minutes later (Morgan,+ * 2026-08-10: an out-of-credits run read as "it is still cycling"). Every+ * surface renders this instead of a generic error line.+ */+export const CREDITS_EXHAUSTED_MESSAGE =+ "You're out of credits, so the server refused this request.\n\n" ++ 'Plan credits refill on your renewal date. Top-up credits are one-time, never ' ++ 'expire, and are only used once the plan credits are gone. Load up at ' ++ TOPUP_URL ++ '.'diff --git a/src/lib/http-status.ts b/src/lib/http-status.tsnew file mode 100644index 00000000..848b814a--- /dev/null+++ b/src/lib/http-status.ts@@ -0,0 +1,36 @@+// The HTTP status of a failed model call, whichever field happens to carry it.+//+// ProviderError (api/providers/types.ts) stores it as `status`; the Ollama+// streaming path (lib/ollama-stream-tools.ts) tags its plain Error with+// `statusCode`. A guard that reads only one of the two is dead on the other+// transport, and both are on the hot path of every run.+//+// That is exactly what happened (Morgan, 2026-08-10): the agent's rule "never+// retry a deterministic 4xx" read `statusCode`, so on the cloud path an+// out-of-credits refusal was retried twice with backoff before anything was+// shown, and a dying run looked like work for another 4.5 seconds.++export function httpStatusOf(err: unknown): number {+ if (!err || typeof err !== 'object') return 0+ const e = err as { status?: unknown; statusCode?: unknown }+ const raw = typeof e.status === 'number' ? e.status : e.statusCode+ return typeof raw === 'number' && Number.isFinite(raw) ? raw : 0+}++/**+ * Is retrying this failure pointless? True for a deterministic client error:+ * the same request will be refused the same way, so the run must stop and say+ * so instead of burning seconds on backoff.+ *+ * 429 is the exception that makes this worth a function. LU Cloud answers 429+ * for three different things: the per-user burst guard, an upstream provider+ * throttle (both genuinely transient, both send retry-after), and an empty+ * wallet, which no amount of waiting fixes. Only the last one is terminal, and+ * it is the only one that carries `code: 'credits_exhausted'`.+ */+export function isTerminalModelError(err: unknown): boolean {+ const code = (err as { code?: unknown } | null)?.code+ if (code === 'credits_exhausted') return true+ const status = httpStatusOf(err)+ return status >= 400 && status < 500 && status !== 429+}