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 loop ends where the credits do
David9e399aa67360
diff --git a/src/hooks/__tests__/loop-stops-on-terminal.test.ts b/src/hooks/__tests__/loop-stops-on-terminal.test.tsnew file mode 100644index 00000000..ecc66b60--- /dev/null+++ b/src/hooks/__tests__/loop-stops-on-terminal.test.ts@@ -0,0 +1,74 @@+/**+ * A loop must not outlive a refusal that no retry can fix.+ *+ * Found reviewing the A3 and A4 fixes (2026-08-14). Those two made an empty+ * wallet terminal: the catch writes CREDITS_EXHAUSTED_MESSAGE and returns. But+ * `return` does not skip `finally`, and the /loop driver lives in the finally.+ * It gates on three things, none of them the wallet, so with the default+ * interval of 5 s the next pass fires, the proxy refuses it again, and+ * CreditsExhaustedModal reopens on every pass. The user dismisses a dialog that+ * comes straight back, forever, until they find Stop. Both surfaces carry the+ * same driver and both had the same gap.+ *+ * Source-level, like the other driver tests: the pass is scheduled deep inside+ * a hook that needs the whole app around it, and what has to hold is a property+ * of the control flow, not of a rendered component.+ *+ * Run: npx vitest run src/hooks/__tests__/loop-stops-on-terminal.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 codex = readFileSync(resolve(here, '../useCodex.ts'), 'utf8')+const agent = readFileSync(resolve(here, '../useAgentChat.ts'), 'utf8')++describe.each([+ ['the coding surface', codex, 'loopState && convId && loopHalt', 'codexLoopTimer = setTimeout('],+ ['the agent surface', agent, 'opts?.loop && convId && loopHalt', 'agentLoopTimer = setTimeout('],+])('%s', (_name, src, guard, scheduler) => {+ it('declares the halt per run, so one refusal cannot poison the next loop', () => {+ expect(src).toContain('let loopHalt: string | null = null')+ })++ it('sets it where the wallet is refused', () => {+ const at = src.indexOf("loopHalt = 'out of credits'")+ expect(at).toBeGreaterThan(-1)+ const credits = src.indexOf("code === 'credits_exhausted'")+ expect(credits).toBeGreaterThan(-1)+ // Set inside the credits branch, not somewhere that happens to run anyway.+ expect(at - credits).toBeGreaterThan(0)+ expect(at - credits).toBeLessThan(400)+ })++ it('the driver checks it BEFORE the branch that schedules the next pass', () => {+ const halt = src.indexOf(guard)+ const schedule = src.indexOf(scheduler)+ expect(halt).toBeGreaterThan(-1)+ expect(schedule).toBeGreaterThan(-1)+ expect(halt).toBeLessThan(schedule)+ })++ it('it clears the loop store, or the bar keeps promising a pass nobody runs', () => {+ const block = src.slice(src.indexOf(guard), src.indexOf(guard) + 700)+ expect(block).toContain('useAgentLoopStore.getState().clear()')+ })++ it('and says once why it stopped', () => {+ expect(src).toContain('The loop stopped because the run was ${loopHalt}')+ })+})++describe('the ordinary loop is untouched', () => {+ it('a normal pass still reaches the scheduler through the else branch', () => {+ expect(codex).toContain('} else if (loopState && convId && !userStoppedRef.current) {')+ expect(agent).toContain('} else if (opts?.loop && convId && !userStoppedRef.current) {')+ })++ it('LOOP_DONE and the pass cap are still the other two ways out', () => {+ expect(codex).toContain('loopPassSaysDone(fullContent.trim())')+ expect(codex).toContain('cap > 0 && nextPass > cap')+ })+})diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex 7713a1b4..8e344001 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -554,6 +554,11 @@ export function useAgentChat() {// interrupted when the chat is deleted mid-generation (gated to a no-op when// nothing is in flight).useGenerationStore.getState().registerAborter(convId, () => { runningRef.current = false; abort.abort(); requestGenerationCancel() })+ // A refusal no retry can fix has to end the loop as well. `return` in the+ // catch does not skip the finally, so without this the driver fires the+ // next pass into the same refusal and the credits dialog reopens every+ // interval until the user finds Stop.+ let loopHalt: string | null = nullcontentRef.current = ''thinkingRef.current = ''blocksRef.current = []@@ -1747,6 +1752,7 @@ export function useAgentChat() {`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') {+ loopHalt = 'out of credits'// 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,@@ -1827,7 +1833,15 @@ export function useAgentChat() {// one: a loop someone asked to keep going keeps going until it says done// or they stop it. The loop bar above the composer is what keeps that// honest rather than invisible.- if (opts?.loop && convId && !userStoppedRef.current) {+ if (opts?.loop && convId && loopHalt) {+ // Same rule as the coding surface: no retry fixes an empty wallet, so+ // the loop ends here instead of refiring into the same refusal.+ useAgentLoopStore.getState().clear()+ useChatStore.getState().addMessage(convId, {+ id: uuid(), role: 'assistant', timestamp: Date.now(),+ content: `The loop stopped because the run was ${loopHalt}. Start it again once that is sorted.`,+ })+ } else if (opts?.loop && convId && !userStoppedRef.current) {const loopState = opts.loopconst saidDone = loopPassSaysDone(contentRef.current.trim())const cap = Math.max(0, useSettingsStore.getState().settings.loopMaxPasses ?? 0)diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.tsindex d922621b..b36cc2dd 100644--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@ -272,6 +272,11 @@ export function useCodex() {// still works: honour it, and carry the two generators openly from the next// step on rather than leaving the model to reference a file it cannot make.let createGateOpened = false+ // A loop must not outlive a refusal no retry can fix. `return` in the catch+ // below does not skip the finally, so without this the /loop driver simply+ // fires the next pass, the proxy refuses it again, and the credits dialog+ // reopens every interval until the user finds Stop.+ let loopHalt: string | null = null// A brand-new instruction clears a previous stop; a /loop pass inherits it.if (!opts?.loop) userStoppedRef.current = false// `/loop [30s] …` — the interval is the PAUSE BETWEEN PASSES, and the@@ -1997,6 +2002,7 @@ export function useCodex() {// 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') {+ loopHalt = 'out of credits'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, {@@ -2094,7 +2100,16 @@ export function useCodex() {// keep going keeps going (David 2026-07-25). The stop button is the// brake, and the loop bar above the composer makes sure it is never// running invisibly.- if (loopState && convId && !userStoppedRef.current) {+ if (loopState && convId && loopHalt) {+ // Stop the loop where the refusal happened, and say so once. Silently+ // dropping it would leave the LoopBar promising a pass nobody is going+ // to run (audit A3).+ useAgentLoopStore.getState().clear()+ useChatStore.getState().addMessage(convId, {+ id: uuid(), role: 'assistant', timestamp: Date.now(),+ content: `The loop stopped because the run was ${loopHalt}. Start it again once that is sorted.`,+ })+ } else if (loopState && convId && !userStoppedRef.current) {const saidDone = loopPassSaysDone(fullContent.trim())const cap = Math.max(0, settings.loopMaxPasses ?? 0)const nextPass = loopState.pass + 1