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): end the file_read loop — real cloud context, bounded prompts, read-your-writes, hardened loop guards (2.5.10)
purplea6eb9fc62a03
diff --git a/src/api/__tests__/context-compaction.test.ts b/src/api/__tests__/context-compaction.test.tsindex 6d5f3c77..db0b758b 100644--- a/src/api/__tests__/context-compaction.test.ts+++ b/src/api/__tests__/context-compaction.test.ts@@ -173,3 +173,86 @@ describe('compactMessages', () => {expect(result[result.length - 1].content).toBe('latest')})})++// ── Oversized tool results (2.5.10) ────────────────────────────────+// KEEP_RECENT keeps the newest messages even over budget — before the cap,+// one giant file_read result rode along VERBATIM in every request (live+// 2026-07-26: ~225k-token prompts against a 6.5k trim target).++describe('compactMessages — oversized tool results', () => {+ const giant = 'A'.repeat(3000) + 'M'.repeat(6000) + 'Z'.repeat(3000) // 12k chars++ const history = (): OllamaChatMessage[] => [+ { role: 'system', content: 'sys' },+ { role: 'user', content: 'old '.repeat(400) },+ { role: 'assistant', content: 'old '.repeat(400) },+ { role: 'user', content: 'read it' },+ { role: 'tool', content: giant },+ { role: 'assistant', content: 'done' },+ ]++ it('caps a giant kept tool result head+tail instead of keeping it verbatim', () => {+ const messages = history()+ const result = compactMessages(messages, 150)+ const toolMsg = result.find((m) => m.role === 'tool')+ expect(toolMsg).toBeDefined()+ expect(toolMsg!.content.length).toBeLessThan(giant.length)+ expect(toolMsg!.content).toMatch(/truncated \d+ chars/)+ // Head and tail survive — that is where the signal lives.+ expect(toolMsg!.content.startsWith('AAAA')).toBe(true)+ expect(toolMsg!.content.endsWith('ZZZZ')).toBe(true)+ // The caller's array is never mutated.+ expect(messages[4].content).toBe(giant)+ })++ it('never caps user or assistant text, only tool results', () => {+ const bigUser = 'u'.repeat(9000)+ const messages: OllamaChatMessage[] = [+ { role: 'user', content: 'old '.repeat(400) },+ { role: 'assistant', content: 'old '.repeat(400) },+ { role: 'user', content: bigUser },+ { role: 'assistant', content: 'ok' },+ { role: 'user', content: 'next' },+ { role: 'assistant', content: 'sure' },+ ]+ const result = compactMessages(messages, 150)+ expect(result.some((m) => m.content === bigUser)).toBe(true)+ })++ it('touches nothing while the history is within budget', () => {+ const messages = history()+ expect(compactMessages(messages, 100000)).toEqual(messages)+ })++ it('caps Hermes-style <tool_response> results carried on user messages too', () => {+ const messages: OllamaChatMessage[] = [+ { role: 'user', content: 'old '.repeat(400) },+ { role: 'assistant', content: 'old '.repeat(400) },+ { role: 'assistant', content: 'reading' },+ { role: 'user', content: `<tool_response>${giant}</tool_response>` },+ { role: 'assistant', content: 'done' },+ { role: 'user', content: 'next' },+ ]+ const result = compactMessages(messages, 150)+ const carrier = result.find((m) => typeof m.content === 'string' && m.content.includes('<tool_response>'))+ expect(carrier).toBeDefined()+ expect(carrier!.content.length).toBeLessThan(giant.length)+ })++ it('the trim notice no longer instructs a blanket re-read', () => {+ const messages: OllamaChatMessage[] = [+ { role: 'system', content: 'sys' },+ ...Array.from({ length: 12 }, (_, i) => ({+ role: (i % 2 === 0 ? 'user' : 'assistant') as 'user' | 'assistant',+ content: `msg ${i} ${'x'.repeat(200)}`,+ })),+ ]+ const result = compactMessages(messages, 120)+ const notice = result.find((m) => m.role === 'system' && m.content.includes('trimmed to fit'))+ expect(notice).toBeDefined()+ // The old wording ("Re-read any file you still need with file_read.")+ // actively FED the re-read loop.+ expect(notice!.content).not.toContain('Re-read any file you still need')+ expect(notice!.content).toMatch(/never repeat a call/)+ })+})diff --git a/src/hooks/__tests__/useCodex-loop-detection.test.ts b/src/hooks/__tests__/useCodex-loop-detection.test.tsindex 47747aae..470f13b2 100644--- a/src/hooks/__tests__/useCodex-loop-detection.test.ts+++ b/src/hooks/__tests__/useCodex-loop-detection.test.ts@@ -1,14 +1,14 @@/**- * Smoke tests for the Codex loop-detector (Bug #5 hotfix, 2026-04-19).+ * Smoke tests for the Codex loop-detector wiring.*- * Small / 3B models (qwen2.5-coder:3b, llama3.2:1b) often get stuck- * repeating the same file_write + shell_execute batch because a test- * fails and they "fix" it by rewriting the same file. The loop detector- * aborts with a clear message when the same batch signature appears- * twice in a row.+ * Bug #5 (2026-04-19) added a consecutive-batch detector; 2.5.10 replaced it+ * with the shared AgentLoopGuard (windowed repeats, identical-read counting,+ * narration repeats — src/lib/agent-loop-guard.ts, behaviour unit-tested in+ * src/lib/__tests__/agent-loop-guard.test.ts) after Morgan's live 5-minute+ * file_read loop (2026-07-26) sailed straight past the consecutive rule.*- * These tests read the actual source so we catch accidental removal- * of the detector during refactors.+ * These tests read the actual source so we catch accidental removal of the+ * guard WIRING during refactors; the guard's logic has its own unit tests.*/import { describe, it, expect } from 'vitest'import { readFileSync } from 'fs'@@ -19,40 +19,36 @@ const __filename = fileURLToPath(import.meta.url)const __dirname = dirname(__filename)const src = readFileSync(join(__dirname, '../useCodex.ts'), 'utf8')-describe('useCodex loop-detector (Bug #5)', () => {- it('declares prevBatchSig tracking variable', () => {- expect(src).toContain('prevBatchSig')+describe('useCodex loop-detector (Bug #5 → AgentLoopGuard)', () => {+ it('instantiates the shared AgentLoopGuard for the run', () => {+ expect(src).toMatch(/new AgentLoopGuard\(\)/)+ expect(src).toContain("from '../lib/agent-loop-guard'")})- it('declares sameBatchRepeats counter', () => {- expect(src).toContain('sameBatchRepeats')+ it('feeds every batch as (name, stringified args) pairs', () => {+ expect(src).toContain('loopGuard.recordBatch(')+ expect(src).toContain('name: tc.function.name, args: JSON.stringify(tc.function.arguments)')})- it('computes batch signature from tool name + arguments, sorted', () => {- expect(src).toContain('batchSig')- expect(src).toContain("tc.function.name + ':' + JSON.stringify(tc.function.arguments)")- expect(src).toContain('.sort()')+ it('checks the narration channel too (repeated "Let me check…" lines)', () => {+ expect(src).toContain('loopGuard.recordNarration(turnContent)')})- it('halts after 2 identical repeats (total 3 matching batches)', () => {- // sameBatchRepeats >= 2 with prevBatchSig === batchSig means 3 batches in a row- expect(src).toMatch(/sameBatchRepeats\s*>=\s*2/)+ it('halts with a user-visible message and breaks the loop', () => {+ expect(src).toMatch(/halted: \$\{batchVerdict\.reason\}/)+ expect(src).toMatch(/stronger model/i)})- it('emits a user-visible halt message mentioning model size', () => {- expect(src).toMatch(/same tool sequence repeated/)- expect(src).toMatch(/larger model/i)+ it('injects the steer message into the model history', () => {+ expect(src).toMatch(/batchVerdict\.action === 'steer'/)+ expect(src).toContain("messages.push({ role: 'user', content: batchVerdict.message })")})- it('resets the repeat counter when the batch changes', () => {- expect(src).toContain('sameBatchRepeats = 0')- })-- it('checks batch signature AFTER tool calls are collected but BEFORE executing', () => {+ it('checks the guard AFTER tool calls are collected but BEFORE executing', () => {// The detector sits between "toolCalls.length === 0 break" and the// batch-building for-loop — so it catches the repeat before we burn// an execution slot and another HTTP round-trip.- const idxCheck = src.indexOf('batchSig = toolCalls')+ const idxCheck = src.indexOf('loopGuard.recordBatch(')const idxExec = src.indexOf('budget.addToolCalls(toolCalls.length)')expect(idxCheck).toBeGreaterThan(0)expect(idxExec).toBeGreaterThan(idxCheck)diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex 920653b3..f9e5f6fc 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -68,7 +68,7 @@ async function extractMemories(userMsg: string, assistantMsg: string, conversati// nothing here dropped the user's context back to Ollama's default and cost a// second model load on every single turn (seen live 2026-07-25).const numCtx = await resolveAgentNumCtx(- modelId, getProviderIdFromModel(activeModel), useSettingsStore.getState().settings.contextWindowOverride,+ modelId, getProviderIdFromModel(activeModel), useSettingsStore.getState().settings.contextWindowOverride, activeModel,)let fullResponse = ''const stream = provider.chatStream(modelId, messages, { temperature: 0.1, maxTokens: 500, contextWindow: numCtx })@@ -650,7 +650,7 @@ export function useAgentChat() {// extraction that runs after this turn sends the SAME value and Ollama// does not reload the model at its default between the two.const agentCtx: number = await resolveAgentNumCtx(- modelId, providerId, settings.contextWindowOverride,+ modelId, providerId, settings.contextWindowOverride, activeModel,)const chatOptions = {// Small-Model Mode (Knob 6): gently clamp temperature for tool turns.@@ -964,6 +964,7 @@ export function useAgentChat() {let allowImg = maxImageGen - imageGenDonelet allowVid = maxVideoGen - videoGenDonelet blocked = false+ let blockedNonMedia = falseconst kept: ToolCall[] = []for (const tc of toolCalls) {const name = tc.function.name@@ -973,6 +974,7 @@ export function useAgentChat() {if (allowVid > 0) { allowVid--; kept.push(tc) } else { blocked = true }} else if (executedCallKeys.has(callKey(tc))) {blocked = true+ blockedNonMedia = true} else {kept.push(tc)}@@ -995,10 +997,14 @@ export function useAgentChat() {id: uuid(), phase: 'reflection', content: turnContent, timestamp: Date.now(),})}+ // Tool-aware wording: telling a coding model "the media is+ // already created" when its duplicate file_read got dropped+ // reads like nonsense and derails it further.agentMessages.push({role: 'user',- content:- 'Stop, the media you were asked for is already created and shown. Write ONLY a short, friendly closing line to the user in their own language (e.g. that their picture/clip is ready). Do not output JSON, do not repeat this note, and do not call any tool.',+ content: blockedNonMedia+ ? 'Stop: you are repeating tool calls that already ran this turn — their results are shown above and have not changed. Do not call the same tool with the same arguments again. Use the results you already have and write your final answer now, without calling any tool.'+ : 'Stop, the media you were asked for is already created and shown. Write ONLY a short, friendly closing line to the user in their own language (e.g. that their picture/clip is ready). Do not output JSON, do not repeat this note, and do not call any tool.',} as ChatMessage)continue}@@ -1283,7 +1289,11 @@ export function useAgentChat() {// Small-Model Mode (Knob 3): truncate long tool outputs (head+tail)// before re-injecting into history. No-op for big models. The short// mediaNote appended at the push sites is left intact.- return settings.smallModelMode ? truncateToolResult(text) : text+ // Head+tail cap for everyone: small-model mode keeps its tight 1500+ // chars, big models get 60k (~15k tokens) so one giant tool result+ // can never ride along verbatim in every following request via+ // compaction's KEEP_RECENT window (225k-token prompts, 2026-07-26).+ return truncateToolResult(text, settings.smallModelMode ? 1500 : 60000)}// After a successful image/video gen, nudge a NATURAL closing comment so// the model doesn't silently loop another generation (David 2026-06-04).diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.tsindex dab2eb4e..a24abb6d 100644--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@ -49,8 +49,10 @@ import { selectRelevantTools, selectRelevantToolsAsync } from '../lib/tool-selecimport { generateEmbeddings } from '../api/rag'import { truncateToolResult } from '../lib/truncate-tool-result'import { compactMessages, getModelMaxTokens, estimateTokens } from '../lib/context-compaction'-import { effectiveContextWindow } from '../lib/context-window'-import { getModelContextCached } from '../api/ollama'+import { resolveAgentNumCtx } from '../lib/agent-num-ctx'+import { AgentLoopGuard } from '../lib/agent-loop-guard'+import { findStagedForPath, stagedReadResult, stagedListingNote } from '../lib/staged-overlay'+import { applyAllStagedChanges } from '../lib/staged-apply'import { useMemoryStore } from '../stores/memoryStore'import { extractMemoriesFromPair } from './useMemory'import type { OllamaChatMessage } from '../types/agent-mode'@@ -636,31 +638,27 @@ export function useCodex() {// "done" and printed a false "Task completed" (David 2026-06-04). A later// fix pinned a flat 8192 — but that hard cap throttled 32k-capable coding// models (qwen2.5-coder 32k) down to 8k AND drove compaction to trim their- // history to ~6.5k. Mirror useAgentChat (David: "muss immer stimmen"): the- // user override wins, else the model's REAL context capped for VRAM- // (effectiveContextWindow → 16384 on Ollama), floored at 8192 so a- // 4k-default model never overflows. Both the num_ctx we send and the- // compaction target below derive from this one value, so they always agree.- let numCtx: number = settings.contextWindowOverride || 8192- if (providerId === 'ollama' && !settings.contextWindowOverride) {- try {- numCtx = Math.max(effectiveContextWindow(await getModelContextCached(modelToUse), 0), 8192)- } catch {- // Keep the 8192 floor when the model's context can't be probed.- }- }+ // history to ~6.5k. Shared resolver (David: "muss immer stimmen"): the+ // user override wins, Ollama models probe their REAL context capped for+ // VRAM, and cloud models resolve their REAL window from the catalog —+ // 2.5.9 left cloud at the flat 8192, so a 262k model was trimmed to ~6.5k+ // every iteration, forgot the files it had just read, and looped on the+ // same file_read for minutes (Morgan, 2026-07-26). Both the num_ctx we+ // send and the compaction target below derive from this one value.+ const numCtx: number = await resolveAgentNumCtx(+ modelToUse, providerId, settings.contextWindowOverride, activeModel,+ )try {// Agent loop — max 20 iterations (legacy cap) AND AgentBudget cap,// whichever is tighter.- // Loop-detection: small / 3B models (qwen2.5-coder:3b, llama3.2:1b)- // often get stuck repeating the same file_write+shell_execute sequence- // because a test fails and they "fix" it by rewriting the same file.- // Track the signature of each iteration's tool-call batch; if the same- // signature appears twice in a row we abort with a clear message- // instead of burning budget on a no-op loop.- let prevBatchSig: string | null = null- let sameBatchRepeats = 0+ // Loop-detection (2.5.10, agent-loop-guard): windowed batch-signature+ // repeats, identical-read counting per mutation epoch, and repeated+ // narration. The old detector only saw the same batch 3× IN A ROW —+ // alternating calls, an injected nudge, or one varying argument reset+ // it forever while the budget allowed 200 iterations of the loop+ // (Morgan's 5-minute file_read loop, 2026-07-26).+ const loopGuard = new AgentLoopGuard()// Echo guard — small models occasionally re-emit the system prompt// ("Hello, I am the Coding Agent, an autonomous coding agent…") after a// tool error. The user asked to silence those silently rather than@@ -1156,22 +1154,26 @@ export function useCodex() {// Phase 5b (v2.4.0), parallel tool execution via tool-executor.if (!runningRef.current || abort.signal.aborted) break- // Loop-detector: compute batch signature (sorted name+args pairs).- // Two identical batches in a row → 3 means we're definitely stuck.- const batchSig = toolCalls- .map(tc => tc.function.name + ':' + JSON.stringify(tc.function.arguments))- .sort()- .join('|')- if (batchSig === prevBatchSig) {- sameBatchRepeats++- if (sameBatchRepeats >= 2) {- const msg = `\n\n_(halted: same tool sequence repeated ${sameBatchRepeats + 1}×, model is looping. Try a larger model like Qwen 3.6 for multi-step code tasks.)_`- useChatStore.getState().updateMessageContent(convId, assistantMsg.id, fullContent + msg)- break- }- } else {- sameBatchRepeats = 0- prevBatchSig = batchSig+ // Loop-detector: narration first (the same line re-emitted every+ // iteration), then the batch itself (windowed signature repeats ++ // identical reads against an unchanged workspace).+ const narrationVerdict = loopGuard.recordNarration(turnContent)+ const batchVerdict = narrationVerdict.action === 'halt'+ ? narrationVerdict+ : loopGuard.recordBatch(+ toolCalls.map((tc) => ({ name: tc.function.name, args: JSON.stringify(tc.function.arguments) })),+ )+ if (batchVerdict.action === 'halt') {+ void diagLog('loop-guard-halt', { iter: i, reason: batchVerdict.reason })+ const msg = `\n\n_(halted: ${batchVerdict.reason}. The model is looping — try a stronger model for multi-step code tasks, or rephrase the instruction.)_`+ useChatStore.getState().updateMessageContent(convId, assistantMsg.id, fullContent + msg)+ break+ }+ if (batchVerdict.action === 'steer') {+ // Let this batch still run (the in-turn cache serves it instantly),+ // but put the anti-repeat instruction in front of the NEXT turn.+ void diagLog('loop-guard-steer', { iter: i })+ messages.push({ role: 'user', content: batchVerdict.message })}type BatchEntry = { tc: typeof toolCalls[number]; ac: AgentToolCall; blockId: string; injectedArgs: Record<string, any> }@@ -1331,13 +1333,21 @@ export function useCodex() {: `${workDir.replace(/[\\/]+$/, '')}${workDir.includes('\\') ? '\\' : '/'}${path.replace(/^[\\/]+/, '')}`const stageReadCtx: { chatId?: string; workingDirectory?: string } =workDir && workDir !== '.' ? { chatId: convId, workingDirectory: workDir } : { chatId: convId }+ // A prior staged entry for this path already knows the DISK state —+ // reuse it so the reviewed diff stays disk → latest even when the+ // model writes the same file twice in one run.+ const priorWrite = findStagedForPath(useStagedChangesStore.getState().list(convId!), path)let oldContent = ''- try {- const r = await backendCall<{ content?: string }>('fs_read', { path: resolvedPath, ...stageReadCtx })- oldContent = r?.content ?? ''- } catch {- // New file — leave oldContent empty so the diff renders an- // all-add hunk and the apply path creates the file.+ if (priorWrite) {+ oldContent = priorWrite.oldContent+ } else {+ try {+ const r = await backendCall<{ content?: string }>('fs_read', { path: resolvedPath, ...stageReadCtx })+ oldContent = r?.content ?? ''+ } catch {+ // New file — leave oldContent empty so the diff renders an+ // all-add hunk and the apply path creates the file.+ }}const diff = computeUnifiedDiff(path, oldContent, newContent)useStagedChangesStore.getState().stage(convId!, {@@ -1370,15 +1380,27 @@ export function useCodex() {: `${workDir.replace(/[\\/]+$/, '')}${workDir.includes('\\') ? '\\' : '/'}${path.replace(/^[\\/]+/, '')}`const stageReadCtx: { chatId?: string; workingDirectory?: string } =workDir && workDir !== '.' ? { chatId: convId, workingDirectory: workDir } : { chatId: convId }- let oldContent = ''- try {- const r = await backendCall<{ content?: string; encoding?: string }>('fs_read', { path: resolvedPath, ...stageReadCtx })- if (r?.encoding === 'base64') return `file_edit: cannot edit a binary file (${path}).`- oldContent = r?.content ?? ''- } catch {- return `file_edit: could not read ${path}. To create a new file use file_write.`+ // Read-your-writes: chain onto the STAGED content when this path is+ // already pending. Without this the base was re-read from DISK —+ // which never saw the staged write — so a second edit to the same+ // file silently clobbered the first, and an edit to a staged NEW+ // file failed with "could not read".+ const priorEdit = findStagedForPath(useStagedChangesStore.getState().list(convId!), path)+ let baseContent = ''+ let diskContent = ''+ if (priorEdit) {+ baseContent = priorEdit.newContent+ diskContent = priorEdit.oldContent+ } else {+ try {+ const r = await backendCall<{ content?: string; encoding?: string }>('fs_read', { path: resolvedPath, ...stageReadCtx })+ if (r?.encoding === 'base64') return `file_edit: cannot edit a binary file (${path}).`+ baseContent = diskContent = r?.content ?? ''+ } catch {+ return `file_edit: could not read ${path}. To create a new file use file_write.`+ }}- const applied = applyUniqueEdit(oldContent, oldString, newString)+ const applied = applyUniqueEdit(baseContent, oldString, newString)if (!applied.ok) {switch (applied.reason) {case 'empty_old': return 'file_edit: old_string must be non-empty. Use file_write to create a new file.'@@ -1389,12 +1411,14 @@ export function useCodex() {}}const newContent = applied.content ?? ''- const diff = computeUnifiedDiff(path, oldContent, newContent)+ // Diff and oldContent stay anchored on the DISK state, so the user+ // reviews (and apply writes) disk → final, not staged → staged.+ const diff = computeUnifiedDiff(path, diskContent, newContent)useStagedChangesStore.getState().stage(convId!, {path,resolvedPath,workingDirectory: workDir && workDir !== '.' ? workDir : undefined,- oldContent,+ oldContent: diskContent,newContent,diff,})@@ -1405,6 +1429,23 @@ export function useCodex() {if (settings.codexStageMode) {if (name === 'file_write') return stageFileWrite(args)if (name === 'file_edit') return stageFileEdit(args)+ // Read-your-writes: staged content is invisible on disk, so reads+ // MUST be answered from the queue — otherwise the model reads the+ // old bytes (or a not-found), concludes its write failed, and+ // stages the same file forever (Morgan's file_read loop,+ // 2026-07-26). The in-turn cache composes correctly: every staged+ // write is audited as a file_write mutation, which invalidates+ // cached reads, so a pre-stage result is never replayed.+ const staged = convId ? useStagedChangesStore.getState().list(convId) : []+ if (staged.length > 0) {+ if (name === 'file_read') {+ const hit = findStagedForPath(staged, String(args.path ?? ''))+ if (hit) return Promise.resolve(stagedReadResult(hit))+ }+ if (name === 'file_list' || name === 'file_search') {+ return withTimeout(name, args).then((r) => r + stagedListingNote(staged))+ }+ }}return withTimeout(name, args)}@@ -1561,10 +1602,14 @@ export function useCodex() {: r.errorHint? `${r.error ?? 'Tool failed'}, ${r.errorHint}`: (r.error ?? 'Tool failed')- // Small-Model Mode (Knob 3): truncate long tool outputs (head+tail)- // before they re-enter the model history. Long results cost small- // models ~30% accuracy (LongFuncEval). No-op for big models.- return settings.smallModelMode ? truncateToolResult(text) : text+ // Head+tail truncation before results re-enter the model history.+ // Small-Model Mode (Knob 3) keeps its tight 1500-char budget (long+ // results cost small models ~30% accuracy, LongFuncEval). Big models+ // get a generous 60k-char cap (~15k tokens): uncapped, one giant+ // file_read rode along VERBATIM in every following request via+ // compaction's KEEP_RECENT window — live 225k-token prompts per+ // iteration, slow turns and a drained wallet (Morgan, 2026-07-26).+ return truncateToolResult(text, settings.smallModelMode ? 1500 : 60000)}// lu-cloud is OpenAI-compatible (DeepInfra) and STRICTLY validates the@@ -1643,6 +1688,25 @@ export function useCodex() {useChatStore.getState().updateMessageContent(convId, assistantMsg.id, fullContent)}+ // Auto-apply (2.5.10): with the user's opt-in, staged changes land on+ // disk the moment the run ends — same trusted write path as the panel's+ // Apply button, so "auto on everything" really means auto (first+ // customer feedback, Morgan 2026-07-26). Failures stay in the queue for+ // manual retry via the Pending panel.+ if (settings.codexStageMode && settings.codexAutoApply && convId) {+ const pending = useStagedChangesStore.getState().list(convId)+ if (pending.length > 0) {+ const applied = await applyAllStagedChanges(convId)+ if (applied.applied.length > 0) {+ fullContent += `\n\n_(auto-applied ${applied.applied.length} staged change${applied.applied.length === 1 ? '' : 's'}: ${applied.applied.join(', ')})_`+ }+ if (applied.failed.length > 0) {+ fullContent += `\n\n_(could not auto-apply: ${applied.failed.join(', ')} — review them in the Pending panel)_`+ }+ useChatStore.getState().updateMessageContent(convId, assistantMsg.id, fullContent)+ }+ }+// Final updatecodexStore.addEvent(convId, {id: uuid(), type: 'done', content: 'Task completed.', timestamp: Date.now(),diff --git a/src/hooks/useMemory.ts b/src/hooks/useMemory.tsindex 96461bdc..1fc76312 100644--- a/src/hooks/useMemory.ts+++ b/src/hooks/useMemory.ts@@ -96,6 +96,7 @@ export async function extractMemoriesFromPair(modelId,getProviderIdFromModel(activeModel),useSettingsStore.getState().settings.contextWindowOverride,+ activeModel,)// Collect full response via streamingdiff --git a/src/lib/__tests__/agent-loop-guard.test.ts b/src/lib/__tests__/agent-loop-guard.test.tsnew file mode 100644index 00000000..4c697a31--- /dev/null+++ b/src/lib/__tests__/agent-loop-guard.test.ts@@ -0,0 +1,110 @@+/**+ * AgentLoopGuard — the detector package built from Morgan's live loop+ * (2026-07-26): identical file_read repeated for 5 minutes plus the same+ * narration line every iteration, while the old "3 identical batches in a+ * row" rule never fired because a nudge or one varying argument reset it.+ */+import { describe, it, expect } from 'vitest'+import { AgentLoopGuard } from '../agent-loop-guard'++const read = (path: string) => ({ name: 'file_read', args: JSON.stringify({ path }) })+const write = (path: string) => ({ name: 'file_write', args: JSON.stringify({ path, content: 'x' }) })+const shell = (command: string) => ({ name: 'shell_execute', args: JSON.stringify({ command }) })++describe('AgentLoopGuard — identical reads (Morgan repro)', () => {+ it('intervenes no later than the 3rd identical file_read', () => {+ const g = new AgentLoopGuard()+ expect(g.recordBatch([read('rotation.py')]).action).toBe('ok')+ expect(g.recordBatch([read('rotation.py')]).action).toBe('ok')+ const third = g.recordBatch([read('rotation.py')])+ // The 3rd identical batch also trips the back-to-back rule — either way+ // the loop must not reach a 4th silent repetition.+ expect(['steer', 'halt']).toContain(third.action)+ })++ it('halts identical reads even when other calls vary in between', () => {+ const g = new AgentLoopGuard()+ // Interleave a DIFFERENT read each time so no batch-level rule can fire+ // on its own — this is the pattern that dodged the old guard.+ expect(g.recordBatch([read('a.py'), read('x1.py')]).action).toBe('ok')+ expect(g.recordBatch([read('a.py'), read('x2.py')]).action).toBe('ok')+ const v3 = g.recordBatch([read('a.py'), read('x3.py')])+ expect(v3.action).toBe('steer')+ expect(v3.action === 'steer' && v3.message).toMatch(/file_read 3 times/)+ expect(g.recordBatch([read('a.py'), read('x4.py')]).action).toBe('ok') // steer fires once+ const v5 = g.recordBatch([read('a.py'), read('x5.py')])+ expect(v5.action).toBe('halt')+ expect(v5.action === 'halt' && v5.reason).toMatch(/file_read repeated 5×/)+ })++ it('resets the read counters after a mutating call (re-read after change is legit)', () => {+ const g = new AgentLoopGuard()+ expect(g.recordBatch([read('a.py')]).action).toBe('ok')+ expect(g.recordBatch([read('a.py')]).action).toBe('ok')+ expect(g.recordBatch([shell('sed -i s/x/y/ a.py')]).action).toBe('ok')+ // Fresh epoch: the same read twice more is fine.+ expect(g.recordBatch([read('a.py')]).action).toBe('ok')+ expect(g.recordBatch([read('a.py')]).action).toBe('ok')+ })+})++describe('AgentLoopGuard — batch signatures', () => {+ it('halts on 3 identical batches back-to-back (old-guard parity, any tool)', () => {+ const g = new AgentLoopGuard()+ expect(g.recordBatch([write('f.py')]).action).toBe('ok')+ expect(g.recordBatch([write('f.py')]).action).toBe('ok')+ const v = g.recordBatch([write('f.py')])+ expect(v.action).toBe('halt')+ expect(v.action === 'halt' && v.reason).toMatch(/3× in a row/)+ })++ it('halts on A,B,A,B,A read alternation the consecutive rule cannot see', () => {+ const g = new AgentLoopGuard()+ expect(g.recordBatch([read('a.py')]).action).toBe('ok')+ expect(g.recordBatch([read('b.py')]).action).toBe('ok')+ expect(g.recordBatch([read('a.py')]).action).toBe('ok')+ expect(g.recordBatch([read('b.py')]).action).toBe('ok')+ const v = g.recordBatch([read('a.py')])+ expect(v.action).toBe('halt')+ expect(v.action === 'halt' && v.reason).toMatch(/no workspace change/)+ })++ it('never halts a legitimate edit → test → edit → test cycle with an identical test command', () => {+ const g = new AgentLoopGuard()+ for (let round = 0; round < 5; round++) {+ expect(g.recordBatch([write(`fix-${round}.py`)]).action).toBe('ok')+ expect(g.recordBatch([shell('npm test')]).action).toBe('ok')+ }+ })+})++describe('AgentLoopGuard — narration', () => {+ it('halts when the model repeats the same line 3× in a row', () => {+ const g = new AgentLoopGuard()+ const line = 'Let me check the rotation engine to understand how spell priorities are determined:'+ expect(g.recordNarration(line).action).toBe('ok')+ expect(g.recordNarration(line).action).toBe('ok')+ const v = g.recordNarration(line)+ expect(v.action).toBe('halt')+ expect(v.action === 'halt' && v.reason).toMatch(/repeated the same message 3×/)+ })++ it('normalizes whitespace and case before comparing', () => {+ const g = new AgentLoopGuard()+ expect(g.recordNarration('Checking the config file now').action).toBe('ok')+ expect(g.recordNarration('checking the config FILE now').action).toBe('ok')+ expect(g.recordNarration('Checking the config file now').action).toBe('halt')+ })++ it('ignores trivial short lines and resets on new content', () => {+ const g = new AgentLoopGuard()+ expect(g.recordNarration('Done.').action).toBe('ok')+ expect(g.recordNarration('Done.').action).toBe('ok')+ expect(g.recordNarration('Done.').action).toBe('ok')+ const line = 'Now updating the parser to handle nested blocks'+ expect(g.recordNarration(line).action).toBe('ok')+ expect(g.recordNarration(line).action).toBe('ok')+ expect(g.recordNarration('And now the tests for the parser change').action).toBe('ok')+ expect(g.recordNarration(line).action).toBe('ok') // streak was broken+ })+})diff --git a/src/lib/__tests__/agent-num-ctx.test.ts b/src/lib/__tests__/agent-num-ctx.test.tsindex 70858d8a..c7e975a4 100644--- a/src/lib/__tests__/agent-num-ctx.test.ts+++ b/src/lib/__tests__/agent-num-ctx.test.ts@@ -1,21 +1,30 @@import { describe, it, expect, vi, beforeEach } from 'vitest'-// The Ollama probe is the only I/O in the resolver.+// The Ollama probe and the catalog lookup are the only I/O in the resolver.vi.mock('../../api/ollama', () => ({getModelContextCached: vi.fn(),}))+vi.mock('../context-compaction', () => ({+ getModelMaxTokens: vi.fn(),+}))import { resolveAgentNumCtx } from '../agent-num-ctx'import { getModelContextCached } from '../../api/ollama'+import { getModelMaxTokens } from '../context-compaction'const probe = getModelContextCached as unknown as ReturnType<typeof vi.fn>+const catalog = getModelMaxTokens as unknown as ReturnType<typeof vi.fn>describe('resolveAgentNumCtx — one num_ctx per model, per turn', () => {- beforeEach(() => probe.mockReset())+ beforeEach(() => {+ probe.mockReset()+ catalog.mockReset()+ })it('lets an explicit override win without probing the model', async () => {expect(await resolveAgentNumCtx('qwen2.5-coder:14b', 'ollama', 32768)).toBe(32768)expect(probe).not.toHaveBeenCalled()+ expect(catalog).not.toHaveBeenCalled()})it('uses the model context capped for VRAM when there is no override', async () => {@@ -36,11 +45,31 @@ describe('resolveAgentNumCtx — one num_ctx per model, per turn', () => {// three report identically while the returned value is correct. Left// uncovered rather than shipping a red test for working code.- it('does not probe Ollama for a cloud model', async () => {+ // 2.5.10 — the Morgan bug: cloud models used to fall through to the flat+ // 8192, so a 262k model was compaction-trimmed to ~6.5k every iteration and+ // the coding agent looped on the files it kept forgetting.+ it('resolves a cloud model to its REAL window from the catalog', async () => {+ catalog.mockResolvedValue(262144)+ expect(+ await resolveAgentNumCtx('Qwen/Qwen3-Coder-480B', 'lu-cloud', 0, 'lu-cloud:Qwen/Qwen3-Coder-480B'),+ ).toBe(262144)+ // The catalog is asked with the FULL model name (prefix included) — the+ // model store indexes by it.+ expect(catalog).toHaveBeenCalledWith('lu-cloud:Qwen/Qwen3-Coder-480B')+ expect(probe).not.toHaveBeenCalled()+ })++ it('keeps the 8192 floor for a cloud model the catalog does not know', async () => {+ catalog.mockResolvedValue(4096) // getModelMaxTokens' own catch-all valueexpect(await resolveAgentNumCtx('Qwen/Qwen3-Coder-480B', 'lu-cloud', 0)).toBe(8192)expect(probe).not.toHaveBeenCalled()})+ it('keeps the floor when the catalog returns nothing usable', async () => {+ catalog.mockResolvedValue(undefined)+ expect(await resolveAgentNumCtx('some/model', 'openai', 0)).toBe(8192)+ })+// The reason this resolver exists: the chat request and the memory-extraction// request that follows it hit the SAME model, and Ollama reloads the model// whenever num_ctx changes between requests. Same inputs must give the samediff --git a/src/lib/__tests__/staged-apply.test.ts b/src/lib/__tests__/staged-apply.test.tsnew file mode 100644index 00000000..cf3e4262--- /dev/null+++ b/src/lib/__tests__/staged-apply.test.ts@@ -0,0 +1,101 @@+/**+ * staged-apply — the one trusted write path shared by the Pending panel's+ * Apply buttons and Codex auto-apply (codexAutoApply).+ */+import { describe, it, expect, vi, beforeEach } from 'vitest'++vi.mock('../../api/backend', () => ({+ backendCall: vi.fn(),+}))+const { addMessage } = vi.hoisted(() => ({ addMessage: vi.fn() }))+vi.mock('../../stores/chatStore', () => ({+ useChatStore: { getState: () => ({ addMessage }) },+}))++import { backendCall } from '../../api/backend'+import { applyStagedChange, applyAllStagedChanges } from '../staged-apply'+import { useStagedChangesStore } from '../../stores/stagedChangesStore'++const fsWrite = backendCall as unknown as ReturnType<typeof vi.fn>+const CHAT = 'chat-1'++const stage = (path: string, over: Record<string, unknown> = {}) =>+ useStagedChangesStore.getState().stage(CHAT, {+ path,+ oldContent: '',+ newContent: `content of ${path}`,+ diff: '',+ ...over,+ })++describe('applyStagedChange', () => {+ beforeEach(() => {+ fsWrite.mockReset()+ addMessage.mockClear()+ useStagedChangesStore.getState().clear(CHAT)+ })++ it('writes via fs_write with the stage-time jail root and dequeues the entry', async () => {+ fsWrite.mockResolvedValue({ status: 'saved', path: '/proj/gui.py' })+ stage('gui.py', { resolvedPath: '/proj/gui.py', workingDirectory: '/proj' })+ const change = useStagedChangesStore.getState().list(CHAT)[0]++ await applyStagedChange(CHAT, change)++ expect(fsWrite).toHaveBeenCalledWith('fs_write', {+ path: '/proj/gui.py',+ content: 'content of gui.py',+ chatId: CHAT,+ workingDirectory: '/proj',+ })+ expect(useStagedChangesStore.getState().list(CHAT)).toHaveLength(0)+ expect(addMessage).toHaveBeenCalledOnce()+ })++ it('treats "unchanged" as success but throws on any other status, keeping the entry', async () => {+ fsWrite.mockResolvedValue({ status: 'unchanged', path: '/p/a.py' })+ stage('a.py')+ await applyStagedChange(CHAT, useStagedChangesStore.getState().list(CHAT)[0])+ expect(useStagedChangesStore.getState().list(CHAT)).toHaveLength(0)++ fsWrite.mockResolvedValue({ status: 'denied' })+ stage('b.py')+ const bad = useStagedChangesStore.getState().list(CHAT)[0]+ await expect(applyStagedChange(CHAT, bad)).rejects.toThrow(/denied/)+ expect(useStagedChangesStore.getState().list(CHAT)).toHaveLength(1)+ })+})++describe('applyAllStagedChanges', () => {+ beforeEach(() => {+ fsWrite.mockReset()+ addMessage.mockClear()+ useStagedChangesStore.getState().clear(CHAT)+ })++ it('applies everything and reports the paths', async () => {+ fsWrite.mockResolvedValue({ status: 'saved' })+ stage('one.py')+ stage('two.py')+ const res = await applyAllStagedChanges(CHAT)+ expect(res.applied.sort()).toEqual(['one.py', 'two.py'])+ expect(res.failed).toEqual([])+ expect(useStagedChangesStore.getState().list(CHAT)).toHaveLength(0)+ })++ it('one failing write never blocks the rest — it stays queued and is reported', async () => {+ stage('good.py')+ stage('bad.py')+ fsWrite.mockImplementation((_cmd: string, args: { path: string }) =>+ args.path.includes('bad')+ ? Promise.reject(new Error('disk full'))+ : Promise.resolve({ status: 'saved' }),+ )+ const res = await applyAllStagedChanges(CHAT)+ expect(res.applied).toEqual(['good.py'])+ expect(res.failed).toEqual(['bad.py'])+ const left = useStagedChangesStore.getState().list(CHAT)+ expect(left).toHaveLength(1)+ expect(left[0].path).toBe('bad.py')+ })+})diff --git a/src/lib/__tests__/staged-overlay.test.ts b/src/lib/__tests__/staged-overlay.test.tsnew file mode 100644index 00000000..58ba6e51--- /dev/null+++ b/src/lib/__tests__/staged-overlay.test.ts@@ -0,0 +1,77 @@+/**+ * Read-your-writes overlay for Stage-and-Approve — the fix for Morgan's loop+ * (2026-07-26): staged writes were invisible to file_read, so the model+ * re-read stale disk bytes, concluded the write failed, and staged the same+ * file forever.+ */+import { describe, it, expect } from 'vitest'+import {+ normalizeStagedPath,+ findStagedForPath,+ stagedReadResult,+ stagedListingNote,+} from '../staged-overlay'+import type { StagedChange } from '../../stores/stagedChangesStore'++const change = (over: Partial<StagedChange>): StagedChange => ({+ id: 'id-1',+ path: 'gui.py',+ oldContent: '',+ newContent: 'print("hi")\n',+ diff: '',+ stagedAt: 0,+ ...over,+})++describe('normalizeStagedPath', () => {+ it('strips ./, unifies slashes, drops trailing slash', () => {+ expect(normalizeStagedPath('./src/gui.py')).toBe('src/gui.py')+ expect(normalizeStagedPath('src\\gui.py')).toBe('src/gui.py')+ expect(normalizeStagedPath('src/dir/')).toBe('src/dir')+ })++ it('compares Windows drive paths case-insensitively, Unix paths not', () => {+ expect(normalizeStagedPath('C:\\Proj\\GUI.py')).toBe('c:/proj/gui.py')+ expect(normalizeStagedPath('/home/User/GUI.py')).toBe('/home/User/GUI.py')+ })+})++describe('findStagedForPath', () => {+ const list = [+ change({ id: '1', path: 'gui.py', resolvedPath: '/proj/wow-bot/gui.py' }),+ change({ id: '2', path: 'src/main.py' }),+ ]++ it('matches the path the model wrote with', () => {+ expect(findStagedForPath(list, 'gui.py')?.id).toBe('1')+ expect(findStagedForPath(list, './src/main.py')?.id).toBe('2')+ })++ it('matches the workspace-resolved absolute path too', () => {+ expect(findStagedForPath(list, '/proj/wow-bot/gui.py')?.id).toBe('1')+ })++ it('returns undefined for unknown or empty paths', () => {+ expect(findStagedForPath(list, 'other.py')).toBeUndefined()+ expect(findStagedForPath(list, '')).toBeUndefined()+ })+})++describe('stagedReadResult / stagedListingNote', () => {+ it('serves the staged content first, with a pending marker', () => {+ const out = stagedReadResult(change({ newContent: 'CONTENT-42' }))+ expect(out.startsWith('CONTENT-42')).toBe(true)+ expect(out).toMatch(/NOT on disk yet/)+ })++ it('lists every pending path once, and is empty without staged changes', () => {+ const note = stagedListingNote([+ change({ id: '1', path: 'gui.py' }),+ change({ id: '2', path: 'main.py' }),+ ])+ expect(note).toContain('gui.py')+ expect(note).toContain('main.py')+ expect(note).toMatch(/pending user approval/)+ expect(stagedListingNote([])).toBe('')+ })+})diff --git a/src/lib/agent-loop-guard.ts b/src/lib/agent-loop-guard.tsnew file mode 100644index 00000000..0b4c906e--- /dev/null+++ b/src/lib/agent-loop-guard.ts@@ -0,0 +1,166 @@+/**+ * Loop guard for the agent ReAct loops (Codex + Chat agent).+ *+ * Born from a live failure (Morgan, 2026-07-26): the coding agent repeated+ * the same file_read and the same narration line for 5 minutes. The old+ * detector only halted on the same batch signature 3× IN A ROW — alternating+ * batches, an injected nudge, or one varying argument reset the counter every+ * time, so a real loop never tripped it while the budget allowed 200+ * iterations of it.+ *+ * Four complementary detectors, all pure and cheap. The dividing line is the+ * mutation epoch: any side-effecting call (shell, write, git mutation) may+ * change what the next identical call returns, so repeat detection that spans+ * a mutation would punish legitimate edit → test → edit → test cycles. Every+ * epoch-scoped counter therefore resets on a mutating batch.+ *+ * 1. Identical batches back-to-back (old-guard parity, any tool class):+ * 3 in a row halts. Survives mutations on purpose — three byte-identical+ * batches with nothing else between them is a stall even for shell.+ *+ * 2. Windowed signatures among PURE-READ batches: the same signature 3×+ * within the last 6 read-only batches halts, consecutive or not. Catches+ * the A,B,A,B,A alternation that detector 1 can never see.+ *+ * 3. Identical read calls within an epoch: a repeated read with+ * byte-identical arguments cannot return new information while the+ * workspace is unchanged. The 3rd identical read steers the model once,+ * the 5th halts.+ *+ * 4. Repeated narration: the model emitting the same non-trivial text 3×+ * in a row ("Let me check the rotation engine…") halts even when its+ * tool calls vary enough to dodge 1-3.+ */++export type LoopGuardVerdict =+ | { action: 'ok' }+ | { action: 'steer'; message: string }+ | { action: 'halt'; reason: string }++const CONSECUTIVE_HALT_AT = 3+const BATCH_WINDOW = 6+const WINDOW_HALT_REPEATS = 3+const READ_STEER_AT = 3+const READ_HALT_AT = 5+const NARRATION_HALT_AT = 3+/** Ignore trivial repeated lines ("Done.", "ok") — too easy to hit honestly. */+const MIN_NARRATION_LEN = 12++/**+ * Tools whose result is a pure function of the workspace state. Only these+ * feed the epoch-scoped repeat counters; everything else (shell, writes, web,+ * time) may legitimately repeat and instead RESETS the epoch.+ */+const READ_ONLY_TOOLS = new Set<string>([+ 'file_read',+ 'file_list',+ 'file_search',+ 'git_status',+ 'git_log',+ 'git_diff',+])++export class AgentLoopGuard {+ private lastSig: string | null = null+ private consecutive = 0+ /** Batch signatures since the last mutating batch (pure-read epoch). */+ private pureWindow: string[] = []+ private readCounts = new Map<string, number>()+ private steeredKeys = new Set<string>()+ private lastNarration = ''+ private narrationSeen = 0++ /**+ * Record one iteration's tool-call batch BEFORE executing it. `args` must+ * be the serialized (stringified) arguments so identity is byte-exact —+ * the same convention the in-turn cache uses.+ */+ recordBatch(calls: Array<{ name: string; args: string }>): LoopGuardVerdict {+ if (calls.length === 0) return { action: 'ok' }+ const keys = calls.map((c) => `${c.name}|${c.args}`)+ const sig = [...keys].sort().join('||')++ // (1) Back-to-back identical batches, any tool class.+ if (sig === this.lastSig) {+ this.consecutive+++ } else {+ this.lastSig = sig+ this.consecutive = 1+ }+ if (this.consecutive >= CONSECUTIVE_HALT_AT) {+ return { action: 'halt', reason: `same tool sequence repeated ${this.consecutive}× in a row` }+ }++ const hasMutation = calls.some((c) => !READ_ONLY_TOOLS.has(c.name))++ // (2) Windowed repeats among pure-read batches (alternation).+ if (!hasMutation) {+ this.pureWindow.push(sig)+ if (this.pureWindow.length > BATCH_WINDOW) this.pureWindow.shift()+ const repeats = this.pureWindow.filter((s) => s === sig).length+ if (repeats >= WINDOW_HALT_REPEATS) {+ return {+ action: 'halt',+ reason: `same tool sequence repeated ${repeats}× within the last ${this.pureWindow.length} steps with no workspace change`,+ }+ }+ }++ // (3) Identical read calls within the epoch.+ let steer: LoopGuardVerdict | null = null+ for (let i = 0; i < calls.length; i++) {+ if (!READ_ONLY_TOOLS.has(calls[i].name)) continue+ const n = (this.readCounts.get(keys[i]) ?? 0) + 1+ this.readCounts.set(keys[i], n)+ if (n >= READ_HALT_AT) {+ return {+ action: 'halt',+ reason: `${calls[i].name} repeated ${n}× with identical arguments and an unchanged workspace`,+ }+ }+ if (n >= READ_STEER_AT && !this.steeredKeys.has(keys[i])) {+ this.steeredKeys.add(keys[i])+ steer = {+ action: 'steer',+ message:+ `You have now called ${calls[i].name} ${n} times with exactly the same arguments. ` ++ 'Nothing changed in between, so the result is identical to the one you already have. ' ++ 'Do NOT repeat this call again. Use the result from before, or take a DIFFERENT action that moves the task forward.',+ }+ }+ }++ if (hasMutation) {+ // A side-effecting call may change what reads return — give the+ // epoch-scoped counters a clean slate so a legitimate re-read after a+ // change is never punished. steeredKeys survives: one steer per unique+ // call is enough for the whole run.+ this.readCounts.clear()+ this.pureWindow = []+ }+ return steer ?? { action: 'ok' }+ }++ /** Record the assistant text of one iteration (before its tools run). */+ recordNarration(text: string): LoopGuardVerdict {+ const norm = text.trim().replace(/\s+/g, ' ').toLowerCase()+ if (norm.length < MIN_NARRATION_LEN) {+ this.lastNarration = ''+ this.narrationSeen = 0+ return { action: 'ok' }+ }+ if (norm === this.lastNarration) {+ this.narrationSeen+++ } else {+ this.lastNarration = norm+ this.narrationSeen = 1+ }+ if (this.narrationSeen >= NARRATION_HALT_AT) {+ return {+ action: 'halt',+ reason: `the model repeated the same message ${this.narrationSeen}× without making progress`,+ }+ }+ return { action: 'ok' }+ }+}diff --git a/src/lib/agent-num-ctx.ts b/src/lib/agent-num-ctx.tsindex 2f90f0b0..7777dc8b 100644--- a/src/lib/agent-num-ctx.ts+++ b/src/lib/agent-num-ctx.ts@@ -16,26 +16,46 @@import { getModelContextCached } from '../api/ollama'import { effectiveContextWindow } from './context-window'+import { getModelMaxTokens } from './context-compaction'/**- * @param modelId provider-local model id (already stripped of any prefix)- * @param providerId 'ollama' | 'openai' | 'lu-cloud' | …- * @param override the user's contextWindowOverride (0 = none)+ * @param modelId provider-local model id (already stripped of any prefix)+ * @param providerId 'ollama' | 'openai' | 'lu-cloud' | …+ * @param override the user's contextWindowOverride (0 = none)+ * @param fullModelName the UNstripped model name ('lu-cloud:Qwen/…') — needed+ * to resolve a cloud model's real window from the catalog** The override wins outright. Without one, Ollama models get their REAL context* capped for VRAM, floored at 8192 so feeding a generated image back for vision* feedback never overflows a 4096-default model.+ *+ * Cloud models resolve their REAL window from the model catalog. They used to+ * fall through to the flat 8192 — there is no KV-cache/VRAM cost on our side,+ * but the compaction budget derives from this value, so a 262k cloud model was+ * trimmed to ~6.5k every iteration. The model "forgot" the files it had just+ * read, the trim notice told it to re-read them, and the coding agent looped+ * on the same file_read for minutes (Morgan, 2026-07-26).*/export async function resolveAgentNumCtx(modelId: string,providerId: string,override: number | undefined,+ fullModelName?: string,): Promise<number> {let ctx: number = override || 8192- if (providerId === 'ollama' && !override) {- try {- ctx = Math.max(effectiveContextWindow(await getModelContextCached(modelId), 0), 8192)- } catch { /* keep the 8192 floor on failure */ }+ if (!override) {+ if (providerId === 'ollama') {+ try {+ ctx = Math.max(effectiveContextWindow(await getModelContextCached(modelId), 0), 8192)+ } catch { /* keep the 8192 floor on failure */ }+ } else {+ try {+ const real = await getModelMaxTokens(fullModelName ?? modelId)+ if (typeof real === 'number' && Number.isFinite(real) && real > 0) {+ ctx = Math.max(real, 8192)+ }+ } catch { /* keep the 8192 floor on failure */ }+ }}return ctx}diff --git a/src/lib/constants.ts b/src/lib/constants.tsindex c402e55e..dc12393f 100644--- a/src/lib/constants.ts+++ b/src/lib/constants.ts@@ -69,6 +69,7 @@ export const DEFAULT_SETTINGS: Settings = {codexRepoMapEnabled: false,codexRepoMapLimit: 20,codexStageMode: false,+ codexAutoApply: false,codexReviewMode: false,// H2 security gate. OFF by default = the autonomous coding agent keeps// running shell/code unattended; ON pauses each exec for a confirm.diff --git a/src/lib/context-compaction.ts b/src/lib/context-compaction.tsindex 78cebd73..8eccd4de 100644--- a/src/lib/context-compaction.ts+++ b/src/lib/context-compaction.ts@@ -11,6 +11,7 @@import { getModelContext } from '../api/ollama'import { getProviderForModel, getProviderIdFromModel } from '../api/providers'import { useModelStore } from '../stores/modelStore'+import { truncateToolResult } from './truncate-tool-result'import type { OllamaChatMessage } from '../types/agent-mode'// ── Token Estimation ────────────────────────────────────────────@@ -125,15 +126,29 @@ export function compactMessages(const systemTokens = systemMsg ? estimateMessageTokens([systemMsg]) : 0const budget = Math.max(0, maxTokens - systemTokens)+ // Cap oversized TOOL RESULTS before fitting the suffix. KEEP_RECENT below+ // keeps the newest messages even when they exceed the budget — without this+ // cap a single giant file_read result rode along VERBATIM in every request+ // (live 2026-07-26: ~225k-token prompts against a 6.5k trim target, every+ // iteration slow and expensive). Only tool results are capped; user and+ // assistant text is never touched. The cap adapts to the budget (chars ≈+ // tokens × 4), floored so tiny budgets still keep a useful head+tail.+ const perResultCap = Math.max(4000, Math.min(32000, Math.floor(budget * 4 * 0.35)))+ const capped = nonSystem.map((m) =>+ isToolResultMessage(m) && typeof m.content === 'string' && m.content.length > perResultCap+ ? { ...m, content: truncateToolResult(m.content, perResultCap) }+ : m,+ )+// Accumulate a recent suffix that fits, newest-first. Keep at least// KEEP_RECENT messages even when that exceeds budget (recent context is the// most valuable), otherwise stop as soon as the next message would overflow.const kept: OllamaChatMessage[] = []let used = 0- for (let i = nonSystem.length - 1; i >= 0; i--) {- const t = estimateMessageTokens([nonSystem[i]])+ for (let i = capped.length - 1; i >= 0; i--) {+ const t = estimateMessageTokens([capped[i]])if (used + t > budget && kept.length >= KEEP_RECENT) break- kept.unshift(nonSystem[i])+ kept.unshift(capped[i])used += t}@@ -143,13 +158,17 @@ export function compactMessages(kept.shift()}- const droppedCount = nonSystem.length - kept.length+ const droppedCount = capped.length - kept.lengthconst compacted: OllamaChatMessage[] = []if (systemMsg) compacted.push(systemMsg)if (droppedCount > 0) {+ // Wording matters here: the old notice ("Re-read any file you still need+ // with file_read.") actively FED a re-read loop — every iteration the+ // model was told to read again what it had just read. Keep the honest+ // recovery path but make it single-shot and anti-repeat.compacted.push({role: 'system',- content: `[${droppedCount} earlier message${droppedCount === 1 ? '' : 's'} were trimmed to fit the context window. Re-read any file you still need with file_read.]`,+ content: `[${droppedCount} earlier message${droppedCount === 1 ? '' : 's'} were trimmed to fit the context window. Results you already saw still hold. If a detail is genuinely missing, re-read that specific file once; never repeat a call that already ran.]`,})}compacted.push(...kept)diff --git a/src/lib/settings-reset.ts b/src/lib/settings-reset.tsindex d12b4d5a..083090ee 100644--- a/src/lib/settings-reset.ts+++ b/src/lib/settings-reset.ts@@ -25,7 +25,7 @@ export const SETTINGS_TAB_RESET_KEYS: Record<SettingsTab, (keyof Settings)[]> ='agentMaxToolCalls', 'agentMaxIterations','searchProvider', 'braveApiKey', 'tavilyApiKey','codexArchitectMode', 'codexArchitectModel', 'codexArchitectAllowCloud',- 'codexRepoMapEnabled', 'codexRepoMapLimit', 'codexStageMode', 'codexReviewMode',+ 'codexRepoMapEnabled', 'codexRepoMapLimit', 'codexStageMode', 'codexAutoApply', 'codexReviewMode',],'voice-remote': [],}diff --git a/src/lib/staged-apply.ts b/src/lib/staged-apply.tsnew file mode 100644index 00000000..0b24cd99--- /dev/null+++ b/src/lib/staged-apply.ts@@ -0,0 +1,62 @@+/**+ * Applying staged changes to disk — shared by the StagedChangesPanel buttons+ * and Codex auto-apply (settings.codexAutoApply), so both paths write through+ * the exact same trusted call.+ *+ * Writes go via fs_write DIRECTLY, not the `file_write` model tool. Two+ * reasons: (1) by apply time the loop's finally may have cleared the active+ * chat/workspace, so file_write's chatCtx() is empty and the write would jail+ * to agent-workspace/default — rejecting the absolute project path. (2)+ * file_write deliberately does NOT let its caller pick the jail root (2.5.7+ * security review: a prompt-injected model could set workingDirectory to+ * escape the sandbox). Apply is a trusted, user-gated action, so it is safe+ * to pass the workspace root captured at stage time as the jail root.+ */++import { backendCall } from '../api/backend'+import { useStagedChangesStore, type StagedChange } from '../stores/stagedChangesStore'+import { useChatStore } from '../stores/chatStore'++export async function applyStagedChange(chatId: string, change: StagedChange): Promise<void> {+ const res = await backendCall<{ status?: string; path?: string }>('fs_write', {+ path: change.resolvedPath || change.path,+ content: change.newContent,+ chatId,+ workingDirectory: change.workingDirectory,+ })+ // 'saved' and 'unchanged' are both success ('unchanged' = the file already+ // matched byte-for-byte). Anything else is a real failure worth retrying.+ if (res?.status && res.status !== 'saved' && res.status !== 'unchanged') {+ throw new Error(`fs_write returned status "${res.status}"`)+ }+ useStagedChangesStore.getState().remove(chatId, change.id)+ // Mirror the apply in the chat log so the user sees a confirmation in the+ // main pane, not just the side-pane entry disappearing.+ useChatStore.getState().addMessage(chatId, {+ id: crypto.randomUUID(),+ role: 'system',+ content: `Applied staged change: ${change.path}`,+ timestamp: Date.now(),+ hidden: true,+ })+}++/** Apply every pending change for a chat, sequentially (fs_write serializes+ * per path anyway). Failures stay in the queue for manual retry and are+ * reported by path instead of throwing, so one bad write never blocks the+ * rest. */+export async function applyAllStagedChanges(+ chatId: string,+): Promise<{ applied: string[]; failed: string[] }> {+ const applied: string[] = []+ const failed: string[] = []+ for (const change of [...useStagedChangesStore.getState().list(chatId)]) {+ try {+ await applyStagedChange(chatId, change)+ applied.push(change.path)+ } catch {+ failed.push(change.path)+ }+ }+ return { applied, failed }+}diff --git a/src/lib/staged-overlay.ts b/src/lib/staged-overlay.tsnew file mode 100644index 00000000..b768a5b5--- /dev/null+++ b/src/lib/staged-overlay.ts@@ -0,0 +1,56 @@+/**+ * Read-your-writes for Stage-and-Approve (codexStageMode).+ *+ * Staged file_write / file_edit calls never touch the disk — they sit in+ * stagedChangesStore until the user applies them. Without an overlay the+ * model's next file_read went to the DISK, found nothing (or the old bytes),+ * concluded its write failed, and staged the same file again, forever+ * (Morgan, 2026-07-26: a 5-minute file_read loop with three pending files).+ * These helpers answer reads from the staging queue instead, so the model+ * always sees its own pending work.+ */++import type { StagedChange } from '../stores/stagedChangesStore'++/** Normalize for comparison: forward slashes, no leading "./", no trailing "/". */+export function normalizeStagedPath(p: string): string {+ let out = String(p ?? '').trim().replace(/\\/g, '/')+ out = out.replace(/^\.\//, '')+ out = out.replace(/\/+$/, '')+ // Windows paths compare case-insensitively (same rule as side-effect-key).+ const isWindowsLike = /^[A-Za-z]:\//.test(out) || out.startsWith('//')+ return isWindowsLike ? out.toLowerCase() : out+}++/** The staged entry a read of `path` must see, if any. Matches the path the+ * model wrote with AND the workspace-resolved absolute path. */+export function findStagedForPath(+ list: readonly StagedChange[],+ path: string,+): StagedChange | undefined {+ const target = normalizeStagedPath(path)+ if (!target) return undefined+ return list.find(+ (c) =>+ normalizeStagedPath(c.path) === target ||+ (c.resolvedPath ? normalizeStagedPath(c.resolvedPath) === target : false),+ )+}++/** file_read payload for a staged path: the pending content, plus a short+ * marker so the model does not stage the identical bytes again. */+export function stagedReadResult(change: StagedChange): string {+ return (+ `${change.newContent}\n\n` ++ `[staged: this is your own pending version of ${change.path}. ` ++ 'It is queued for user approval and NOT on disk yet. Do not write the same content again.]'+ )+}++/** Suffix for file_list / file_search results so pending files stay+ * discoverable even though the disk does not have them yet. */+export function stagedListingNote(list: readonly StagedChange[]): string {+ if (list.length === 0) return ''+ const names = list.map((c) => c.path).join(', ')+ return `\n\n[staged, pending user approval (not on disk yet): ${names}. Use file_read to see their staged content.]`+}diff --git a/src/lib/truncate-tool-result.ts b/src/lib/truncate-tool-result.tsindex ab3777ba..1ec912ab 100644--- a/src/lib/truncate-tool-result.ts+++ b/src/lib/truncate-tool-result.ts@@ -1,5 +1,5 @@/**- * Tool-output truncation for Small-Model Mode (Knob 3).+ * Head+tail tool-output truncation.** Long tool responses measurably hurt small models: in IBM's LongFuncEval* (arXiv 2505.10570) a long tool output cost Granite-3.1-8B ~30% AST accuracy,@@ -8,8 +8,13 @@* file_read, a verbose build log), keep the HEAD and the TAIL — where the* signal usually lives — and drop the middle with a marker.*- * Big-model behaviour is unchanged: callers only apply this when- * settings.smallModelMode is on.+ * Three callers, three budgets:+ * - Small-Model Mode (Knob 3): tight 1500-char default.+ * - Big models: a generous 60k-char cap where results enter history. Uncapped,+ * one giant file_read result rode along VERBATIM in every following request+ * via compaction's KEEP_RECENT window — live prompts of ~225k tokens per+ * iteration, slow turns and a drained credit wallet (Morgan, 2026-07-26).+ * - compactMessages: a budget-adaptive cap on tool results it keeps.*/export function truncateToolResult(text: string, maxChars = 1500): string {if (typeof text !== 'string') return text as unknown as string@@ -22,5 +27,5 @@ export function truncateToolResult(text: string, maxChars = 1500): string {const head = text.slice(0, headChars)const tail = tailChars > 0 ? text.slice(text.length - tailChars) : ''const dropped = text.length - head.length - tail.length- return `${head}\n\n…[truncated ${dropped} chars for small-model mode]…\n\n${tail}`+ return `${head}\n\n…[truncated ${dropped} chars]…\n\n${tail}`}diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.tsindex 5c9b6902..6bb2fcd2 100644--- a/src/stores/settingsStore.ts+++ b/src/stores/settingsStore.ts@@ -46,7 +46,10 @@ import { DEFAULT_SETTINGS, BUILT_IN_PERSONAS } from '../lib/constants'// keeps the field undefined and the Settings number box renders empty, which// is how this was caught on the ship exe (2026-07-25). Behaviour was already// correct via `?? 0`; this is so the UI shows the real value.-const STORE_VERSION = 16+// v17 (2.5.10): added settings.codexAutoApply (default false) — auto-apply+// staged changes when the run finishes. Additive merge backfills the default;+// stage-mode behaviour is unchanged until the user turns the new switch on.+const STORE_VERSION = 17interface SettingsState {settings: Settingsdiff --git a/src/types/settings.ts b/src/types/settings.tsindex a43a9927..883c98a1 100644--- a/src/types/settings.ts+++ b/src/types/settings.ts@@ -161,6 +161,13 @@ export interface Settings {* applies (or rejects) per-file.*/codexStageMode: boolean+ /**+ * Auto-apply staged changes when the run finishes. Only meaningful while+ * codexStageMode is on: every diff is still recorded and visible, but the+ * user is not asked to click Apply per file — "auto on everything" then+ * really means auto (first customer feedback, Morgan 2026-07-26).+ */+ codexAutoApply: boolean/*** Code-Review mode. When on, Codex runs read-only — every `file_write`* and `shell_execute`-style call is blocked with a friendly message and