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): the loop guard sees failures a tool reports as text

purple80557abd1ae8
diff --git a/src/api/agents/tool-executor.ts b/src/api/agents/tool-executor.ts
index b2eb56ff..08260fd5 100644
--- a/src/api/agents/tool-executor.ts
+++ b/src/api/agents/tool-executor.ts
@@ -495,6 +495,18 @@ function abortedResult(tagged: { req: ExecutionRequest; key?: string }): Executi
}
}
+/**
+ * What the loop guard needs to know about one result: did it fail. A tool that
+ * reports its failure as text (`Error (1): …`, `Web search failed: …`) comes
+ * back `completed`, and the guard fed `status === 'failed'` never saw it: a
+ * command failing over and over read as progress and even cleared the failure
+ * streaks (bug hunt 01.10.2026), so the run went on to the 200-round budget.
+ */
+export function resultFailed(r: Pick<ExecutionResult, 'status' | 'result'>): boolean {
+ if (r.status === 'failed') return true
+ return (r.status === 'completed' || r.status === 'cached') && toolResultIsFailure(r.result)
+}
+
/** Convenience: attach ExecutionResult fields back onto an AgentToolCall. */
export function applyResultToToolCall(call: AgentToolCall, result: ExecutionResult): AgentToolCall {
call.status =
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 8341d04e..63a81296 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -88,7 +88,7 @@ import { budgetFromSettings } from '../api/agents/budget'
import type { ChatMessage, ToolCall, ToolDefinition } from '../api/providers/types'
import type { WorkflowEngineCallbacks } from '../types/agent-workflows'
import { renderWorkflowStepList, workflowProgressHeader, type WorkflowStepView } from '../lib/workflow-progress-view'
-import { executeParallel, applyResultToToolCall, type ExecutionRequest } from '../api/agents/tool-executor'
+import { executeParallel, applyResultToToolCall, resultFailed, type ExecutionRequest } from '../api/agents/tool-executor'
import { useToolAuditStore } from '../stores/toolAuditStore'
import { makeInTurnCacheLookup } from '../api/agents/in-turn-cache'
import { explainError as explainToolError } from '../api/agents/error-hints'
@@ -2705,7 +2705,7 @@ export function useAgentChat() {
// cannot see (they only look at what was asked for, and they skip
// shell on purpose).
const failVerdict = loopGuard.recordResults(
- results.map((r) => ({ name: r.toolName, failed: r.status === 'failed', error: r.error, args: r.dispatchedArgs })),
+ results.map((r) => ({ name: r.toolName, failed: resultFailed(r), error: r.error ?? (resultFailed(r) ? r.result?.split('\n')[0].slice(0, 300) : undefined), args: r.dispatchedArgs })),
)
if (failVerdict.action === 'halt') {
addBlock(runState, convId!, assistantMessage.id, {
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index f46b284e..62356cf8 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -56,7 +56,7 @@ import { log } from '../lib/logger'
import type { AgentToolCall } from '../types/agent-mode'
import { isThinkingCompatible, isPlainTextPlanner } from '../lib/model-compatibility'
import type { ChatMessage, ToolCall, ToolDefinition } from '../api/providers/types'
-import { executeParallel, applyResultToToolCall, APPROVE_ALL, type ExecutionRequest } from '../api/agents/tool-executor'
+import { executeParallel, applyResultToToolCall, resultFailed, APPROVE_ALL, type ExecutionRequest } from '../api/agents/tool-executor'
import { useToolAuditStore } from '../stores/toolAuditStore'
import { makeInTurnCacheLookup } from '../api/agents/in-turn-cache'
import { explainError as explainToolError } from '../api/agents/error-hints'
@@ -2410,7 +2410,7 @@ export function useCodex() {
// cannot see (they only look at what was asked for, and they skip
// shell on purpose).
const failVerdict = loopGuard.recordResults(
- results.map((r) => ({ name: r.toolName, failed: r.status === 'failed', error: r.error, args: r.dispatchedArgs })),
+ results.map((r) => ({ name: r.toolName, failed: resultFailed(r), error: r.error ?? (resultFailed(r) ? r.result?.split('\n')[0].slice(0, 300) : undefined), args: r.dispatchedArgs })),
)
if (failVerdict.action === 'halt') {
const msg = `\n\n_(halted: ${failVerdict.reason}. The model is looping. Try a stronger model for multi-step code tasks, or rephrase the instruction.)_`
diff --git a/src/lib/__tests__/loop-guard-failing-rounds.test.ts b/src/lib/__tests__/loop-guard-failing-rounds.test.ts
index 73e4f9e3..cf5a9b93 100644
--- a/src/lib/__tests__/loop-guard-failing-rounds.test.ts
+++ b/src/lib/__tests__/loop-guard-failing-rounds.test.ts
@@ -195,17 +195,19 @@ describe('G36: variants of the same failing executable', () => {
it('the hooks hand the dispatched args through', () => {
for (const f of ['../../hooks/useCodex.ts', '../../hooks/useAgentChat.ts']) {
- expect(read(f)).toMatch(/error: r\.error, args: r\.dispatchedArgs/)
+ expect(read(f)).toMatch(/error: r\.error \?\? [^\n]*, args: r\.dispatchedArgs/)
}
})
})
describe('both agent loops feed it', () => {
for (const f of ['../../hooks/useCodex.ts', '../../hooks/useAgentChat.ts']) {
+ // The real status includes a failure the tool reported as text
+ // (resultFailed, bug hunt 01.10.2026; loop-guard-sees-text-failures.test.ts).
it(`${f.split('/').pop()} calls recordResults with the real statuses`, () => {
const src = read(f)
expect(src).toMatch(/loopGuard\.recordResults\(/)
- expect(src).toMatch(/failed: r\.status === 'failed'/)
+ expect(src).toMatch(/failed: resultFailed\(r\)/)
expect(src).toMatch(/failVerdict\.action === 'halt'/)
expect(src).toMatch(/failVerdict\.action === 'steer'/)
})
diff --git a/src/lib/__tests__/loop-guard-sees-text-failures.test.ts b/src/lib/__tests__/loop-guard-sees-text-failures.test.ts
new file mode 100644
index 00000000..ee383be9
--- /dev/null
+++ b/src/lib/__tests__/loop-guard-sees-text-failures.test.ts
@@ -0,0 +1,51 @@
+/**
+ * Bug hunt 01.10.2026: a tool that reports its failure as text comes back from
+ * the executor as `completed`. The loop guard was fed `status === 'failed'`,
+ * so `npm test` failing six times in a row (`Error (1): …`) read as six
+ * successful non-read calls: the failure streak never grew and was even reset
+ * every round, and the run went on to the 200-round budget, resending the
+ * whole context each step.
+ */
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+import { AgentLoopGuard } from '../agent-loop-guard'
+import { resultFailed } from '../../api/agents/tool-executor'
+
+const npmTestFails = { status: 'completed' as const, result: 'Error (1):\nnpm ERR! Test failed. See above for more details.' }
+
+describe('the loop guard sees failures a tool reports as text', () => {
+ it('six rounds of a failing shell command halt the run', () => {
+ const g = new AgentLoopGuard()
+ const verdicts = Array.from({ length: 6 }, () =>
+ g.recordResults([{ name: 'shell_execute', failed: resultFailed(npmTestFails), error: 'Error (1)' }]),
+ )
+ expect(verdicts[2].action).toBe('steer')
+ expect(verdicts[5].action).toBe('halt')
+ })
+
+ it('NEGATIVE CONTROL: fed status alone, the same run is never stopped', () => {
+ const g = new AgentLoopGuard()
+ const verdicts = Array.from({ length: 12 }, () =>
+ g.recordResults([{ name: 'shell_execute', failed: npmTestFails.status === ('failed' as string) }]),
+ )
+ expect(verdicts.every((v) => v.action === 'ok')).toBe(true)
+ })
+
+ it('reads the forms our tools fail in, and nothing else', () => {
+ expect(resultFailed({ status: 'failed', result: undefined })).toBe(true)
+ expect(resultFailed({ status: 'completed', result: 'Web search failed: timeout' })).toBe(true)
+ expect(resultFailed({ status: 'cached', result: 'Error: 500' })).toBe(true)
+ expect(resultFailed({ status: 'completed', result: 'Found 3 results for "rocket launch"' })).toBe(false)
+ expect(resultFailed({ status: 'completed', result: 'ok' })).toBe(false)
+ expect(resultFailed({ status: 'rejected', result: 'Error: no' })).toBe(false)
+ })
+
+ it('both loops feed the guard through it', () => {
+ for (const hook of ['useAgentChat.ts', 'useCodex.ts']) {
+ const src = readFileSync(resolve(__dirname, '../../hooks', hook), 'utf8')
+ expect(src).toMatch(/loopGuard\.recordResults\(\s*results\.map\(\(r\) => \(\{ name: r\.toolName, failed: resultFailed\(r\)/)
+ expect(src).not.toMatch(/failed: r\.status === 'failed'/)
+ }
+ })
+})