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): Anthropic tool batches, stalled streams, and the caches a long run pays for
purplec0d388516c90
diff --git a/src-tauri/src/commands/remote.rs b/src-tauri/src/commands/remote.rsindex 31b004b0..3819c05b 100644--- a/src-tauri/src/commands/remote.rs+++ b/src-tauri/src/commands/remote.rs@@ -545,6 +545,32 @@ enum ToolGate {/// which is the same "look at what this person is doing" class as `screenshot`,/// and screenshot was gated. With the default flipped, a tool added to the/// dispatch without a decision here is refused instead of silently exposed.+/// Line window for `file_read` (audit C1) — mirror of the desktop+/// `sliceFileReadResult`, so the relay and the app answer the same contract.+/// No offset and no limit returns the content untouched.+fn slice_file_read(content: &str, offset: Option<u64>, limit: Option<u64>) -> String {+ if offset.unwrap_or(0) == 0 && limit.unwrap_or(0) == 0 {+ return content.to_string();+ }+ let lines: Vec<&str> = content.split('\n').collect();+ let total = lines.len();+ let start = offset.filter(|o| *o > 0).unwrap_or(1).min(total as u64 + 1) as usize;+ let count = limit.filter(|l| *l > 0).map(|l| l as usize).unwrap_or(total);+ let window: Vec<&str> = lines.iter().skip(start - 1).take(count).copied().collect();+ let end = start + window.len() - if window.is_empty() { 0 } else { 1 };+ let mut out = format!("[lines {}-{} of {}]\n{}", start, end, total, window.join("\n"));+ if end < total {+ let rest = total - end;+ out.push_str(&format!(+ "\n[{} more line{} — call file_read again with offset: {}]",+ rest,+ if rest == 1 { "" } else { "s" },+ end + 1+ ));+ }+ out+}+fn gate_for(tool: &str) -> ToolGate {match tool {// RCE-equivalent: gated behind the dedicated, default-OFF `shell`@@ -646,7 +672,18 @@ async fn handle_agent_tool("file_read" => {let path = body.args.get("path").and_then(|v| v.as_str()).unwrap_or("").to_string();if path.is_empty() { Err("file_read needs a non-empty `path` argument.".into()) }- else { crate::commands::agent::file_read(path, chat_id.clone(), app_state.clone()) }+ else {+ // Windowed read parity with the desktop tool (audit C1): the+ // relay serves the same tool contract, so offset/limit have to+ // page here too or a mobile agent reads a 5000-line file whole.+ let offset = body.args.get("offset").and_then(|v| v.as_u64());+ let limit = body.args.get("limit").and_then(|v| v.as_u64());+ crate::commands::agent::file_read(path, chat_id.clone(), app_state.clone())+ .map(|v| {+ let text = v.get("content").and_then(|c| c.as_str()).unwrap_or("");+ serde_json::json!({ "content": slice_file_read(text, offset, limit) })+ })+ }}"file_write" => {let path = body.args.get("path").and_then(|v| v.as_str()).unwrap_or("").to_string();@@ -2148,8 +2185,10 @@ button{-webkit-appearance:none;appearance:none}{name:'web_fetch', description:'Fetch a single URL and return its readable text (up to ~24 000 chars). Strips <script>, <style>, <nav>, <header>, <footer>, <aside>, <form> — returns main content only. PREFER this over web_search when you already know the target URL. NEVER call with localhost, private IPs (10.*, 192.168.*, 172.16-31.*), or file:// — they are refused. If response is empty or 4xx, try a different URL rather than retrying the same one.',parameters:[{name:'url',type:'string',description:'Full URL including protocol (http:// or https://)',required:true},{name:'maxLength',type:'number',description:'Max chars to return (default: 24000)',required:false}]},- {name:'file_read', description:'Read the complete contents of a file. PREFER absolute paths; relative paths resolve against the agent workspace (~/agent-workspace). The entire file is returned — there is no pagination or range parameter. DO NOT re-read a file you just wrote with file_write; the write response already confirmed the save. For directory listings use file_list; for content search across many files use file_search.',- parameters:[{name:'path',type:'string',description:'Path to the file (absolute preferred)',required:true}]},+ {name:'file_read', description:'Read a file. PREFER absolute paths; relative paths resolve against the agent workspace (~/agent-workspace). Omitting offset/limit returns the whole file. For LARGE files pass offset (1-based start line) and limit (number of lines) to read a window — the response names the window and the total line count, and tells you the offset for the next page. Very long whole-file reads get their middle truncated, so page large files. DO NOT re-read a file you just wrote with file_write; the write response already confirmed the save. For directory listings use file_list; for content search across many files use file_search.',+ parameters:[{name:'path',type:'string',description:'Path to the file (absolute preferred)',required:true},+ {name:'offset',type:'number',description:'1-based line to start reading from (optional)',required:false},+ {name:'limit',type:'number',description:'Maximum number of lines to return (optional)',required:false}]},{name:'file_write', description:'Write a WHOLE file. Use for CREATING a new file or fully replacing one. To change part of an EXISTING file, PREFER file_edit — it is far cheaper than resending the whole file and never truncates a large one. Creates parent directories if missing. OVERWRITES existing content — there is NO append mode. PREFER absolute paths. Writes to the same path within one turn are serialized automatically via the sideEffectKey scheduler.',parameters:[{name:'path',type:'string',description:'Path to the file (absolute preferred)',required:true},{name:'content',type:'string',description:'The complete new content of the file',required:true}]},diff --git a/src/api/agents/repo-map.ts b/src/api/agents/repo-map.tsindex ddd3ffe8..8519c788 100644--- a/src/api/agents/repo-map.ts+++ b/src/api/agents/repo-map.ts@@ -18,15 +18,30 @@ export interface FetchRepoMapInput {signal?: AbortSignal}+/**+ * Short-lived result cache (audit E4). The Bridge walk visits up to 20k+ * files and parses up to 512 KiB each — and it ran on EVERY instruction,+ * including the follow-up sent twenty seconds after the last one. A repo's+ * import graph does not change meaningfully inside a minute; an agent run+ * that edits files invalidates through the normal TTL expiry.+ */+const REPO_MAP_TTL_MS = 60_000+const repoMapCache = new Map<string, { at: number; result: RepoMapResult }>()+/*** Calls the Bridge `repo_map` command. The Bridge walks the working* directory, parses imports, runs PageRank, and returns the top-N ranked- * files. Pure I/O — no caching; the caller decides when to refresh.+ * files.*/export async function fetchRepoMap(input: FetchRepoMapInput): Promise<RepoMapResult> {if (!input.workingDirectory) {return { files: [], count: 0 }}+ const cacheKey = `${input.workingDirectory}|${input.query ?? ''}|${input.limit ?? 20}`+ const hit = repoMapCache.get(cacheKey)+ if (hit && Date.now() - hit.at < REPO_MAP_TTL_MS) {+ return hit.result+ }// The Rust `repo_map` command takes a SINGLE `args: serde_json::Value` param// (deserialized into RepoMapArgs) — so the payload MUST be wrapped in// `{ args: … }`. Sending the fields top-level makes Tauri reject the call@@ -40,10 +55,12 @@ export async function fetchRepoMap(input: FetchRepoMapInput): Promise<RepoMapReslimit: input.limit ?? 20,},})- return {+ const result = {files: Array.isArray(out.files) ? out.files : [],count: typeof out.count === 'number' ? out.count : 0,}+ repoMapCache.set(cacheKey, { at: Date.now(), result })+ return result}/**diff --git a/src/api/providers/__tests__/anthropic-convert.test.ts b/src/api/providers/__tests__/anthropic-convert.test.tsnew file mode 100644index 00000000..c9d54a7b--- /dev/null+++ b/src/api/providers/__tests__/anthropic-convert.test.ts@@ -0,0 +1,62 @@+/**+ * Audit B7 — Anthropic requires all tool_result blocks answering one+ * assistant turn in ONE user message. The agent loop pushes one tool-result+ * message per call, and the old string-only merge left two parallel calls as+ * two consecutive user messages, which the API rejects. Verified through the+ * request body chatWithTools actually sends.+ */+import { describe, it, expect, vi, afterEach } from 'vitest'+import { AnthropicProvider } from '../anthropic-provider'+import type { ChatMessage } from '../types'++function providerWithCapturedBody() {+ const provider = new AnthropicProvider({+ id: 'anthropic', name: 'Anthropic', enabled: true,+ baseUrl: 'https://api.anthropic.com', apiKey: 'sk-test', isLocal: false,+ })+ const bodies: any[] = []+ vi.stubGlobal('fetch', vi.fn(async (_url: any, init: any) => {+ bodies.push(JSON.parse(init.body))+ return {+ ok: true,+ json: async () => ({ content: [{ type: 'text', text: 'ok' }], usage: { input_tokens: 12, output_tokens: 3 } }),+ } as any+ }))+ return { provider, bodies }+}++afterEach(() => vi.unstubAllGlobals())++describe('AnthropicProvider message conversion (audit B7)', () => {+ it('folds parallel tool results into one user message of blocks', async () => {+ const { provider, bodies } = providerWithCapturedBody()+ const messages: ChatMessage[] = [+ { role: 'user', content: 'run both' },+ {+ role: 'assistant', content: '',+ tool_calls: [+ { id: 'toolu_1', function: { name: 'file_read', arguments: { path: 'a.ts' } } },+ { id: 'toolu_2', function: { name: 'file_read', arguments: { path: 'b.ts' } } },+ ],+ },+ { role: 'tool', content: 'contents of a', tool_call_id: 'toolu_1' },+ { role: 'tool', content: 'contents of b', tool_call_id: 'toolu_2' },+ ]+ await provider.chatWithTools('claude-opus-4-20250514', messages, [])+ const sent = bodies[0].messages+ // user, assistant(tool_use), ONE user carrying BOTH tool_result blocks+ expect(sent).toHaveLength(3)+ const resultMsg = sent[2]+ expect(resultMsg.role).toBe('user')+ expect(Array.isArray(resultMsg.content)).toBe(true)+ const ids = resultMsg.content.map((b: any) => b.tool_use_id)+ expect(ids).toEqual(['toolu_1', 'toolu_2'])+ })++ it('returns real token usage', async () => {+ const { provider } = providerWithCapturedBody()+ const turn = await provider.chatWithTools('claude-opus-4-20250514', [{ role: 'user', content: 'hi' }], [])+ expect(turn.promptEvalCount).toBe(12)+ expect(turn.evalCount).toBe(3)+ })+})diff --git a/src/api/providers/anthropic-provider.ts b/src/api/providers/anthropic-provider.tsindex 206aaf1b..4aa3c074 100644--- a/src/api/providers/anthropic-provider.ts+++ b/src/api/providers/anthropic-provider.ts@@ -231,7 +231,7 @@ export class AnthropicProvider implements ProviderClient {messages: ChatMessage[],tools: ToolDefinition[],options?: ChatOptions,- ): Promise<{ content: string; toolCalls: ToolCall[] }> {+ ): Promise<{ content: string; toolCalls: ToolCall[]; promptEvalCount?: number; evalCount?: number }> {const { system, anthropicMessages } = this.convertMessages(messages)const body: Record<string, any> = {@@ -299,7 +299,14 @@ export class AnthropicProvider implements ProviderClient {}}- return { content, toolCalls }+ // Real usage (audit B7): without it the TokenCounter stayed on the+ // char/4 estimate for every Anthropic agent turn.+ return {+ content,+ toolCalls,+ promptEvalCount: data.usage?.input_tokens || undefined,+ evalCount: data.usage?.output_tokens || undefined,+ }}async listModels(): Promise<ProviderModel[]> {@@ -395,14 +402,25 @@ export class AnthropicProvider implements ProviderClient {}// Anthropic requires messages to alternate user/assistant.- // Merge consecutive same-role messages.+ // Merge consecutive same-role messages. Block-array contents merge too+ // (audit B7): the agent loop pushes one tool-result message PER call, and+ // Anthropic requires all tool_result blocks answering one assistant turn+ // to arrive in ONE user message. The old string-only merge left two+ // parallel tool calls as two consecutive user messages, which the API+ // rejects — so any multi-tool batch broke the whole Anthropic agent path.+ const asBlocks = (content: string | Record<string, any>[]): Record<string, any>[] =>+ typeof content === 'string' ? [{ type: 'text', text: content }] : contentconst merged: Record<string, any>[] = []for (const msg of anthropicMessages) {const last = merged[merged.length - 1]- if (last && last.role === msg.role && typeof last.content === 'string' && typeof msg.content === 'string') {+ if (!last || last.role !== msg.role) {+ merged.push(msg)+ continue+ }+ if (typeof last.content === 'string' && typeof msg.content === 'string') {last.content += '\n\n' + msg.content} else {- merged.push(msg)+ last.content = [...asBlocks(last.content), ...asBlocks(msg.content)]}}diff --git a/src/api/providers/openai-provider.ts b/src/api/providers/openai-provider.tsindex 1070f5dd..be793489 100644--- a/src/api/providers/openai-provider.ts+++ b/src/api/providers/openai-provider.ts@@ -272,7 +272,12 @@ export class OpenAIProvider implements ProviderClient {JSON.stringify(body.messages || '').length + JSON.stringify(body.tools || '').lengthconst promptTokens = Math.ceil(promptChars / 4)const headroom = Math.max(256, ctxLen - promptTokens - RESERVE)- body.max_tokens = requested > 0 ? Math.min(requested, headroom) : headroom+ // Audit E6: an UNSET budget used to send the whole remaining window as+ // max_tokens — six figures on a 128k model. Servers that validate+ // max_tokens against the model's real OUTPUT limit reject that outright.+ // 32k is beyond any single reply this app produces; an explicit user+ // request still passes through un-capped (their server, their call).+ body.max_tokens = requested > 0 ? Math.min(requested, headroom) : Math.min(headroom, 32768)}async *chatStream(@@ -619,6 +624,20 @@ export class OpenAIProvider implements ProviderClient {private async probeContextFromServer(model: string): Promise<number | null> {if (!this.isLanBackend) return null+ // Probe cache (audit E5): applyMaxTokens calls getContextLength on EVERY+ // request, and a LAN backend without a catalog entry paid one or two HTTP+ // probes per agent iteration. A loaded model's window does not move+ // between iterations; 5 minutes covers an LM Studio reload with changed+ // settings. Negative answers cache too — a server that has no context+ // endpoint will not grow one mid-run.+ const cacheKey = `${this.baseUrl}|${model}`+ const hit = OpenAIProvider.probeCache.get(cacheKey)+ if (hit && Date.now() - hit.at < 300_000) return hit.ctx+ const remember = (ctx: number | null): number | null => {+ OpenAIProvider.probeCache.set(cacheKey, { at: Date.now(), ctx })+ return ctx+ }+// 1. LM Studio Enhanced API: /api/v0/models/<id>// Base-URL ist typischerweise http://localhost:1234/v1 — wir tauschen// /v1 gegen /api/v0 aus. Wenn der Server kein LM Studio ist, kommt 404@@ -632,7 +651,7 @@ export class OpenAIProvider implements ProviderClient {if (lmsRes.ok) {const data = await lmsRes.json()const max = data?.max_context_length ?? data?.context_length- if (max && Number(max) > 0) return Number(max)+ if (max && Number(max) > 0) return remember(Number(max))}} catch { /* fall through */ }@@ -650,13 +669,17 @@ export class OpenAIProvider implements ProviderClient {data?.max_model_len ??data?.n_ctx_train ??data?.context_length- if (ctx && Number(ctx) > 0) return Number(ctx)+ if (ctx && Number(ctx) > 0) return remember(Number(ctx))}} catch { /* fall through */ }- return null+ return remember(null)}+ /** Probe results per endpoint+model (audit E5). Static, not an instance+ * field: the lu-cloud provider builds a fresh delegate per call. */+ private static probeCache = new Map<string, { at: number; ctx: number | null }>()+async getContextLength(model: string): Promise<number> {// Cascade:// 1. Server-declared context_length from the /models catalogue (LUdiff --git a/src/hooks/__tests__/useCodex-loop-detection.test.ts b/src/hooks/__tests__/useCodex-loop-detection.test.tsindex 470f13b2..e425fee4 100644--- a/src/hooks/__tests__/useCodex-loop-detection.test.ts+++ b/src/hooks/__tests__/useCodex-loop-detection.test.ts@@ -39,9 +39,18 @@ describe('useCodex loop-detector (Bug #5 → AgentLoopGuard)', () => {expect(src).toMatch(/stronger model/i)})- it('injects the steer message into the model history', () => {+ it('injects the steer message into the model history, AFTER the calls it refers to', () => {expect(src).toMatch(/batchVerdict\.action === 'steer'/)- expect(src).toContain("messages.push({ role: 'user', content: batchVerdict.message })")+ expect(src).toContain("messages.push({ role: 'user', content: pendingSteer })")+ // Audit F2: pushed at detection time the steer landed chronologically+ // BEFORE the assistant tool_calls message it complains about, so the+ // history read "do not repeat this" and then showed the model doing it.+ const idxHold = src.indexOf('pendingSteer = batchVerdict.message')+ const idxPush = src.indexOf("messages.push({ role: 'user', content: pendingSteer })")+ const idxHistory = src.indexOf("messages.push({ role: 'assistant', content: turnContent || '', tool_calls: toolCalls })")+ expect(idxHold).toBeGreaterThan(0)+ expect(idxHistory).toBeGreaterThan(idxHold)+ expect(idxPush).toBeGreaterThan(idxHistory)})it('checks the guard AFTER tool calls are collected but BEFORE executing', () => {diff --git a/src/hooks/__tests__/useCodex-streaming.test.ts b/src/hooks/__tests__/useCodex-streaming.test.tsindex 6030d511..89010aff 100644--- a/src/hooks/__tests__/useCodex-streaming.test.ts+++ b/src/hooks/__tests__/useCodex-streaming.test.ts@@ -216,14 +216,16 @@ describe('streamWithTools NDJSON parsing', () => {// (useAgentChat.ts) can share the same wire protocol — these checks now// guard the new location instead of useCodex.ts.describe('streamWithTools drift detection', () => {- it('ollama-stream-tools.ts still uses append-spread for tool_calls (not overwrite)', () => {+ it('ollama-stream-tools.ts still appends tool_calls (not overwrite), deduped since audit F1', () => {const __filename = fileURLToPath(import.meta.url)const __dirname = dirname(__filename)const src = readFileSync(join(__dirname, '../../lib/ollama-stream-tools.ts'), 'utf8')- // Must contain the spread-append pattern, not the old overwrite- expect(src).toContain('...toolCalls,')- expect(src).toContain('...j.message.tool_calls.map')+ // Every chunk AND the tail-buffer pass must go through the appending,+ // deduping helper — split-across-lines calls still accumulate, while a+ // server that repeats the full array cannot double-execute a call.+ expect(src.match(/appendCalls\(j\.message\.tool_calls\)/g)?.length).toBe(2)+ expect(src).toContain('seenCalls')// Must NOT contain the old overwrite patternexpect(src).not.toMatch(/toolCalls\s*=\s*j\.message\.tool_calls\.map/)})diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex d1826934..a2dcdea6 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -45,6 +45,7 @@ import { buildLoopRecheck, loopPassSaysDone } from '../lib/agent-commands'import { generateEmbeddings } from '../api/rag'import { truncateToolResult } from '../lib/truncate-tool-result'import { toolCallCapMs, raceWithToolTimeout, SHELL_EXECUTE_DEFAULT_TIMEOUT_MS, CODE_EXECUTE_DEFAULT_TIMEOUT_MS } from '../lib/tool-timeout'+import { AgentLoopGuard } from '../lib/agent-loop-guard'import { budgetFromSettings } from '../api/agents/budget'import type { ChatMessage, ToolCall, ToolDefinition } from '../api/providers/types'import type { StepResult, WorkflowEngineCallbacks } from '../types/agent-workflows'@@ -102,6 +103,14 @@ interface ApprovalEntry {// ── Hook ──────────────────────────────────────────────────────+/**+ * The pending next /loop pass. MODULE scope, not a hook ref (audit A3): the+ * chat view unmounts on a view switch, and a timer parked in an unmounted+ * instance's ref was unreachable for the remounted hook — stopAgent cleared+ * its own (empty) ref while the old timer kept firing new passes.+ */+let agentLoopTimer: ReturnType<typeof setTimeout> | null = null+export function useAgentChat() {const [isAgentRunning, setIsAgentRunning] = useState(false)const [pendingApproval, setPendingApproval] = useState<AgentToolCall | null>(null)@@ -110,8 +119,6 @@ export function useAgentChat() {/** True once the user pressed stop, so the /loop driver does not start* another pass on the run they just killed. */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 approvalQueueRef = useRef<ApprovalEntry[]>([])const contentRef = useRef('')const thinkingRef = useRef('')@@ -629,6 +636,12 @@ export function useAgentChat() {const executedCallKeys = new Set<string>()const callKey = (tc: { function: { name: string; arguments: unknown } }) =>tc.function.name + '|' + JSON.stringify(tc.function.arguments ?? {})+ // Loop-detection (audit follow-up): agent-loop-guard's own header says it+ // covers "Codex + Chat agent", but only Codex ever wired it — the agent+ // loop relied on the exact-repeat set alone, which the epoch reset (B1)+ // rightly weakened. Windowed batch repeats, per-epoch identical reads and+ // repeated narration now watch this loop too.+ const loopGuard = new AgentLoopGuard()try {// ── Agent Loop ──────────────────────────────────────────@@ -1196,6 +1209,26 @@ export function useAgentChat() {}}+ // Loop-detector, parity with Codex: narration first (the same line+ // re-emitted every iteration), then the batch (windowed signature+ // repeats + identical reads against an unchanged workspace). Steer is+ // held and appended AFTER this iteration's history (audit F2), so it+ // never sits chronologically before the calls it refers to.+ 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') {+ contentRef.current =+ (contentRef.current ? contentRef.current + '\n\n' : '') ++ `_(halted: ${batchVerdict.reason}. The model is looping — try a stronger model for multi-step tasks, or rephrase the instruction.)_`+ scheduleUIUpdate()+ break+ }+ const pendingSteer = batchVerdict.action === 'steer' ? batchVerdict.message : null+type BatchEntry = { tc: typeof toolCalls[number]; ac: AgentToolCall; blockId: string }const batch: BatchEntry[] = []budget.addToolCalls(toolCalls.length)@@ -1456,6 +1489,11 @@ export function useAgentChat() {}}+ // Now the steer sits AFTER the calls it refers to (audit F2).+ if (pendingSteer) {+ agentMessages.push({ role: 'user', content: pendingSteer })+ }+// Vision feedback (David 2026-06-03): after image_generate, hand the// generated picture to a vision-capable model so it SEES the result and// can comment — and learns the filename to chain into video_generate.@@ -1628,9 +1666,14 @@ export function useAgentChat() {task: loopState.task, intervalMs: loopState.intervalMs,nextAt: Date.now() + loopState.intervalMs,})- loopTimerRef.current = setTimeout(() => {- loopTimerRef.current = null- if (runningRef.current) return+ agentLoopTimer = setTimeout(() => {+ agentLoopTimer = null+ // A skipped pass clears the loop store too (audit A3) — leaving+ // it standing painted a LoopBar promising a pass that never came.+ if (runningRef.current) {+ useAgentLoopStore.getState().clear()+ return+ }if (useChatStore.getState().activeConversationId !== convForLoop) {useAgentLoopStore.getState().clear()return@@ -1655,9 +1698,9 @@ export function useAgentChat() {// Stop means stop: also cancel a /loop pass 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 (agentLoopTimer) {+ clearTimeout(agentLoopTimer)+ agentLoopTimer = null}useAgentLoopStore.getState().clear()runningRef.current = falsediff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.tsindex cda0765b..2859c148 100644--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@ -1267,11 +1267,16 @@ export function useCodex() {useChatStore.getState().updateMessageContent(convId, assistantMsg.id, fullContent + msg)break}+ // Steer is appended AFTER this iteration's assistant+tool messages+ // (audit F2). Pushed here it landed chronologically BEFORE the calls+ // it complains about, so the history read "do not repeat this" and+ // then showed the model doing it.+ let pendingSteer: string | null = nullif (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 })+ pendingSteer = batchVerdict.message}type BatchEntry = { tc: typeof toolCalls[number]; ac: AgentToolCall; blockId: string; injectedArgs: Record<string, any> }@@ -1712,6 +1717,11 @@ export function useCodex() {messages.push({ role: 'user', content: buildHermesToolResult(entry.ac.toolName, resultTextFor(result)) })}}++ // Now the steer sits AFTER the calls it refers to (audit F2).+ if (pendingSteer) {+ messages.push({ role: 'user', content: pendingSteer })+ }}// Bug fix: when the model's final turn returns empty content (alldiff --git a/src/lib/__tests__/readonly-enforcement.test.ts b/src/lib/__tests__/readonly-enforcement.test.tsindex 27e2e5c5..7dfe1ba0 100644--- a/src/lib/__tests__/readonly-enforcement.test.ts+++ b/src/lib/__tests__/readonly-enforcement.test.ts@@ -98,9 +98,11 @@ describe('/loop actually loops', () => {it('starts the NEXT pass after the interval instead of killing the run', () => {const src = read('../../hooks/useCodex.ts')- expect(src).toContain('loopTimerRef.current = setTimeout(')+ // The handle is module-scoped since audit A3 — a hook ref died with the+ // unmounted Code view, so stopCodex could not reach a pending pass.+ expect(src).toContain('let codexLoopTimer:')+ expect(src).toContain('codexLoopTimer = setTimeout(fireLoopPass, loopState.intervalMs)')expect(src).toContain('buildLoopRecheck(loopState.task, nextPass)')- expect(src).toContain('}, loopState.intervalMs)')})it('stops on the done marker or on a cap the user set, and NOTHING else', () => {@@ -136,9 +138,11 @@ describe('/loop actually loops', () => {const src = read('../../hooks/useCodex.ts')const stopIdx = src.indexOf('const stopCodex = useCallback(')expect(stopIdx).toBeGreaterThan(0)- const stopBody = src.slice(stopIdx, stopIdx + 600)- expect(stopBody).toContain('clearTimeout(loopTimerRef.current)')+ const stopBody = src.slice(stopIdx, stopIdx + 900)+ expect(stopBody).toContain('clearTimeout(codexLoopTimer)')expect(stopBody).toContain('userStoppedRef.current = true')+ // And it reaches a run started by a PREVIOUS hook instance (audit A2).+ expect(stopBody).toContain('abortConversation(')})})diff --git a/src/lib/ollama-stream-tools.ts b/src/lib/ollama-stream-tools.tsindex 926af10a..e4058786 100644--- a/src/lib/ollama-stream-tools.ts+++ b/src/lib/ollama-stream-tools.ts@@ -96,6 +96,21 @@ export async function streamOllamaChatWithTools(let content = ''let thinking = ''let toolCalls: ToolCall[] = []+ // Audit F1: some servers repeat the FULL tool_calls array in a later chunk+ // (and the tail-buffer pass could append the same calls once more). Without+ // this, the identical call ran twice. Byte-identical name+args within one+ // turn is never two intended calls — that is what the repeat guard and the+ // in-turn cache treat as one call too.+ const seenCalls = new Set<string>()+ const appendCalls = (raw: any[]) => {+ for (const tc of raw) {+ const repaired = repairToolCallArgs(tc.function.arguments)+ const key = `${tc.function.name}|${JSON.stringify(repaired ?? {})}`+ if (seenCalls.has(key)) continue+ seenCalls.add(key)+ toolCalls = [...toolCalls, { function: { name: tc.function.name, arguments: repaired } }]+ }+ }// Real token usage from the final Ollama chunk (top-level, not in `message`).// prompt_eval_count is the FULL consumed context (system + tools + RAG +// history) for THIS turn — the agent/code loop stores the latest so the@@ -103,12 +118,33 @@ export async function streamOllamaChatWithTools(let promptEvalCount = 0let evalCount = 0+ // No-bytes watchdog (audit A7): a wedged runner behind a live connection+ // ends neither with data nor an error, and read() sat forever. Five silent+ // minutes is a dead stream — thinking models still produce deltas.+ const IDLE_TIMEOUT_MS = 300_000while (true) {if (options.signal?.aborted) {try { await reader.cancel() } catch { /* noop */ }break}- const { done, value } = await reader.read()+ let idleTimer: ReturnType<typeof setTimeout> | undefined+ let done: boolean, value: Uint8Array | undefined+ try {+ ;({ done, value } = await Promise.race([+ reader.read(),+ new Promise<never>((_, reject) => {+ idleTimer = setTimeout(+ () => reject(new Error(`Ollama stream stalled: no data received for ${Math.round(IDLE_TIMEOUT_MS / 1000)}s.`)),+ IDLE_TIMEOUT_MS,+ )+ }),+ ]))+ } catch (err) {+ try { await reader.cancel() } catch { /* noop */ }+ throw err+ } finally {+ clearTimeout(idleTimer)+ }if (done) breakbuf += decoder.decode(value, { stream: true })@@ -145,15 +181,7 @@ export async function streamOllamaChatWithTools(onThinking(thinking)}if (j.message.tool_calls && Array.isArray(j.message.tool_calls)) {- toolCalls = [- ...toolCalls,- ...j.message.tool_calls.map((tc: any) => ({- function: {- name: tc.function.name,- arguments: repairToolCallArgs(tc.function.arguments),- },- })),- ]+ appendCalls(j.message.tool_calls)}}if (typeof j.prompt_eval_count === 'number') promptEvalCount = j.prompt_eval_count@@ -173,15 +201,7 @@ export async function streamOllamaChatWithTools(throw new Error(`Ollama: ${j.error}`)}if (j.message?.tool_calls && Array.isArray(j.message.tool_calls)) {- toolCalls = [- ...toolCalls,- ...j.message.tool_calls.map((tc: any) => ({- function: {- name: tc.function.name,- arguments: repairToolCallArgs(tc.function.arguments),- },- })),- ]+ appendCalls(j.message.tool_calls)}if (j.message?.content) {content += j.message.contentdiff --git a/src/lib/provider-stream.ts b/src/lib/provider-stream.tsindex a23b2ece..01d3d369 100644--- a/src/lib/provider-stream.ts+++ b/src/lib/provider-stream.ts@@ -30,6 +30,42 @@ export interface StreamedProviderTurn {finishReason?: string}+/**+ * No-bytes watchdog (audit A7). A backend that wedges mid-stream (crashed+ * runner behind a live proxy, half-dead connection) ends neither with data+ * nor with an error — the loop just sat on read() forever with the typing+ * dots on. Five minutes with not a single chunk is a dead stream, not a slow+ * one: reasoners emit thinking deltas while they work, so even "silent"+ * phases produce bytes.+ */+const STREAM_IDLE_TIMEOUT_MS = 300_000++async function* withIdleGuard<T>(iter: AsyncIterable<T>, idleMs: number): AsyncGenerator<T> {+ const it = iter[Symbol.asyncIterator]()+ for (;;) {+ let timer: ReturnType<typeof setTimeout> | undefined+ let next: IteratorResult<T>+ try {+ next = await Promise.race([+ it.next(),+ new Promise<never>((_, reject) => {+ timer = setTimeout(+ () => reject(new Error(`Stream stalled: no data received for ${Math.round(idleMs / 1000)}s.`)),+ idleMs,+ )+ }),+ ])+ } catch (err) {+ try { await it.return?.(undefined as never) } catch { /* releasing the reader is best-effort */ }+ throw err+ } finally {+ clearTimeout(timer)+ }+ if (next.done) return+ yield next.value+ }+}+export async function streamProviderTurn(provider: ProviderClient,model: string,@@ -41,7 +77,7 @@ export async function streamProviderTurn(let content = ''let thinking = ''const turn: StreamedProviderTurn = { content: '', toolCalls: [], thinking: '' }- for await (const chunk of provider.chatStream(model, messages, options)) {+ for await (const chunk of withIdleGuard(provider.chatStream(model, messages, options), STREAM_IDLE_TIMEOUT_MS)) {if (chunk.content) {content += chunk.contentonContent?.(content, chunk.content)