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): stop reaches the run, and a repeat after a mutation is not a loop
purplecd0b6bb477cd
diff --git a/src/api/mcp/__tests__/tool-registry-retry.test.ts b/src/api/mcp/__tests__/tool-registry-retry.test.tsnew file mode 100644index 00000000..13b5b0cc--- /dev/null+++ b/src/api/mcp/__tests__/tool-registry-retry.test.ts@@ -0,0 +1,83 @@+/**+ * Audit B2 — a retry re-RUNS the tool, so it must never happen for a+ * side-effecting tool, and never for anything the user aborted. Before this+ * rule the throw path retried EVERYTHING once, blind: a git_commit whose+ * invoke threw after the commit landed committed twice, an aborted+ * shell_execute ran again into the abort.+ */+import { describe, it, expect } from 'vitest'+import { ToolRegistry } from '../tool-registry'+import type { MCPToolDefinition } from '../types'++const mkTool = (name: string, category: MCPToolDefinition['category'] = 'terminal'): MCPToolDefinition => ({+ name,+ description: `description of ${name}`,+ inputSchema: { type: 'object', properties: {}, required: [] },+ category,+ source: 'builtin',+})++function throwingExecutor(message: string, runs: { count: number }) {+ return async () => {+ runs.count+++ throw new Error(message)+ }+}++describe('ToolRegistry.execute — retry discipline (audit B2)', () => {+ it('retries a transient throw for a read-only tool', async () => {+ const registry = new ToolRegistry()+ const runs = { count: 0 }+ registry.registerBuiltin(mkTool('file_read', 'filesystem'), async () => {+ runs.count+++ if (runs.count === 1) throw new Error('fetch failed')+ return 'contents'+ })+ const result = await registry.execute('file_read', {})+ expect(runs.count).toBe(2)+ expect(result).toBe('contents')+ })++ it('never retries a mutating tool, even on a transient throw', async () => {+ const registry = new ToolRegistry()+ const runs = { count: 0 }+ registry.registerBuiltin(mkTool('git_commit'), throwingExecutor('fetch failed', runs))+ const result = await registry.execute('git_commit', {})+ expect(runs.count).toBe(1)+ expect(result).toMatch(/^Error:/)+ })++ it('never retries a non-transient throw', async () => {+ const registry = new ToolRegistry()+ const runs = { count: 0 }+ registry.registerBuiltin(mkTool('file_read', 'filesystem'), throwingExecutor('ENOENT: no such file', runs))+ const result = await registry.execute('file_read', {})+ expect(runs.count).toBe(1)+ expect(result).toContain('ENOENT')+ })++ it('never retries an aborted call — the user said stop', async () => {+ const registry = new ToolRegistry()+ const runs = { count: 0 }+ registry.registerBuiltin(mkTool('file_read', 'filesystem'), async () => {+ runs.count+++ const err = new Error('The operation was aborted')+ err.name = 'AbortError'+ throw err+ })+ const result = await registry.execute('file_read', {})+ expect(runs.count).toBe(1)+ expect(result).toMatch(/^Error:/)+ })++ it('string-result transient errors still only retry read-only tools', async () => {+ const registry = new ToolRegistry()+ const shellRuns = { count: 0 }+ registry.registerBuiltin(mkTool('shell_execute'), async () => {+ shellRuns.count+++ return 'Error: request timed out'+ })+ await registry.execute('shell_execute', {})+ expect(shellRuns.count).toBe(1)+ })+})diff --git a/src/api/mcp/tool-registry.ts b/src/api/mcp/tool-registry.tsindex 116ecf78..ce05637b 100644--- a/src/api/mcp/tool-registry.ts+++ b/src/api/mcp/tool-registry.ts@@ -3,6 +3,7 @@import type { MCPToolDefinition, PermissionMap, PermissionLevel } from './types'import type { OllamaTool } from '../../types/agent-mode'import type { ToolDefinition } from '../providers/types'+import { MUTATING_TOOLS } from '../../lib/mutating-tools'type ToolExecutor = (args: Record<string, any>) => Promise<string>/**@@ -106,19 +107,30 @@ export class ToolRegistry {const entry = this.tools.get(name)if (!entry) return `Error: Unknown tool "${name}"`+ // Audit B2: a retry re-RUNS the tool. For a side-effecting tool that is a+ // second commit, a second push, a second shell command — never acceptable+ // on spec. Reads may retry, and only on transient failures.+ const retriable = !MUTATING_TOOLS.has(name)+ const isTransientText = (s: string) =>+ s.includes('timed out') || s.includes('ECONNREFUSED') || s.includes('fetch failed')+for (let attempt = 0; attempt <= maxRetries; attempt++) {try {const result = await entry.executor(args)// If result is an error and we have retries left, retryif (result.startsWith('Error:') && attempt < maxRetries) {// Only retry on transient errors (timeout, network)- const isTransient = result.includes('timed out') || result.includes('ECONNREFUSED') || result.includes('fetch failed')- if (isTransient) continue+ if (retriable && isTransientText(result)) continue}return result} catch (err) {- if (attempt < maxRetries) continueconst message = err instanceof Error ? err.message : String(err)+ // The throw path used to retry EVERYTHING once, blind — including a+ // git_commit whose invoke threw after the commit landed, and aborted+ // calls. Same rule as the string path: transient + non-mutating only,+ // and an abort is the user speaking, not a network hiccup.+ const aborted = (err as { name?: string })?.name === 'AbortError' || /abort/i.test(message)+ if (attempt < maxRetries && retriable && !aborted && isTransientText(message)) continuereturn `Error: ${message}`}}diff --git a/src/components/chat/CodexView.tsx b/src/components/chat/CodexView.tsxindex b5a2c900..6a939800 100644--- a/src/components/chat/CodexView.tsx+++ b/src/components/chat/CodexView.tsx@@ -455,7 +455,12 @@ export function CodexView() {<ChatInputonSend={(content) => sendInstruction(content)}onStop={stopCodex}- isGenerating={isRunning}+ // Store flag, not the hook's local isRunning (audit A2): the view+ // remounts on every tab switch and a fresh hook says "idle" while+ // the old instance's loop is still running — which offered a second+ // parallel send and no Stop button. The generating flag follows the+ // conversation, not the hook instance.+ isGenerating={isRunning || codexGenerating}slashCommandscomposerModel={<ModelSelector openUpward surface="code" />}composerAbove={<><LoopBar onStop={stopCodex} /><GoalBar /></>}diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex 891da862..511c9ee4 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -138,11 +138,31 @@ export function useAgentChat() {// ── Wait for user approval (enqueues; UI shows head of queue) ──- function waitForApproval(toolCall: AgentToolCall): Promise<boolean> {+ function waitForApproval(toolCall: AgentToolCall, signal?: AbortSignal): Promise<boolean> {return new Promise((resolve) => {+ // Audit A4: this promise used to resolve ONLY on a click. Stop while a+ // tool sat awaiting approval meant the resolver was never called, the+ // loop's finally never ran, and the conversation was wedged with the+ // typing dots on forever. An abort now answers "no" for the user.+ if (signal?.aborted) {+ resolve(false)+ return+ }+ const entry = { toolCall, resolve }const wasEmpty = approvalQueueRef.current.length === 0- approvalQueueRef.current.push({ toolCall, resolve })+ approvalQueueRef.current.push(entry)if (wasEmpty) setPendingApproval(toolCall)+ signal?.addEventListener(+ 'abort',+ () => {+ const idx = approvalQueueRef.current.indexOf(entry)+ if (idx < 0) return // already answered by a click+ approvalQueueRef.current.splice(idx, 1)+ resolve(false)+ if (idx === 0) advanceApprovalQueue()+ },+ { once: true },+ )})}@@ -1160,7 +1180,11 @@ export function useAgentChat() {if (blocked.length) {toolCalls = toolCalls.filter((tc) => !MUTATING_TOOLS.has(tc.function?.name ?? ''))const names = [...new Set(blocked.map((tc) => tc.function.name))].join(', ')- messages.push({+ // `agentMessages`, not `messages` (audit follow-up): this guard was+ // copied from useCodex, whose history array IS called messages. In+ // this hook that name does not exist, so the first read-only turn+ // that actually blocked a mutating call died on a ReferenceError.+ agentMessages.push({role: 'user',content: `${names} is not available on this turn, it is a read-only command. Do not try to change anything. Finish with the written answer using what you have already read.`,})@@ -1222,7 +1246,7 @@ export function useAgentChat() {// creation (permission level 'auto') bypass the approval// gate entirely. Only 'pending_approval' tools enqueue.if (entry.ac.status !== 'pending_approval') return true- const approved = await waitForApproval(entry.ac)+ const approved = await waitForApproval(entry.ac, abort.signal)if (approved) {entry.ac.status = 'running'updateBlockById(convId!, assistantMessage.id, entry.blockId, {@@ -1299,20 +1323,25 @@ export function useAgentChat() {content: contentLabel,})- // `mediaOk` guard: without it a ComfyUI error text was written into the- // PERSISTENT cross-conversation memory store as a 'reference' fact.- if ((result.status === 'completed' || result.status === 'cached') && entry.ac.result && mediaOk) {- const argsShort = JSON.stringify(entry.ac.args).substring(0, 100)- const resultShort = entry.ac.result.substring(0, 200)- useMemoryStore.getState().addMemory({- type: 'reference',- title: `${entry.ac.toolName} result`,- description: `${entry.ac.toolName}(${argsShort.substring(0, 60)}) → ${resultShort.substring(0, 60)}`,- content: `${entry.ac.toolName}(${argsShort}) → ${resultShort}`,- tags: [`agent:${entry.ac.toolName}`],- source: convId || 'agent',- })- }+ // Per-tool-call memory writes were removed here (audit E1): every+ // successful call became a permanent 'reference' memory, so a long+ // run left hundreds of file_read/shell entries competing for the+ // memory budget of every FUTURE conversation, plus one embedding+ // call each against the same backend the chat was using. The+ // curated turn-level extractor (extractMemoriesFromPair) is the+ // memory path; raw tool results were never memories.+ }++ // Epoch reset (audit B1). The over-loop guard blocks a call whose+ // name+args exactly repeat one already run THIS turn. But after a+ // mutation the same call is legitimately new: edit → test → edit →+ // test repeats `run_tests` with identical args and MUST re-run.+ // Same dividing line the loop guard and the in-turn cache use: any+ // side-effecting call may change what the next identical call+ // returns, so the repeat set starts over. Media stays capped via+ // imageGenDone/videoGenDone, which this reset does not touch.+ if (batch.some((e) => MUTATING_TOOLS.has(e.ac.toolName))) {+ executedCallKeys.clear()}// Feed results back into LLM history. Format differs per provider:diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.tsindex 09338aa0..bee0b412 100644--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@ -27,6 +27,7 @@ import {} from '../lib/agent-commands'import { useGenerationStore } from '../stores/generationStore'import { backendCall, isOllamaLocal } from '../api/backend'+import { requestGenerationCancel } from '../api/vram-handoff'import { planWithArchitect, renderArchitectPlanSection } from '../api/agents/architect'import { fetchRepoMap, renderRepoMapSection } from '../api/agents/repo-map'import { isLocalModelByName } from '../api/agents/model-locality'@@ -196,6 +197,15 @@ function codexCanThink(model: string): boolean {return mode ? mode === 'toggle' : isThinkingCompatible(model)}+/**+ * The pending next /loop pass. MODULE scope, not a hook ref (audit A3): the+ * Code view unmounts on every tab switch, and a timer parked in an unmounted+ * instance's ref was unreachable for the remounted hook — stopCodex cleared+ * its own (empty) ref while the old timer kept firing new passes. One shared+ * handle means whichever instance is alive can cancel the pending pass.+ */+let codexLoopTimer: ReturnType<typeof setTimeout> | null = null+export function useCodex() {const [isRunning, setIsRunning] = useState(false)const abortRef = useRef<AbortController | null>(null)@@ -203,8 +213,6 @@ export function useCodex() {/** True once the user pressed stop, so the /loop driver does not start* another pass on the run they just killed. Cleared when a new run starts. */const userStoppedRef = useRef(false)- /** The pending next /loop pass, so stop can cancel it mid-interval. */- const loopTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)const sendInstruction = useCallback(async (rawInstruction: string,@@ -535,6 +543,17 @@ export function useCodex() {// realtime counter show only in the coding chat that's actually running,// not in every chat the user switches to (David 2026-06-12). Cleared below.useGenerationStore.getState().setGenerating(convId, true)+ // Register the abort in the STORE, not just in hook refs (audit A2). The+ // Code view unmounts on a tab switch and the remounted hook starts with+ // empty refs — before this, a run that survived the switch had no working+ // Stop button and a second instruction could start a parallel loop on the+ // same conversation. With the store aborter, stopCodex (any instance) and+ // chat deletion both reach the real controller. Cleared in finally.+ useGenerationStore.getState().registerAborter(convId, () => {+ runningRef.current = false+ abort.abort()+ requestGenerationCancel()+ })// Architect / RepoMap pre-pass (B8 + B9). Both inject into the// system prompt BEFORE the first iteration and surface a visible@@ -1531,7 +1550,7 @@ export function useCodex() {toolName: req.toolName,command: String(a.command ?? a.code ?? a.script ?? '').slice(0, 800),cloudReason: !settings.codexConfirmShell && providerId === 'lu-cloud',- })+ }, abort.signal)}: undefined,recordAudit: (entry) => {@@ -1826,6 +1845,7 @@ export function useCodex() {setIsRunning(false)useGenerationStore.getState().setGenerating(convId, false)+ useGenerationStore.getState().clearAborter(convId)runningRef.current = falseabortRef.current = nullclearActiveChatId()@@ -1876,19 +1896,34 @@ export function useCodex() {task: loopState.task, intervalMs: loopState.intervalMs,nextAt: Date.now() + loopState.intervalMs,})- loopTimerRef.current = setTimeout(() => {- loopTimerRef.current = null+ const fireLoopPass = () => {+ codexLoopTimer = null// Bail if the user moved on or started something else meanwhile.- if (runningRef.current) return+ // Clear the loop store too — leaving it standing painted a LoopBar+ // that promised a pass which was never coming (audit A3).+ if (runningRef.current) {+ useAgentLoopStore.getState().clear()+ return+ }if (useChatStore.getState().activeConversationId !== convForLoop) {useAgentLoopStore.getState().clear()return}+ // The Code view is not on screen (other chat mode, other view):+ // do NOT start an invisible run — the loop's own contract is+ // "never running invisibly" (David 2026-07-25). Defer instead of+ // cancel, so peeking at Create doesn't kill a standing loop; the+ // pass fires within 5 s of the view coming back.+ if (useCodexStore.getState().chatMode !== 'codex') {+ codexLoopTimer = setTimeout(fireLoopPass, 5000)+ return+ }void sendRef.current?.(buildLoopRecheck(loopState.task, nextPass), {displayContent: cap > 0 ? `pass ${nextPass} of ${cap}` : `pass ${nextPass}`,loop: { ...loopState, pass: nextPass },})- }, loopState.intervalMs)+ }+ codexLoopTimer = setTimeout(fireLoopPass, loopState.intervalMs)}}}@@ -1903,14 +1938,18 @@ export function useCodex() {// Stop means stop: also cancel a /loop pass that is waiting out its// interval, otherwise the run the user just killed comes back by itself.userStoppedRef.current = true- if (loopTimerRef.current) {- clearTimeout(loopTimerRef.current)- loopTimerRef.current = null+ if (codexLoopTimer) {+ clearTimeout(codexLoopTimer)+ codexLoopTimer = null}useAgentLoopStore.getState().clear()runningRef.current = falseabortRef.current?.abort()abortRef.current = null+ // The run may belong to a PREVIOUS hook instance (the Code view remounts+ // on every tab switch) whose controller this instance never saw. The+ // store-registered aborter reaches it regardless of who started it.+ useGenerationStore.getState().abortConversation(useChatStore.getState().activeConversationId)setIsRunning(false)}, [])diff --git a/src/stores/__tests__/codexConfirmStore-abort.test.ts b/src/stores/__tests__/codexConfirmStore-abort.test.tsnew file mode 100644index 00000000..ea213e1b--- /dev/null+++ b/src/stores/__tests__/codexConfirmStore-abort.test.ts@@ -0,0 +1,54 @@+/**+ * Audit A4 — Stop while the shell-confirm dialog is open must resolve the+ * awaited approval as "no" and take the dialog down. Before this, the promise+ * only ever resolved on a click, so the run's finally never ran and the chat+ * stayed wedged with the typing dots on.+ */+import { describe, it, expect, beforeEach } from 'vitest'+import { useCodexConfirmStore } from '../codexConfirmStore'++const req = { toolName: 'shell_execute', command: 'rm -rf build', cloudReason: false }++beforeEach(() => {+ useCodexConfirmStore.setState({ pending: null, resolve: null })+})++describe('codexConfirmStore.ask with an abort signal', () => {+ it('resolves false and clears the dialog when the signal fires', async () => {+ const ctrl = new AbortController()+ const p = useCodexConfirmStore.getState().ask(req, ctrl.signal)+ expect(useCodexConfirmStore.getState().pending).not.toBeNull()+ ctrl.abort()+ await expect(p).resolves.toBe(false)+ expect(useCodexConfirmStore.getState().pending).toBeNull()+ expect(useCodexConfirmStore.getState().resolve).toBeNull()+ })++ it('resolves false immediately on an already-aborted signal', async () => {+ const ctrl = new AbortController()+ ctrl.abort()+ await expect(useCodexConfirmStore.getState().ask(req, ctrl.signal)).resolves.toBe(false)+ expect(useCodexConfirmStore.getState().pending).toBeNull()+ })++ it('a click still wins over a later abort', async () => {+ const ctrl = new AbortController()+ const p = useCodexConfirmStore.getState().ask(req, ctrl.signal)+ useCodexConfirmStore.getState().answer(true)+ ctrl.abort()+ await expect(p).resolves.toBe(true)+ })++ it('an abort of request A does not clear a newer request B', async () => {+ const a = new AbortController()+ const pA = useCodexConfirmStore.getState().ask(req, a.signal)+ const pB = useCodexConfirmStore.getState().ask({ ...req, command: 'npm test' })+ // B replaced A, so A already resolved false; aborting A now must not+ // touch B's open dialog.+ a.abort()+ await expect(pA).resolves.toBe(false)+ expect(useCodexConfirmStore.getState().pending?.command).toBe('npm test')+ useCodexConfirmStore.getState().answer(true)+ await expect(pB).resolves.toBe(true)+ })+})diff --git a/src/stores/codexConfirmStore.ts b/src/stores/codexConfirmStore.tsindex 6477fb0b..e1aa6c0d 100644--- a/src/stores/codexConfirmStore.ts+++ b/src/stores/codexConfirmStore.ts@@ -25,7 +25,7 @@ interface CodexConfirmState {pending: CodexConfirmRequest | null/** Resolver for the awaited approval. Null when nothing is pending. */resolve: ((allow: boolean) => void) | null- ask: (req: CodexConfirmRequest) => Promise<boolean>+ ask: (req: CodexConfirmRequest, signal?: AbortSignal) => Promise<boolean>answer: (allow: boolean) => void}@@ -33,13 +33,28 @@ export const useCodexConfirmStore = create<CodexConfirmState>((set, get) => ({pending: null,resolve: null,- ask: (req) =>+ ask: (req, signal) =>new Promise<boolean>((resolve) => {+ // Audit A4: Stop while the dialog was open never resolved this promise,+ // so the run's finally never ran and the chat stayed wedged. An abort+ // answers "no" and takes the dialog down with it.+ if (signal?.aborted) {+ resolve(false)+ return+ }// A second request while one is open would strand the first resolver and// hang that tool call forever. Deny the older one and take the new.const prev = get().resolveif (prev) prev(false)set({ pending: req, resolve })+ signal?.addEventListener(+ 'abort',+ () => {+ if (get().resolve === resolve) set({ pending: null, resolve: null })+ resolve(false)+ },+ { once: true },+ )}),answer: (allow) => {