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(code-mode): working dir, long-build timeouts, honest completion, live thinking; turn off chat video tool
purple49459f0a1467
diff --git a/src-tauri/src/commands/remote.rs b/src-tauri/src/commands/remote.rsindex dbaf2584..7c2ef4ba 100644--- a/src-tauri/src/commands/remote.rs+++ b/src-tauri/src/commands/remote.rs@@ -572,7 +572,7 @@ async fn handle_agent_tool(}let timeout = body.args.get("timeout").and_then(|v| v.as_u64());let shell = body.args.get("shell").and_then(|v| v.as_str()).map(String::from);- crate::commands::shell::shell_execute(command, None, cwd, timeout, shell).await+ crate::commands::shell::shell_execute(command, None, cwd, timeout, shell, chat_id.clone()).await}}"system_info" => crate::commands::system::system_info(),diff --git a/src-tauri/src/commands/shell.rs b/src-tauri/src/commands/shell.rsindex d78bc14c..b4bb2b71 100644--- a/src-tauri/src/commands/shell.rs+++ b/src-tauri/src/commands/shell.rs@@ -7,16 +7,39 @@ use std::os::windows::process::CommandExt;#[cfg(target_os = "windows")]const CREATE_NO_WINDOW: u32 = 0x08000000;+use std::path::{Path, PathBuf};++/// Resolve the per-chat agent workspace (`~/agent-workspace/<chat_id>/`).+/// Mirrors commands/filesystem.rs::resolve_path so shell output lands in the+/// SAME folder the file tools write to. Used as the fallback cwd when the+/// caller doesn't pass one — without it the child process inherits the LU+/// app's ambient cwd and dumps build output into ~/Documents (David 2026-06-04).+fn workspace_cwd(chat_id: Option<&str>) -> PathBuf {+ let id = chat_id.unwrap_or("default");+ let safe: String = id+ .chars()+ .take(64)+ .map(|c| if c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.' { c } else { '_' })+ .collect();+ let slug = if safe.is_empty() { "default".to_string() } else { safe };+ dirs::home_dir()+ .unwrap_or_default()+ .join("agent-workspace")+ .join(slug)+}+#[tauri::command]+#[allow(non_snake_case)]pub async fn shell_execute(command: String,args: Option<Vec<String>>,cwd: Option<String>,timeout: Option<u64>,shell: Option<String>,+ chatId: Option<String>,) -> Result<serde_json::Value, String> {tokio::task::spawn_blocking(move || {- shell_execute_sync(command, args, cwd, timeout, shell)+ shell_execute_sync(command, args, cwd, timeout, shell, chatId)}).await.map_err(|e| format!("Task join error: {}", e))?@@ -28,6 +51,7 @@ fn shell_execute_sync(cwd: Option<String>,timeout: Option<u64>,shell: Option<String>,+ chat_id: Option<String>,) -> Result<serde_json::Value, String> {let timeout_ms = timeout.unwrap_or(120_000);let shell_bin = shell.unwrap_or_else(|| {@@ -56,12 +80,20 @@ fn shell_execute_sync(}}- // Working directory — validate it exists- if let Some(ref dir) = cwd {- let path = std::path::Path::new(dir);- if path.is_dir() {- cmd.current_dir(path);+ // Working directory. Use the explicit cwd when it exists; otherwise fall+ // back to the per-chat agent workspace (created if missing) so a relative+ // command never runs in the app's ambient cwd and scatters files into+ // ~/Documents (David 2026-06-04). Mirrors the file tools' path resolution.+ let workdir: PathBuf = match cwd.as_ref().map(|d| Path::new(d)) {+ Some(p) if p.is_dir() => p.to_path_buf(),+ _ => {+ let w = workspace_cwd(chat_id.as_deref());+ let _ = std::fs::create_dir_all(&w);+ w}+ };+ if workdir.is_dir() {+ cmd.current_dir(&workdir);}cmd.stdin(Stdio::null())diff --git a/src/api/__tests__/tool-registry.test.ts b/src/api/__tests__/tool-registry.test.tsindex 799edb67..5917ff1d 100644--- a/src/api/__tests__/tool-registry.test.ts+++ b/src/api/__tests__/tool-registry.test.ts@@ -5,6 +5,22 @@ import {getToolByName,getToolPermission,} from '../tool-registry'+import { toolRegistry, DEFAULT_PERMISSIONS } from '../mcp'++// Tools whose category is BLOCKED by default are intentionally dropped from+// getOllamaTools (it passes DEFAULT_PERMISSIONS, which excludes blocked+// categories). video_generate is OFF by default as of v2.5.0-polish+// (2026-06-04), so it must not be offered to the model.+const blockedByDefaultNames = new Set(+ toolRegistry+ .getAll()+ .filter((t) => DEFAULT_PERMISSIONS[t.category] === 'blocked')+ .map((t) => t.name),+)+const offeredDefNames = AGENT_TOOL_DEFS+ .map((t) => t.name)+ .filter((n) => !blockedByDefaultNames.has(n))+ .sort()// ── AGENT_TOOL_DEFS ─────────────────────────────────────────────@@ -94,9 +110,18 @@ describe('AGENT_TOOL_DEFS', () => {// ── getOllamaTools ──────────────────────────────────────────────describe('getOllamaTools', () => {- it('returns same number of tools as AGENT_TOOL_DEFS', () => {+ it('returns one tool per NON-blocked AGENT_TOOL_DEFS entry', () => {const ollamaTools = getOllamaTools()- expect(ollamaTools).toHaveLength(AGENT_TOOL_DEFS.length)+ // getOllamaTools filters out default-blocked categories (video), so it+ // returns AGENT_TOOL_DEFS minus those.+ expect(ollamaTools).toHaveLength(AGENT_TOOL_DEFS.length - blockedByDefaultNames.size)+ })++ it('excludes video_generate (off by default) but keeps image_generate', () => {+ const names = getOllamaTools().map((t) => t.function.name)+ expect(blockedByDefaultNames.has('video_generate')).toBe(true)+ expect(names).not.toContain('video_generate')+ expect(names).toContain('image_generate')})it('each tool has type "function" at the top level', () => {@@ -116,11 +141,10 @@ describe('getOllamaTools', () => {}})- it('preserves tool names from AGENT_TOOL_DEFS', () => {+ it('preserves (non-blocked) tool names from AGENT_TOOL_DEFS', () => {const ollamaTools = getOllamaTools()const ollamaNames = ollamaTools.map((t) => t.function.name).sort()- const defNames = AGENT_TOOL_DEFS.map((t) => t.name).sort()- expect(ollamaNames).toEqual(defNames)+ expect(ollamaNames).toEqual(offeredDefNames)})it('does not include permission field (Ollama format excludes it)', () => {diff --git a/src/api/mcp/types.ts b/src/api/mcp/types.tsindex c9d13c87..a6512070 100644--- a/src/api/mcp/types.ts+++ b/src/api/mcp/types.ts@@ -13,7 +13,11 @@ export const DEFAULT_PERMISSIONS: PermissionMap = {web: 'auto',system: 'auto',image: 'confirm',- video: 'confirm',+ // Video generation is turned OFF for now (David 2026-06-04). 'blocked'+ // removes video_generate from the tool list every model sees (see the+ // tool-selection / tool-registry filters), so it is never offered. The+ // chat Tools menu also locks the toggle. Flip back to 'confirm' to re-enable.+ video: 'blocked',workflow: 'confirm',}diff --git a/src/components/chat/CodexView.tsx b/src/components/chat/CodexView.tsxindex 7aa3148b..b3a4a0c9 100644--- a/src/components/chat/CodexView.tsx+++ b/src/components/chat/CodexView.tsx@@ -11,8 +11,9 @@ import { RealtimeCounter } from './RealtimeCounter'import { PluginsDropdown } from './PluginsDropdown'import { TypingIndicator } from './TypingIndicator'import { useSettingsStore } from '../../stores/settingsStore'+import { useModelStore } from '../../stores/modelStore'import { StagedChangesPanel } from './StagedChangesPanel'-import { User, Code, Brain, Eye, GitBranch, Download, RefreshCw, ChevronRight, ChevronDown } from 'lucide-react'+import { User, Code, Brain, Eye, GitBranch, Download, RefreshCw, RotateCcw, Folder } from 'lucide-react'import { useEffect, useRef, useState } from 'react'import { checkGitInstalled, openExternal, type GitStatus } from '../../api/backend'import { extractToolCallsWithRanges, stripRanges } from '../../lib/tool-call-repair'@@ -66,46 +67,11 @@ function stripChannelTags(text: string): string {return t.trim()}-// A single between-tool answer. The LATEST answer renders expanded; OLDER-// answers auto-collapse to a one-line preview as soon as a newer answer-// arrives, yet stay visible + clickable to re-expand (David 2026-06-02 r2:-// "jede antwort … soll auch zu sehen bleiben, aber einklappen sobald eine-// neue antwort da ist"). `isLatest` is recomputed every render from the block-// timestamps, so the previously-latest answer flips to collapsed on its own-// the moment a new answer block appears — no effect/cleanup needed.-function CollapsibleAnswer({ content, isLatest }: { content: string; isLatest: boolean }) {- const [override, setOverride] = useState<boolean | null>(null)- const expanded = override === null ? isLatest : override- if (expanded) {- return (- <div className="px-1 py-0.5">- {!isLatest && (- <button- onClick={() => setOverride(false)}- className="flex items-center gap-1 mb-0.5 text-[0.65rem] text-gray-400 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300 transition-colors"- title="Collapse this answer"- >- <ChevronDown size={10} /> collapse- </button>- )}- <div className="text-[0.75rem] leading-relaxed">- <MarkdownRenderer content={content} />- </div>- </div>- )- }- const preview = content.replace(/\s+/g, ' ').trim()- return (- <button- onClick={() => setOverride(true)}- className="group flex items-center gap-1.5 w-full text-left px-1 py-0.5 text-[0.7rem] text-gray-400 hover:text-gray-700 dark:text-gray-500 dark:hover:text-gray-300 transition-colors"- title="Show this answer"- >- <ChevronRight size={11} className="shrink-0 opacity-70 group-hover:opacity-100" />- <span className="truncate italic">{preview.slice(0, 96)}{preview.length > 96 ? '…' : ''}</span>- </button>- )-}+// Code-Mode renders EVERY between-tool answer as normal, always-visible prose+// now (David 2026-06-04: "kein Collapse, das soll ganz normal wie eine Antwort+// angezeigt werden"). The render path below dedupes verbatim repeats so a+// chatty small model can't stack the same line. (The old CollapsibleAnswer+// one-line-preview component was removed.)export function CodexView() {const { sendInstruction, stopCodex, isRunning } = useCodex()@@ -126,6 +92,9 @@ export function CodexView() {const thinkingEnabled = useSettingsStore((s) => s.settings.thinkingEnabled)const codexReviewMode = useSettingsStore((s) => s.settings.codexReviewMode)const updateSettings = useSettingsStore((s) => s.updateSettings)+ const activeModel = useModelStore((s) => s.activeModel)+ const createConversation = useChatStore((s) => s.createConversation)+ const codexWorkingDir = useCodexStore((s) => s.workingDirectory)// Git availability for the Codex view (v2.5.0). Codex shells out to git for// git_status/diff/commit/log; if git is missing those tools fail. Probe on@@ -146,6 +115,15 @@ export function CodexView() {checkGitInstalled().then(setGitStatus).catch(() => {}).finally(() => setGitChecking(false))}+ // New coding session (David 2026-06-04: "start neu" must really start new).+ // Abort any in-flight loop, then create a fresh codex conversation. The+ // working directory persists in codexStore, so the new session keeps the+ // folder; a brand-new conversation means a brand-new thread on next send.+ const startNewSession = () => {+ stopCodex()+ if (activeModel) createConversation(activeModel, '', 'codex')+ }+return (<div className="flex-1 flex overflow-hidden">{/* Main panel */}@@ -167,7 +145,29 @@ export function CodexView() {<span>Review</span></span>)}+ {/* Working directory indicator — so the user always sees WHERE the+ agent operates (David 2026-06-04: "ich hab den Ordner angegeben …+ er ist eigentlich in Dokumenten"). Empty = per-chat sandbox under+ ~/agent-workspace, which is also where shell output now lands. */}+ <span+ className="flex items-center gap-1 text-[0.5rem] text-gray-500 dark:text-gray-500 font-mono truncate max-w-[200px]"+ title={codexWorkingDir || 'Sandbox: ~/agent-workspace/<chat>'}+ >+ <Folder size={9} className="shrink-0 opacity-70" />+ <span className="truncate">{codexWorkingDir || 'sandbox · ~/agent-workspace'}</span>+ </span><div className="flex-1" />+ {/* New coding session — aborts any running loop and starts a fresh+ chat/thread (keeps the working directory). David 2026-06-04:+ "start neu" must actually start new. */}+ <button+ onClick={startNewSession}+ title="New coding session (clears the current run, keeps the folder)"+ className="flex items-center gap-1 px-1.5 py-0.5 rounded text-[0.55rem] text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-white/5 transition-colors"+ >+ <RotateCcw size={10} />+ <span>New</span>+ </button><TokenCounter /><MemoryDebugToggle /><PluginsDropdown />@@ -242,7 +242,10 @@ export function CodexView() {<div className="max-w-[85%] space-y-0.5">{/* Thinking */}{msg.role === 'assistant' && msg.thinking && (- <ThinkingBlock thinking={msg.thinking} />+ <ThinkingBlock+ thinking={msg.thinking}+ streaming={isRunning && msg.id === messages[messages.length - 1]?.id && !cleanContent.trim()}+ />)}{/* Reflection blocks (Architect plan, RepoMapcontext, etc.) — rendered above the tool calls@@ -290,29 +293,31 @@ export function CodexView() {(b.phase === 'answer' && stripChannelTags(b.content)),).sort((a, b) => a.timestamp - b.timestamp)- // The newest answer stays expanded; all earlier- // answers auto-collapse (CollapsibleAnswer).- const answerIds = ordered- .filter((b) => b.phase === 'answer')- .map((b) => b.id)- const latestAnswerId = answerIds.length- ? answerIds[answerIds.length - 1]- : nullreturn (<div className="space-y-1">- {ordered.map((block) => {+ {ordered.map((block, idx) => {if (block.phase === 'tool_call' && block.toolCall) {return <ToolCallBlock key={block.id} toolCall={block.toolCall} />}if (block.phase === 'answer') {const answer = stripChannelTags(block.content)if (!answer) return null+ // Render EVERY answer normally + always+ // visible (David 2026-06-04: "kein Collapse,+ // ganz normal wie eine Antwort"). Skip only a+ // verbatim repeat of the previous answer so+ // chatty small models don't stack duplicates.+ const prev = ordered+ .slice(0, idx)+ .reverse()+ .find((b) => b.phase === 'answer' && stripChannelTags(b.content))+ if (prev && stripChannelTags(prev.content) === answer) return nullreturn (- <CollapsibleAnswer- key={block.id}- content={answer}- isLatest={block.id === latestAnswerId}- />+ <div key={block.id} className="px-1 py-0.5">+ <div className="text-[0.75rem] leading-relaxed">+ <MarkdownRenderer content={answer} />+ </div>+ </div>)}return nulldiff --git a/src/components/chat/PermissionOverrideBar.tsx b/src/components/chat/PermissionOverrideBar.tsxindex a758f2f5..b134ac66 100644--- a/src/components/chat/PermissionOverrideBar.tsx+++ b/src/components/chat/PermissionOverrideBar.tsx@@ -3,10 +3,11 @@ import { useChatStore } from '../../stores/chatStore'import type { ToolCategory } from '../../api/mcp/types'import { FolderOpen, Terminal, Monitor, Globe, Cpu, Image, Film, GitBranch, Lock } from 'lucide-react'-// Image + Video generation are LIVE (chat agent → ComfyUI, gemma4 vision loop),-// so neither is locked anymore — both are user-toggleable on/off like every-// other category. (Kept the LOCKED mechanism for any future "coming soon" tool.)-const LOCKED: Set<ToolCategory> = new Set([])+// Image generation is LIVE (chat agent → ComfyUI). Video generation is turned+// OFF for now (David 2026-06-04): it stays in the menu but greyed-out,+// struck-through and not clickable via the LOCKED set, and `video` defaults to+// 'blocked' in DEFAULT_PERMISSIONS so the tool is never offered to the model.+const LOCKED: Set<ToolCategory> = new Set(['video'])const CATEGORIES: { key: ToolCategory; icon: typeof Globe; label: string }[] = [{ key: 'web', icon: Globe, label: 'Web' },@@ -56,7 +57,7 @@ export function PermissionOverrideBar() {) : (<Icon size={8} className={isOn ? 'text-green-400' : 'text-gray-600'} />)}- <span className="flex-1 text-left">{label}</span>+ <span className={`flex-1 text-left ${isLocked ? 'line-through' : ''}`}>{label}</span>{isLocked ? (<span className="text-[0.4rem] text-gray-700">soon</span>) : (diff --git a/src/hooks/__tests__/useCodex-fallback-answer.test.ts b/src/hooks/__tests__/useCodex-fallback-answer.test.tsindex b14444ca..e087197a 100644--- a/src/hooks/__tests__/useCodex-fallback-answer.test.ts+++ b/src/hooks/__tests__/useCodex-fallback-answer.test.ts@@ -5,6 +5,13 @@* tool calls), useCodex.ts builds a summary from AgentBlock[] so the* assistant message bubble is never blank.*+ * v2.5.0-polish (David 2026-06-04): the fallback is now HONEST — it no longer+ * prints "Task completed" when the model fired a couple of tool calls that+ * errored and then went silent. It only claims a clean finish ("Done:") when+ * something actually succeeded AND nothing failed; reports "Partially done:"+ * on mixed success/failure; and admits it couldn't finish when nothing+ * succeeded.+ ** We test the identical fallback logic in isolation and add drift detection.*/import { describe, it, expect } from 'vitest'@@ -31,30 +38,38 @@ function buildFallbackAnswer(blocks: MockBlock[]): string {if (otherCompleted > 0) parts.push(`${otherCompleted} other operation(s) completed`)if (failed.length) parts.push(`${failed.length} operation(s) failed`)- return parts.length > 0 ? `Task completed: ${parts.join(', ')}.` : 'Task completed.'+ if (completed.length === 0) {+ return failed.length+ ? `I couldn't complete the task — ${failed.length} operation(s) failed and nothing succeeded. Check the tool errors above, then refine the instruction or try a stronger model.`+ : `I stopped without completing the task — the model ended its turn without doing any work. Try rephrasing the instruction, or turn Think off and resend.`+ }+ if (failed.length > 0) {+ return `Partially done: ${parts.join(', ')}. Some steps failed — see the errors above; the result may be incomplete.`+ }+ return parts.length > 0 ? `Done: ${parts.join(', ')}.` : 'Done.'}// ── Tests ───────────────────────────────────────────────────────────────describe('Codex fallback final answer', () => {- it('produces summary for file_write operations', () => {+ it('produces a clean "Done" summary for file_write operations', () => {const blocks: MockBlock[] = [{ phase: 'tool_call', toolCall: { toolName: 'file_write', status: 'completed' } },{ phase: 'tool_call', toolCall: { toolName: 'file_write', status: 'completed' } },{ phase: 'tool_call', toolCall: { toolName: 'file_write', status: 'completed' } },]- expect(buildFallbackAnswer(blocks)).toBe('Task completed: 3 file(s) written.')+ expect(buildFallbackAnswer(blocks)).toBe('Done: 3 file(s) written.')})- it('produces summary for file_read operations', () => {+ it('produces a clean "Done" summary for file_read operations', () => {const blocks: MockBlock[] = [{ phase: 'tool_call', toolCall: { toolName: 'file_read', status: 'completed' } },{ phase: 'tool_call', toolCall: { toolName: 'file_read', status: 'completed' } },]- expect(buildFallbackAnswer(blocks)).toBe('Task completed: 2 file(s) read.')+ expect(buildFallbackAnswer(blocks)).toBe('Done: 2 file(s) read.')})- it('produces summary for mixed operations', () => {+ it('produces summary for mixed (all-success) operations', () => {const blocks: MockBlock[] = [{ phase: 'tool_call', toolCall: { toolName: 'file_read', status: 'completed' } },{ phase: 'tool_call', toolCall: { toolName: 'file_write', status: 'completed' } },@@ -63,24 +78,43 @@ describe('Codex fallback final answer', () => {{ phase: 'tool_call', toolCall: { toolName: 'file_list', status: 'completed' } },]const answer = buildFallbackAnswer(blocks)+ expect(answer.startsWith('Done:')).toBe(true)expect(answer).toContain('2 file(s) written')expect(answer).toContain('1 file(s) read')expect(answer).toContain('2 other operation(s) completed')})- it('reports failed operations', () => {+ it('reports a PARTIAL outcome when some ops succeed and some fail', () => {const blocks: MockBlock[] = [{ phase: 'tool_call', toolCall: { toolName: 'file_write', status: 'completed' } },{ phase: 'tool_call', toolCall: { toolName: 'file_write', status: 'failed' } },{ phase: 'tool_call', toolCall: { toolName: 'shell_execute', status: 'failed' } },]const answer = buildFallbackAnswer(blocks)+ expect(answer.startsWith('Partially done:')).toBe(true)expect(answer).toContain('1 file(s) written')expect(answer).toContain('2 operation(s) failed')+ // The honest fix: never the bare "Task completed" claim on a failed run.+ expect(answer).not.toContain('Task completed')+ })++ it('admits it could not finish when NOTHING succeeded (the gemma4 false-success bug)', () => {+ // Repro of David 2026-06-04: 2x shell_execute that errored, then silence —+ // the old code said "Task completed". Now it must be honest.+ const blocks: MockBlock[] = [+ { phase: 'tool_call', toolCall: { toolName: 'shell_execute', status: 'failed' } },+ { phase: 'tool_call', toolCall: { toolName: 'shell_execute', status: 'failed' } },+ ]+ const answer = buildFallbackAnswer(blocks)+ expect(answer).toContain("couldn't complete the task")+ expect(answer).toContain('nothing succeeded')+ expect(answer).not.toContain('Task completed')})- it('returns generic message when no blocks exist', () => {- expect(buildFallbackAnswer([])).toBe('Task completed.')+ it('admits it did no work when there are no blocks at all', () => {+ const answer = buildFallbackAnswer([])+ expect(answer).toContain('stopped without completing the task')+ expect(answer).not.toContain('Task completed')})it('ignores non-tool_call phases', () => {@@ -89,7 +123,7 @@ describe('Codex fallback final answer', () => {{ phase: 'streaming', toolCall: undefined },{ phase: 'tool_call', toolCall: { toolName: 'file_write', status: 'completed' } },]- expect(buildFallbackAnswer(blocks)).toBe('Task completed: 1 file(s) written.')+ expect(buildFallbackAnswer(blocks)).toBe('Done: 1 file(s) written.')})it('ignores running operations (not yet completed or failed)', () => {@@ -98,18 +132,20 @@ describe('Codex fallback final answer', () => {{ phase: 'tool_call', toolCall: { toolName: 'shell_execute', status: 'running' } },]// 'running' is neither 'completed' nor 'failed', so it's not counted- expect(buildFallbackAnswer(blocks)).toBe('Task completed: 1 file(s) written.')+ expect(buildFallbackAnswer(blocks)).toBe('Done: 1 file(s) written.')})- it('handles all-failed scenario', () => {+ it('handles all-failed scenario honestly', () => {const blocks: MockBlock[] = [{ phase: 'tool_call', toolCall: { toolName: 'file_write', status: 'failed' } },{ phase: 'tool_call', toolCall: { toolName: 'file_write', status: 'failed' } },]- expect(buildFallbackAnswer(blocks)).toBe('Task completed: 2 operation(s) failed.')+ const answer = buildFallbackAnswer(blocks)+ expect(answer).toContain("couldn't complete the task")+ expect(answer).toContain('2 operation(s) failed')})- it('handles large batch with diverse tools', () => {+ it('handles large batch with diverse tools (partial — one failure)', () => {const blocks: MockBlock[] = [...Array(5).fill(null).map(() => ({ phase: 'tool_call', toolCall: { toolName: 'file_write', status: 'completed' } })),...Array(3).fill(null).map(() => ({ phase: 'tool_call', toolCall: { toolName: 'file_read', status: 'completed' } })),@@ -118,6 +154,7 @@ describe('Codex fallback final answer', () => {{ phase: 'tool_call', toolCall: { toolName: 'file_write', status: 'failed' } },]const answer = buildFallbackAnswer(blocks)+ expect(answer.startsWith('Partially done:')).toBe(true)expect(answer).toContain('5 file(s) written')expect(answer).toContain('3 file(s) read')expect(answer).toContain('3 other operation(s) completed')@@ -127,16 +164,19 @@ describe('Codex fallback final answer', () => {// ── Drift detection ─────────────────────────────────────────────────────describe('fallback answer drift detection', () => {- it('useCodex.ts contains the fallback summary builder', () => {+ it('useCodex.ts contains the honest fallback summary builder', () => {const __filename = fileURLToPath(import.meta.url)const __dirname = dirname(__filename)const src = readFileSync(join(__dirname, '../useCodex.ts'), 'utf8')// Must contain the fallback trigger- expect(src).toContain("if (!fullContent.trim())")+ expect(src).toContain('if (!fullContent.trim())')// Must build parts array with file write/read counts- expect(src).toContain("file(s) written")- expect(src).toContain("file(s) read")- expect(src).toContain("Task completed:")+ expect(src).toContain('file(s) written')+ expect(src).toContain('file(s) read')+ // Must use the honest wording, NOT the old false "Task completed:" claim.+ expect(src).toContain('Partially done:')+ expect(src).toContain("couldn't complete the task")+ expect(src).not.toContain('Task completed:')})})diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex 1d4bbc5f..205007ae 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -467,7 +467,12 @@ export function useAgentChat() {const wantsImage = /\b(bild|bilder|foto|image|picture|pic|draw|zeichne|mal(e|en)?|grafik|illustration|render)\b/i.test(userPromptText)const wantsVideo = /\b(video|clip|animier\w*|animate|film|gif|bewegt|motion|mp4|webm)\b/i.test(userPromptText)const maxImageGen = wantsVideo && !wantsImage ? 0 : 1- const maxVideoGen = wantsVideo ? 1 : 0+ // Video generation is turned OFF in the chat tools (video defaults to+ // 'blocked' + locked toggle, David 2026-06-04). Respect that here so the+ // deterministic media-synthesis fallback below never force-creates a video+ // the user disabled.+ const videoAllowed = permissions.video !== 'blocked'+ const maxVideoGen = wantsVideo && videoAllowed ? 1 : 0let imageGenDone = 0let videoGenDone = 0let mediaSteered = falsediff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.tsindex 54d003b7..7be61aa7 100644--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@ -456,6 +456,17 @@ export function useCodex() {agentMaxIterations: settings.agentMaxIterations ?? 200,})+ // num_ctx for the coding loop. Code-Mode previously sent NO num_ctx, so+ // Ollama used its small default (~4k) while compaction trimmed to the+ // model's max → the history overflowed the real window and weak models+ // (gemma4 with Think on) returned EMPTY turns, which the loop misread as+ // "done" and printed a false "Task completed" (David 2026-06-04). Pin a+ // sane floor (user override wins) and compact to it so both agree.+ const numCtx =+ settings.contextWindowOverride && settings.contextWindowOverride > 0+ ? settings.contextWindowOverride+ : 8192+try {// Agent loop — max 20 iterations (legacy cap) AND AgentBudget cap,// whichever is tighter.@@ -527,10 +538,9 @@ export function useCodex() {// 8K-context local models blow past their window after a few tool// calls and Ollama starts silently truncating or errors out.try {- const maxCtx = await getModelMaxTokens(activeModel)messages = compactMessages(messages as unknown as OllamaChatMessage[],- Math.floor(maxCtx * 0.8),+ Math.floor(numCtx * 0.8),) as unknown as ChatMessage[]} catch {// Compaction is best-effort; fall through with raw history.@@ -602,7 +612,7 @@ export function useCodex() {void diagLog('streamWithTools-enter', { iter: i, messagesLen: messages.length, toolsCount: tools.length, thinking: chatOptions.thinking })turn = await streamWithTools(modelToUse, messages, tools,- { temperature: 0.1, thinking: chatOptions.thinking, maxTokens: chatOptions.maxTokens, signal: abort.signal },+ { temperature: 0.1, thinking: chatOptions.thinking, maxTokens: chatOptions.maxTokens, contextWindow: numCtx, signal: abort.signal },liveContent,(t) => {if (keepThinking) {@@ -622,7 +632,7 @@ export function useCodex() {if (thinkErr?.statusCode === 400 || thinkErr?.message?.includes('does not support thinking')) {turn = await streamWithTools(modelToUse, messages, tools,- { temperature: 0.1, thinking: undefined, maxTokens: chatOptions.maxTokens, signal: abort.signal },+ { temperature: 0.1, thinking: undefined, maxTokens: chatOptions.maxTokens, contextWindow: numCtx, signal: abort.signal },liveContent,() => {},)@@ -871,13 +881,22 @@ export function useCodex() {// Inject working directory for file/shell tools (skip if workDir is just '.' or empty)const hasValidWorkDir = workDir && workDir !== '.' && workDir.length > 2- if (toolName === 'shell_execute' && !toolArgs.cwd) {- if (hasValidWorkDir) toolArgs.cwd = workDir- if (!toolArgs.timeout) toolArgs.timeout = 30000+ // Working directory + a GENEROUS default timeout for shell/code tools.+ // When a folder is picked we pass it as cwd; otherwise the Rust side+ // resolves the per-chat ~/agent-workspace/<slug> (never the app's+ // ambient cwd, which used to dump build output into ~/Documents).+ // The timeout must be LONG: building an app (npm install, cargo/gradle+ // build) routinely runs minutes. The old 30s default + 60s JS hard-cap+ // killed every real build → "coding agent can't build anything /+ // always times out" (David 2026-06-04). The model can still pass its+ // own timeout to go higher/lower.+ if (toolName === 'shell_execute') {+ if (!toolArgs.cwd && hasValidWorkDir) toolArgs.cwd = workDir+ if (!toolArgs.timeout) toolArgs.timeout = 600000}- if (toolName === 'code_execute' && !toolArgs.cwd) {- if (hasValidWorkDir) toolArgs.cwd = workDir- if (!toolArgs.timeout) toolArgs.timeout = 30000+ if (toolName === 'code_execute') {+ if (!toolArgs.cwd && hasValidWorkDir) toolArgs.cwd = workDir+ if (!toolArgs.timeout) toolArgs.timeout = 120000}// Resolve relative file paths against working directory.// Absolute-path detection must accept ANY drive letter (C:, D:, E:, …),@@ -941,13 +960,29 @@ 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>) =>- Promise.race([+ 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.+ 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 = 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 (60s)')), 60000)+ setTimeout(() => reject(new Error(`Tool execution timed out (${Math.round(capMs / 1000)}s)`)), capMs)),])+ }// Multi-File Stage-and-Approve (B10). When the user has codex// stage mode on, file_write calls don't hit the disk — they@@ -1139,9 +1174,21 @@ export function useCodex() {if (otherCompleted > 0) parts.push(`${otherCompleted} other operation(s) completed`)if (failed.length) parts.push(`${failed.length} operation(s) failed`)- fullContent = parts.length > 0- ? `Task completed: ${parts.join(', ')}.`- : 'Task completed.'+ // Be HONEST about the outcome. The old code printed "Task completed"+ // even when the model fired a couple of shell commands that errored and+ // then went silent — the false-success David hit (gemma4: 2x+ // shell_execute → "Task completed 1" with nothing built, 2026-06-04).+ // Only claim a clean finish when something actually succeeded AND+ // nothing failed.+ if (completed.length === 0) {+ fullContent = failed.length+ ? `I couldn't complete the task — ${failed.length} operation(s) failed and nothing succeeded. Check the tool errors above, then refine the instruction or try a stronger model.`+ : `I stopped without completing the task — the model ended its turn without doing any work. Try rephrasing the instruction, or turn Think off and resend.`+ } else if (failed.length > 0) {+ fullContent = `Partially done: ${parts.join(', ')}. Some steps failed — see the errors above; the result may be incomplete.`+ } else {+ fullContent = parts.length > 0 ? `Done: ${parts.join(', ')}.` : 'Done.'+ }useChatStore.getState().updateMessageContent(convId, assistantMsg.id, fullContent)}@@ -1172,7 +1219,7 @@ export function useCodex() {} else if (/does not support tools|tool.*not.*support/i.test(msg)) {hint = '\n\nHint: this model does not support native tool calling. Pick a tool-capable model (Qwen 3, Llama 3.1+, Gemma 4) or switch to a model without the coder-only restriction.'} else if (/timed out/i.test(msg)) {- hint = '\n\nHint: the tool call took longer than 60 s. Try a smaller model or a more targeted prompt.'+ hint = '\n\nHint: a tool call exceeded its time budget. For long builds, raise the command timeout, split the work, or run it via shell_execute_background.'}fullContent += `\n\nError: ${msg}${hint}`useChatStore.getState().updateMessageContent(convId, assistantMsg.id, fullContent)