Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat(agent): the toolbox matches the task, and a long step no longer costs the run

purple9c3c4b758e81
diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.ts
index d9a2494a..7aff3965 100644
--- a/src/api/mcp/builtin-tools.ts
+++ b/src/api/mcp/builtin-tools.ts
@@ -9,6 +9,7 @@ import { WorkflowEngine } from '../../lib/workflow-engine'
import type { StepResult } from '../../types/agent-workflows'
import { DELEGATE_TASK_TOOL_DEF, buildDelegateExecutor } from '../agents/sub-agent'
import { applyUniqueEdit } from '../../lib/surgical-edit'
+import { sliceFileReadResult } from '../../lib/file-read-window'
import { isMlxImageHost, generateMlxImageDataUrl, listMlxImageModels, type MlxImageModel } from '../mlx-image'
import { getVideoStatus, listVideoModels, generateVideo as generateMlxVideo, getVideoProgress, cancelVideo, readVideoAsBlobUrl, type VideoModel } from '../mlx-video'
@@ -84,14 +85,18 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [
{
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. '
+ '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.',
inputSchema: {
type: 'object',
properties: {
path: { type: 'string', description: 'Path to the file (absolute preferred)' },
+ offset: { type: 'number', description: '1-based line to start reading from (optional)' },
+ limit: { type: 'number', description: 'Maximum number of lines to return (optional)' },
},
required: ['path'],
},
@@ -706,7 +711,8 @@ async function executeFileRead(args: Record<string, any>): Promise<string> {
: Math.floor((String(data.content || '').length * 3) / 4)
return `[binary file — ${formatBytes(bytes)}, not shown. This tool reads text only; do not write binary content back through file_write.]`
}
- return data.content || ''
+ // Windowed read (audit C1) — see src/lib/file-read-window.ts.
+ return sliceFileReadResult(String(data.content || ''), args)
}
/** Last path segment, defaulting to file.txt. */
diff --git a/src/api/providers/ollama-provider.ts b/src/api/providers/ollama-provider.ts
index 146b4f1c..32d08483 100644
--- a/src/api/providers/ollama-provider.ts
+++ b/src/api/providers/ollama-provider.ts
@@ -85,6 +85,9 @@ export class OllamaProvider implements ProviderClient {
model,
messages: ollamaMessages,
stream: true,
+ // Audit A6: match the agent transport so a long turn never pays a
+ // cold multi-GB reload after Ollama's 5-minute default idle unload.
+ keep_alive: '30m',
}
// v2.4.6 Bug L: dropped hardcoded `num_gpu: 99`. Old code forced ALL
@@ -191,6 +194,8 @@ export class OllamaProvider implements ProviderClient {
messages: ollamaMessages,
tools,
stream: false,
+ // Audit A6: see chatStream above.
+ keep_alive: '30m',
}
// v2.4.6 Bug L: see chatStream() above — same num_gpu:99 removal.
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 511c9ee4..d1826934 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -44,6 +44,7 @@ import { useAgentLoopStore } from '../stores/agentLoopStore'
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 { budgetFromSettings } from '../api/agents/budget'
import type { ChatMessage, ToolCall, ToolDefinition } from '../api/providers/types'
import type { StepResult, WorkflowEngineCallbacks } from '../types/agent-workflows'
@@ -715,7 +716,11 @@ export function useAgentChat() {
// routing once the total tool count grows past the threshold
// (Phase 9). The embedding call is best-effort: if Ollama is
// unreachable it silently falls back to keyword-only.
- const lastUserMsg = agentMessages.filter(m => m.role === 'user').pop()?.content || ''
+ // Route on the USER's instruction, never on the newest user-role
+ // message (audit B6): steers, over-loop notes and read-only blocks
+ // are pushed as role 'user', and routing on those swapped the tool
+ // list mid-run to whatever the harness said last.
+ const lastUserMsg = userContent
// Small-Model Mode (Knob 1): tighten the tool cap and force the
// embedding router even on a modest catalog (threshold 6) so a 3B-8B
// model sees ≤6 semantically-ranked tools. Default mode keeps the
@@ -1204,10 +1209,21 @@ export function useAgentChat() {
perToolOverrides
)
const needsApproval = permLevel !== 'auto'
+ // Exec-timeout parity with the Code tab (audit B8): without an
+ // injected default the Rust side used its 120 s fallback, so the
+ // same npm install that passed in Code died here after 2 minutes.
+ // The model's own timeout still wins when it sends one.
+ const toolArgs = { ...tc.function.arguments }
+ if (tc.function.name === 'shell_execute' && !toolArgs.timeout) {
+ toolArgs.timeout = SHELL_EXECUTE_DEFAULT_TIMEOUT_MS
+ }
+ if (tc.function.name === 'code_execute' && !toolArgs.timeout) {
+ toolArgs.timeout = CODE_EXECUTE_DEFAULT_TIMEOUT_MS
+ }
const ac: AgentToolCall = {
id: toolCallId,
toolName: tc.function.name,
- args: tc.function.arguments,
+ args: toolArgs,
status: needsApproval ? 'pending_approval' : 'running',
timestamp: Date.now(),
}
@@ -1236,7 +1252,11 @@ export function useAgentChat() {
const td = toolRegistry.getToolByName(name)
return td ? { name: td.name, inputSchema: td.inputSchema } : undefined
},
- execute: (name: string, args: Record<string, any>) => toolRegistry.execute(name, args),
+ // Timeout backstop shared with Codex (audit B9): before this the
+ // Agent loop had NO ceiling around a tool call, so one hung tool
+ // wedged the whole run with no way out but a restart.
+ execute: (name: string, args: Record<string, any>) =>
+ raceWithToolTimeout(toolRegistry.execute(name, args), name, toolCallCapMs(name, args, settings)),
lookupCache: convId ? makeInTurnCacheLookup({ convId, turnStartMs }) : undefined,
explainError: (toolName, err) => explainToolError(toolName, err),
awaitApproval: async (req) => {
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index bee0b412..6c9fc2cf 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -50,6 +50,7 @@ import { canonicalToolName } from '../lib/loose-tool-parse'
import { selectRelevantTools, selectRelevantToolsAsync } from '../lib/tool-selection'
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 { compactMessages, getModelMaxTokens, estimateTokens } from '../lib/context-compaction'
import { resolveAgentNumCtx } from '../lib/agent-num-ctx'
import { AgentLoopGuard } from '../lib/agent-loop-guard'
@@ -77,7 +78,7 @@ const CODEX_REVIEW_SYSTEM_PROMPT = `You are the Coding Agent in REVIEW MODE, a r
REVIEW MODE CONTRACT (binding):
- You MAY call: file_read, file_list, file_search, git_status, git_log, git_diff, system_info, process_list, get_current_time, web_fetch, web_search.
-- You MUST NOT call: file_write, file_edit, shell_execute, code_execute, run_tests, git_commit, git_push, gh_pr_create, image_generate, video_generate, run_workflow, screenshot, delegate_task. If you call them, the harness will reject the call and tell the model "review-only mode", wasted budget.
+- You MUST NOT call: file_write, file_edit, shell_execute, code_execute, run_tests, git_commit, git_push, gh_pr_create, image_generate, video_generate, run_workflow, screenshot, delegate_task. They are stripped from your tool list; attempting one fails as an unknown tool and wastes the step.
- Output format: a markdown report with sections "## Summary", "## Findings (priority order)", "## Suggested follow-ups". For each finding cite the file + line range (path:line or path:start-end).
- Be direct. No flattery, no boilerplate. If the code is fine, say so in one sentence and stop.`
@@ -135,7 +136,12 @@ const streamWithTools = streamOllamaChatWithTools
// "Video generation auf simplen Prompt in Code und Agentmode") — they only
// surface when the keyword router sees a creative intent in the prompt, so
// pure coding turns keep the same lean tool list as before.
-const CODEX_CATEGORIES = ['filesystem', 'terminal', 'system', 'web', 'image', 'video'] as const
+// workflow joined with audit B11: delegate_task (the sub-agent fan-out, the
+// counterpart of Claude Code's Task tool) lived in that category and was
+// therefore unreachable from the Code tab. Local models only see it on a
+// delegate/parallel intent via the keyword router; cloud models get it in
+// the full catalog.
+const CODEX_CATEGORIES = ['filesystem', 'terminal', 'system', 'web', 'image', 'video', 'workflow'] as const
// `.lurules` reader. MUST go through `fs_read` (the workspace-aware command)
@@ -775,7 +781,12 @@ export function useCodex() {
}
if (strategy === 'native') {
- const lastUserMsg = messages.filter(m => m.role === 'user').pop()?.content || ''
+ // Route on the USER's instruction, never on the newest user-role
+ // message (audit B6): steers, nudges and blocked-tool notes are
+ // pushed as role 'user', and routing on those swapped the tool list
+ // mid-run to whatever the harness happened to say last. The real
+ // instruction is the routing intent for the whole run.
+ const lastUserMsg = instruction
// CODEX_CATEGORIES filter: Codex is a CODING agent — screenshot,
// run_workflow etc. are distractions that pollute the tool list for
// small/3B models. Filter the registry by category BEFORE keyword
@@ -796,21 +807,19 @@ export function useCodex() {
const codexTools = (settings.codexReviewMode || readOnlyTurn)
? codexToolsAll.filter((t) => !MUTATING_TOOLS.has(t.name))
: codexToolsAll
- // Keep the tool list LEAN — exactly like the uselu reference. A small
- // model (qwen2.5-coder:7b) handed the full ~24-tool category set every
- // turn degrades fast: it lapses into prose narration or dumps raw
- // tool-call JSON instead of emitting clean native tool_calls, and the
- // ReAct loop then stops after one step. uselu narrows to a handful of
- // keyword-relevant tools, which keeps small models on-rails; git/test
- // operations go through shell_execute (the dedicated git_*/run_tests
- // tools are intentionally not surfaced by the keyword router). This
- // line is the single most important parity point with uselu — do NOT
- // replace it with the full `codexTools` set (that was the regression).
- // Small-Model Mode (Knob 1): give Codex the embedding router it
- // normally lacks (it ships keyword-only) plus a hard tool cap, so a
- // 3B-8B coding model sees a short, semantically-ranked tool list.
- // Default mode keeps the proven keyword-only selection — uselu parity,
- // the single most important small-model line; do NOT widen it.
+ // Tool-list sizing is a MODEL-STRENGTH decision (audit B3):
+ // - Small-Model Mode: embedding router + hard cap, ≤6 tools. A
+ // 3B-8B model handed the full catalog degrades fast (narrates,
+ // dumps raw JSON, stops after one step — the old regression,
+ // LongFuncEval arXiv 2505.10570).
+ // - Local default: keyword routing over the coding categories,
+ // uselu parity. Kept lean on purpose; the keyword groups now
+ // cover git/tests/background so those are reachable when asked.
+ // - Cloud/remote model: the FULL coding catalog. A hosted model
+ // handles 25+ tools fine (that is exactly what Claude Code
+ // sends), and keyword-guessing its toolbox from message one
+ // starved 30-minute runs of git_commit/run_tests/background
+ // shell mid-way.
const relevantDefs = settings.smallModelMode
? await selectRelevantToolsAsync(lastUserMsg, codexTools, permissions, {
embed: (texts) => generateEmbeddings(texts),
@@ -818,7 +827,9 @@ export function useCodex() {
embeddingThreshold: 6,
maxTools: 6,
})
- : selectRelevantTools(lastUserMsg, codexTools, permissions)
+ : !isLocalModelByName(activeModel)
+ ? codexTools
+ : selectRelevantTools(lastUserMsg, codexTools, permissions)
const tools: ToolDefinition[] = relevantDefs.map(t => ({
type: 'function' as const,
function: { name: t.name, description: t.description, parameters: t.inputSchema },
@@ -1257,11 +1268,11 @@ export function useCodex() {
// own timeout to go higher/lower.
if (toolName === 'shell_execute') {
if (!toolArgs.cwd && hasValidWorkDir) toolArgs.cwd = workDir
- if (!toolArgs.timeout) toolArgs.timeout = 600000
+ if (!toolArgs.timeout) toolArgs.timeout = SHELL_EXECUTE_DEFAULT_TIMEOUT_MS
}
if (toolName === 'code_execute') {
if (!toolArgs.cwd && hasValidWorkDir) toolArgs.cwd = workDir
- if (!toolArgs.timeout) toolArgs.timeout = 120000
+ if (!toolArgs.timeout) toolArgs.timeout = CODE_EXECUTE_DEFAULT_TIMEOUT_MS
}
// Resolve relative file paths against working directory.
// Absolute-path detection must accept ANY drive letter (C:, D:, E:, …),
@@ -1330,45 +1341,13 @@ export function useCodex() {
}),
)
- // 60 s per-call timeout is enforced by wrapping the executor function
- // (keeps the original safety guard — a runaway tool cannot wedge the
- // whole agent turn).
- const withTimeout = (name: string, args: Record<string, any>) => {
- // Shell/code/test/git tools enforce their OWN timeout in the Rust
- // backend (args.timeout). A fixed 60s JS cap here used to preempt
- // long-but-legitimate builds before the backend's timer fired — the
- // root of "coding agent can't build anything / always times out"
- // (David 2026-06-04). For those, set the JS race ceiling just ABOVE
- // the tool's own timeout so the backend always wins; everything else
- // keeps the original 60s guard.
- //
- // Same bug class hit the generation tools when they joined Codex in
- // v2.5.3 (live E2E 2026-06-10: five video_generate attempts all died
- // at "timed out (60s)" mid-VRAM-handoff). image/video generation has
- // its own settings-driven deadline (imageGen/videoGenTimeoutMinutes,
- // enforced in vram-handoff's poll) — set the JS ceiling above it so
- // the generation pipeline's own timeout always wins, exactly like
- // the shell tools.
- const longRunning =
- name === 'shell_execute' || name === 'code_execute' ||
- name === 'shell_execute_background' || name === 'run_tests' ||
- name === 'git_commit' || name === 'git_push'
- const own = Number(args?.timeout)
- const capMs =
- name === 'image_generate'
- ? (Math.max(1, Number(settings.imageGenTimeoutMinutes) || 20) * 60_000 + 120_000)
- : name === 'video_generate'
- ? (Math.max(1, Number(settings.videoGenTimeoutMinutes) || 60) * 60_000 + 120_000)
- : longRunning
- ? (Number.isFinite(own) && own > 0 ? own + 15000 : 615000)
- : 60000
- return Promise.race([
- toolRegistry.execute(name, args),
- new Promise<string>((_, reject) =>
- setTimeout(() => reject(new Error(`Tool execution timed out (${Math.round(capMs / 1000)}s)`)), capMs)
- ),
- ])
- }
+ // Per-call timeout backstop, shared with Agent mode since audit B8/B9
+ // (src/lib/tool-timeout.ts). The tool's own deadline always wins; the
+ // race only exists so a tool whose timer never fires cannot hold the
+ // loop forever — and the timer is cleared when the tool wins (B10),
+ // instead of parking a live closure for up to 615 s per call.
+ const withTimeout = (name: string, args: Record<string, any>) =>
+ raceWithToolTimeout(toolRegistry.execute(name, args), name, toolCallCapMs(name, args, settings))
// Multi-File Stage-and-Approve (B10). When the user has codex
// stage mode on, file_write calls don't hit the disk — they
diff --git a/src/lib/__tests__/file-read-window.test.ts b/src/lib/__tests__/file-read-window.test.ts
new file mode 100644
index 00000000..79ecf7ab
--- /dev/null
+++ b/src/lib/__tests__/file-read-window.test.ts
@@ -0,0 +1,44 @@
+import { describe, it, expect } from 'vitest'
+import { sliceFileReadResult } from '../file-read-window'
+
+const file = Array.from({ length: 10 }, (_, i) => `line ${i + 1}`).join('\n')
+
+describe('sliceFileReadResult (audit C1)', () => {
+ it('returns the whole file untouched when no window is asked for', () => {
+ expect(sliceFileReadResult(file, {})).toBe(file)
+ expect(sliceFileReadResult(file, { offset: 0, limit: 0 })).toBe(file)
+ })
+
+ it('returns a window with header and next-page hint', () => {
+ const out = sliceFileReadResult(file, { offset: 3, limit: 4 })
+ expect(out).toContain('[lines 3-6 of 10]')
+ expect(out).toContain('line 3')
+ expect(out).toContain('line 6')
+ expect(out).not.toContain('line 7\n')
+ expect(out).toContain('offset: 7')
+ })
+
+ it('limit alone reads from the top', () => {
+ const out = sliceFileReadResult(file, { limit: 2 })
+ expect(out).toContain('[lines 1-2 of 10]')
+ expect(out).toContain('offset: 3')
+ })
+
+ it('offset alone reads to the end, with no next-page hint', () => {
+ const out = sliceFileReadResult(file, { offset: 9 })
+ expect(out).toContain('[lines 9-10 of 10]')
+ expect(out).not.toContain('more line')
+ })
+
+ it('an offset past the end yields an empty window, not a crash', () => {
+ const out = sliceFileReadResult(file, { offset: 99, limit: 5 })
+ expect(out).toContain('of 10]')
+ expect(out).not.toContain('line 1')
+ })
+
+ it('never adds line-number prefixes to the content itself', () => {
+ const out = sliceFileReadResult(file, { offset: 2, limit: 1 })
+ const body = out.split('\n')[1]
+ expect(body).toBe('line 2')
+ })
+})
diff --git a/src/lib/file-read-window.ts b/src/lib/file-read-window.ts
new file mode 100644
index 00000000..8dda4f1a
--- /dev/null
+++ b/src/lib/file-read-window.ts
@@ -0,0 +1,29 @@
+/**
+ * Windowed read for file_read (audit C1). Whole-file-only was the single
+ * biggest gap for real codebases: a 5000-line file rode into the context
+ * complete, the 60k-char head+tail truncation then dropped the MIDDLE
+ * silently, and the model edited against content it never saw. offset/limit
+ * page by LINES, with a header naming the window and the total so the model
+ * knows to page.
+ *
+ * No line-number prefixes on the content itself, on purpose: file_edit
+ * matches old_string byte-exactly against the file, and a model that copies
+ * a numbered line into old_string would never match.
+ */
+export function sliceFileReadResult(content: string, args: Record<string, any>): string {
+ const offset = Number(args?.offset)
+ const limit = Number(args?.limit)
+ const hasOffset = Number.isFinite(offset) && offset > 0
+ const hasLimit = Number.isFinite(limit) && limit > 0
+ if (!hasOffset && !hasLimit) return content
+ const lines = content.split('\n')
+ const start = hasOffset ? Math.min(Math.max(1, Math.floor(offset)), lines.length + 1) : 1
+ const count = hasLimit ? Math.floor(limit) : lines.length
+ const window = lines.slice(start - 1, start - 1 + count)
+ const end = start + window.length - 1
+ const header = `[lines ${start}-${end} of ${lines.length}]`
+ const tail = end < lines.length
+ ? `\n[${lines.length - end} more line${lines.length - end === 1 ? '' : 's'} — call file_read again with offset: ${end + 1}]`
+ : ''
+ return `${header}\n${window.join('\n')}${tail}`
+}
diff --git a/src/lib/ollama-stream-tools.ts b/src/lib/ollama-stream-tools.ts
index 5d28b432..926af10a 100644
--- a/src/lib/ollama-stream-tools.ts
+++ b/src/lib/ollama-stream-tools.ts
@@ -46,6 +46,11 @@ export async function streamOllamaChatWithTools(
messages: ollamaMessages,
tools,
stream: true,
+ // Audit A6: without this Ollama unloads the model after its 5-minute
+ // default idle. An agent step that runs a 10-minute build came back to a
+ // cold model and paid a multi-GB reload before the next thought — several
+ // times per long session. 30m matches the warm-up call in api/ollama.ts.
+ keep_alive: '30m',
options: {},
}
if (options.temperature !== undefined) body.options.temperature = options.temperature
diff --git a/src/lib/tool-selection.ts b/src/lib/tool-selection.ts
index bb915baa..d8a0001f 100644
--- a/src/lib/tool-selection.ts
+++ b/src/lib/tool-selection.ts
@@ -52,6 +52,39 @@ const TOOL_GROUPS: ToolGroup[] = [
keywords: ['run', 'execute', 'command', 'shell', 'terminal', 'bash', 'powershell', 'npm', 'git', 'pip', 'node', 'python', 'install', 'build', 'test', 'compile'],
tools: ['shell_execute', 'code_execute'],
},
+ {
+ // Audit B3: a third of the registry sat in NO group and was therefore
+ // invisible to the model forever — all git_*, run_tests, the background
+ // shell and its status tools, pr_resume, gh_pr_create, project_init.
+ // The typed git tools return parsed porcelain instead of an opaque dump,
+ // which is exactly what a small model needs for "commit this".
+ keywords: ['git', 'commit', 'push', 'branch', 'merge', 'rebase', 'stage', 'staged', 'diff', 'changelog', 'version control'],
+ tools: ['git_status', 'git_diff', 'git_log', 'git_commit', 'git_push'],
+ },
+ {
+ keywords: ['test', 'tests', 'spec', 'vitest', 'jest', 'pytest', 'cargo test', 'failing', 'make it green', 'suite'],
+ tools: ['run_tests'],
+ },
+ {
+ keywords: ['pull request', 'pull-request', 'open a pr', 'create a pr', 'the pr', 'github', 'gh pr'],
+ tools: ['gh_pr_create', 'pr_resume', 'git_status', 'git_diff'],
+ },
+ {
+ // Long-running work belongs on the background bridge: it survives the
+ // 10-minute foreground timeout and the model can poll it. The timeout
+ // hint in useCodex points at shell_execute_background, so it has to be
+ // reachable when builds/installs are on the table (audit B4).
+ keywords: ['background', 'install', 'build', 'compile', 'long running', 'long-running', 'dataset', 'refactor everything', 'task status', 'still running'],
+ tools: ['shell_execute_background', 'shell_task_status', 'shell_task_list', 'shell_task_kill'],
+ },
+ {
+ keywords: ['scaffold', 'new project', 'init a', 'initialize', 'bootstrap', 'starter'],
+ tools: ['project_init'],
+ },
+ {
+ keywords: ['delegate', 'sub-agent', 'subagent', 'fan out', 'in parallel', 'parallelize', 'split the work'],
+ tools: ['delegate_task'],
+ },
{
keywords: ['system', 'os', 'cpu', 'ram', 'memory', 'process', 'running', 'hostname'],
tools: ['system_info', 'process_list'],
diff --git a/src/lib/tool-timeout.ts b/src/lib/tool-timeout.ts
new file mode 100644
index 00000000..9f783399
--- /dev/null
+++ b/src/lib/tool-timeout.ts
@@ -0,0 +1,69 @@
+/**
+ * One timeout rule for every tool call, shared by useCodex and useAgentChat
+ * (audit B8/B9): the two loops used to disagree — Codex raced every call
+ * against a generous cap while Agent mode had NO ceiling at all (a hung tool
+ * wedged the whole run), and Agent never injected the long shell default, so
+ * the same build that passed in the Code tab died at the Rust side's 120 s
+ * default in Agent mode.
+ *
+ * The cap is a BACKSTOP above the tool's own deadline, never the working
+ * limit: shell/code/test/git enforce their real timeout in the Rust backend
+ * (args.timeout), image/video in the vram-handoff poll
+ * (imageGen/videoGenTimeoutMinutes). The JS race only exists so a tool whose
+ * own timer never fires cannot hold the loop forever.
+ */
+
+/** Default args.timeout the loops inject for the exec tools (ms). Building an
+ * app (npm install, cargo/gradle) routinely runs minutes; the old 30 s
+ * default + 60 s JS cap killed every real build (David 2026-06-04). */
+export const SHELL_EXECUTE_DEFAULT_TIMEOUT_MS = 600_000
+export const CODE_EXECUTE_DEFAULT_TIMEOUT_MS = 120_000
+
+const LONG_RUNNING = new Set([
+ 'shell_execute',
+ 'code_execute',
+ 'shell_execute_background',
+ 'run_tests',
+ 'git_commit',
+ 'git_push',
+])
+
+export interface ToolTimeoutSettings {
+ imageGenTimeoutMinutes?: number
+ videoGenTimeoutMinutes?: number
+}
+
+/** The JS race ceiling for one tool call, in ms. */
+export function toolCallCapMs(
+ name: string,
+ args: Record<string, any> | undefined,
+ settings: ToolTimeoutSettings,
+): number {
+ if (name === 'image_generate') {
+ return Math.max(1, Number(settings.imageGenTimeoutMinutes) || 20) * 60_000 + 120_000
+ }
+ if (name === 'video_generate') {
+ return Math.max(1, Number(settings.videoGenTimeoutMinutes) || 60) * 60_000 + 120_000
+ }
+ if (LONG_RUNNING.has(name)) {
+ const own = Number(args?.timeout)
+ return Number.isFinite(own) && own > 0 ? own + 15_000 : SHELL_EXECUTE_DEFAULT_TIMEOUT_MS + 15_000
+ }
+ return 60_000
+}
+
+/**
+ * Race a tool run against its cap. The timer is CLEARED when the tool wins
+ * (audit B10) — the old inline race left every winner's setTimeout parked
+ * for up to 615 s with the whole closure alive, times 200 iterations.
+ */
+export function raceWithToolTimeout(run: Promise<string>, name: string, capMs: number): Promise<string> {
+ let timer: ReturnType<typeof setTimeout> | undefined
+ const deadline = new Promise<string>((_, reject) => {
+ timer = setTimeout(
+ () => reject(new Error(`Tool execution timed out (${Math.round(capMs / 1000)}s)`)),
+ capMs,
+ )
+ })
+ return Promise.race([run, deadline]).finally(() => clearTimeout(timer))
+}