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
Phase 5b: Wire tool-executor into useAgentChat + useCodex (v2.4.0)
PurpleDoubleD49f822e4c4e8
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex 0459f02f..f6dc0042 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -26,6 +26,8 @@ import type { AgentBlock, AgentToolCall, OllamaChatMessage } from '../types/agenimport { selectRelevantTools } from '../lib/tool-selection'import type { ChatMessage, ToolCall, ToolDefinition } from '../api/providers/types'import type { StepResult, WorkflowEngineCallbacks } from '../types/agent-workflows'+import { executeParallel, applyResultToToolCall, type ExecutionRequest } from '../api/agents/tool-executor'+import { useToolAuditStore } from '../stores/toolAuditStore'// ── Standalone memory extraction (usable outside React hooks) ──@@ -117,6 +119,25 @@ export function useAgentChat() {}}+ /**+ * ID-keyed block update — used by the parallel tool executor (Phase 5) so+ * N concurrent tool-call blocks can update independently as their results+ * land out of order. Falls back to no-op on unknown id.+ */+ function updateBlockById(+ convId: string,+ msgId: string,+ blockId: string,+ updates: Partial<AgentBlock>+ ) {+ const idx = blocksRef.current.findIndex((b) => b.id === blockId)+ if (idx < 0) return+ const blocks = [...blocksRef.current]+ blocks[idx] = { ...blocks[idx], ...updates }+ blocksRef.current = blocks+ useChatStore.getState().updateMessageAgentBlocks(convId, msgId, blocks)+ }+// ── Main agent message handler ────────────────────────────const sendAgentMessage = useCallback(async (userContent: string, userImages?: import('../types/chat').ImageAttachment[]) => {@@ -457,160 +478,185 @@ export function useAgentChat() {// If no tool calls, the model is doneif (toolCalls.length === 0) break- // Process each tool call+ // Phase 5b (v2.4.0) — parallel tool execution via tool-executor.+ //+ // Pre-create AgentToolCall + block per tc so the UI can render all+ // of them concurrently before any runs. Then executeParallel runs+ // them respecting sideEffectKey (file_write same-path serializes,+ // shell/code share an 'exec' queue, image/workflow share 'comfyui',+ // pure reads fully parallel).+ if (!runningRef.current || abort.signal.aborted) break++ type BatchEntry = { tc: typeof toolCalls[number]; ac: AgentToolCall; blockId: string }+ const batch: BatchEntry[] = []for (const tc of toolCalls) {- if (!runningRef.current || abort.signal.aborted) break-const toolCallId = uuid()- const agentToolCall: AgentToolCall = {+ const blockId = uuid()+ const permLevel = toolRegistry.getPermissionLevel(tc.function.name, permissions)+ const needsApproval = permLevel !== 'auto'+ const ac: AgentToolCall = {id: toolCallId,toolName: tc.function.name,args: tc.function.arguments,- status: 'running',+ status: needsApproval ? 'pending_approval' : 'running',timestamp: Date.now(),}+ addBlock(convId!, assistantMessage.id, {+ id: blockId,+ phase: 'tool_call',+ content: needsApproval+ ? `Requesting approval: ${tc.function.name}`+ : `Running: ${tc.function.name}`,+ toolCall: ac,+ toolCalls: [ac],+ timestamp: Date.now(),+ })+ batch.push({ tc, ac, blockId })+ }- // Check permission via new registry- const permLevel = toolRegistry.getPermissionLevel(tc.function.name, permissions)- const permission = permLevel === 'auto' ? 'auto' : 'confirm'-- if (permission === 'confirm') {- agentToolCall.status = 'pending_approval'- addBlock(convId!, assistantMessage.id, {- id: uuid(),- phase: 'tool_call',- content: `Requesting approval: ${tc.function.name}`,- toolCall: agentToolCall,- timestamp: Date.now(),- })-- const approved = await waitForApproval(agentToolCall)-- if (!approved) {- agentToolCall.status = 'rejected'- updateLastBlock(convId!, assistantMessage.id, {- toolCall: { ...agentToolCall, status: 'rejected' },- content: `Rejected: ${tc.function.name}`,+ const requests: ExecutionRequest[] = batch.map((e) => ({+ id: e.ac.id,+ toolName: e.ac.toolName,+ args: e.ac.args,+ }))+ const auditIds = new Map<string, string>()++ const results = await executeParallel(requests, {+ getTool: (name) => {+ 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),+ awaitApproval: async (req) => {+ const entry = batch.find((e) => e.ac.id === req.id)+ if (!entry) return false+ const approved = await waitForApproval(entry.ac)+ if (approved) {+ entry.ac.status = 'running'+ updateBlockById(convId!, assistantMessage.id, entry.blockId, {+ toolCall: { ...entry.ac },+ toolCalls: [{ ...entry.ac }],+ content: `Running: ${entry.ac.toolName}`,})-- // Feed rejection back- agentMessages.push({- role: 'assistant',- content: turnContent || '',- tool_calls: [tc],+ }+ return approved+ },+ recordAudit: (entry) => {+ if (!convId) return+ if (entry.kind === 'start') {+ const aid = useToolAuditStore.getState().record({+ convId,+ toolCallId: entry.id,+ toolName: entry.toolName,+ args: entry.args,+ startedAt: entry.startedAt,+ parentToolCallId: entry.parentToolCallId,})-- if (providerId === 'openai' || providerId === 'anthropic') {- agentMessages.push({- role: 'tool',- content: 'User rejected this action. Try a different approach.',- tool_call_id: tc.id,- })- } else if (strategy === 'native') {- agentMessages.push({- role: 'tool',- content: 'User rejected this action. Try a different approach.',- })- } else {- agentMessages.push({- role: 'user',- content: buildHermesToolResult(tc.function.name, 'User rejected this action. Try a different approach.'),+ auditIds.set(entry.id, aid)+ } else {+ const aid = auditIds.get(entry.id)+ if (aid) {+ useToolAuditStore.getState().complete(aid, {+ status: entry.status,+ completedAt: entry.completedAt,+ resultPreview: entry.resultPreview,+ error: entry.error,+ errorHint: entry.errorHint,+ cacheHit: entry.cacheHit,})}- continue}+ },+ abortSignal: abort.signal,+ })- agentToolCall.status = 'running'- updateLastBlock(convId!, assistantMessage.id, {- toolCall: { ...agentToolCall, status: 'running' },- content: `Running: ${tc.function.name}`,- })- } else {- addBlock(convId!, assistantMessage.id, {- id: uuid(),- phase: 'tool_call',- content: `Running: ${tc.function.name}`,- toolCall: agentToolCall,- timestamp: Date.now(),- })- }-- // Execute the tool- const startTime = Date.now()- const result = await toolRegistry.execute(tc.function.name, tc.function.arguments)- const duration = Date.now() - startTime-- // Update block with result- const isError = result.startsWith('Error:')- agentToolCall.status = isError ? 'failed' : 'completed'- agentToolCall.result = isError ? undefined : result- agentToolCall.error = isError ? result : undefined- agentToolCall.duration = duration-- updateLastBlock(convId!, assistantMessage.id, {- toolCall: { ...agentToolCall },- content: isError ? `Failed: ${tc.function.name}` : `Completed: ${tc.function.name}`,+ // Apply results back onto blocks + memory + LLM history.+ for (const entry of batch) {+ const result = results.find((r) => r.id === entry.ac.id)+ if (!result) continue+ applyResultToToolCall(entry.ac, result)+ const contentLabel =+ result.status === 'completed'+ ? `Completed: ${entry.ac.toolName}`+ : result.status === 'cached'+ ? `Cached: ${entry.ac.toolName}`+ : result.status === 'rejected'+ ? `Rejected: ${entry.ac.toolName}`+ : `Failed: ${entry.ac.toolName}`+ updateBlockById(convId!, assistantMessage.id, entry.blockId, {+ toolCall: { ...entry.ac },+ toolCalls: [{ ...entry.ac }],+ content: contentLabel,})- // Auto-save tool result to memory- if (!isError) {- const argsShort = JSON.stringify(tc.function.arguments).substring(0, 100)- const resultShort = result.substring(0, 200)+ if ((result.status === 'completed' || result.status === 'cached') && entry.ac.result) {+ const argsShort = JSON.stringify(entry.ac.args).substring(0, 100)+ const resultShort = entry.ac.result.substring(0, 200)useMemoryStore.getState().addMemory({type: 'reference',- title: `${tc.function.name} result`,- description: `${tc.function.name}(${argsShort.substring(0, 60)}) → ${resultShort.substring(0, 60)}`,- content: `${tc.function.name}(${argsShort}) → ${resultShort}`,- tags: [`agent:${tc.function.name}`],+ title: `${entry.ac.toolName} result`,+ description: `${entry.ac.toolName}(${argsShort.substring(0, 60)}) → ${resultShort.substring(0, 60)}`,+ content: `${entry.ac.toolName}(${argsShort}) → ${resultShort}`,+ tags: [`agent:${entry.ac.toolName}`],source: convId || 'agent',})}+ }- // Append tool call + result to messages for next iteration- if (providerId === 'openai') {- // OpenAI format: assistant with tool_calls, then tool role with tool_call_id- agentMessages.push({- role: 'assistant',- content: turnContent || '',- tool_calls: [tc],- })- agentMessages.push({- role: 'tool',- content: result,- tool_call_id: tc.id,- })- } else if (providerId === 'anthropic') {- // Anthropic format: same structure, tool_call_id maps to tool_use id- agentMessages.push({- role: 'assistant',- content: turnContent || '',- tool_calls: [tc],- })+ // Feed results back into LLM history. Format differs per provider:+ // OpenAI / Anthropic / Ollama native: ONE assistant message with+ // tool_calls[] + N tool messages (one per result). This preserves+ // the provider's expected structure when multiple tool calls come+ // back in one assistant turn.+ // Hermes XML fallback: pairs (assistant <tool_call> → user result),+ // kept per-call for compatibility with how the non-native path+ // parses history.+ const resultTextFor = (r: typeof results[number]): string => {+ if (r.status === 'rejected') return 'User rejected this action. Try a different approach.'+ if (r.status === 'completed' || r.status === 'cached') return r.result ?? ''+ // failed+ return r.errorHint ? `${r.error ?? 'Tool failed'} — ${r.errorHint}` : (r.error ?? 'Tool failed')+ }++ if (providerId === 'openai' || providerId === 'anthropic') {+ agentMessages.push({+ role: 'assistant',+ content: turnContent || '',+ tool_calls: toolCalls,+ })+ for (const { tc } of batch) {+ const result = results.find((r) => r.id === batch.find((b) => b.tc === tc)?.ac.id)!agentMessages.push({role: 'tool',- content: result,+ content: resultTextFor(result),tool_call_id: tc.id,})- } else if (strategy === 'native') {- // Ollama native- agentMessages.push({- role: 'assistant',- content: turnContent || '',- tool_calls: [{ function: { name: tc.function.name, arguments: tc.function.arguments } }],- })+ }+ } else if (strategy === 'native') {+ agentMessages.push({+ role: 'assistant',+ content: turnContent || '',+ tool_calls: toolCalls.map((tc) => ({+ function: { name: tc.function.name, arguments: tc.function.arguments },+ })),+ })+ for (const { tc } of batch) {+ const result = results.find((r) => r.id === batch.find((b) => b.tc === tc)?.ac.id)!agentMessages.push({role: 'tool',- content: result,+ content: resultTextFor(result),})- } else {- // Hermes XML+ }+ } else {+ for (const { tc } of batch) {+ const result = results.find((r) => r.id === batch.find((b) => b.tc === tc)?.ac.id)!agentMessages.push({role: 'assistant',content: `<tool_call>\n{"name": "${tc.function.name}", "arguments": ${JSON.stringify(tc.function.arguments)}}\n</tool_call>`,})agentMessages.push({role: 'user',- content: buildHermesToolResult(tc.function.name, result),+ content: buildHermesToolResult(tc.function.name, resultTextFor(result)),})}}diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.tsindex e840f0ea..642c86ac 100644--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@ -15,6 +15,8 @@ import type { AgentBlock, AgentToolCall } from '../types/agent-mode'import { selectRelevantTools } from '../lib/tool-selection'import { isThinkingCompatible } from '../lib/model-compatibility'import type { ChatMessage, ToolCall, ToolDefinition } from '../api/providers/types'+import { executeParallel, applyResultToToolCall, type ExecutionRequest } from '../api/agents/tool-executor'+import { useToolAuditStore } from '../stores/toolAuditStore'const CODEX_SYSTEM_PROMPT = `You are Codex, an autonomous coding agent inside Locally Uncensored. You execute coding tasks by reading files, writing code, and running shell commands. You MUST use tools to interact with the filesystem — never guess file contents.@@ -85,6 +87,12 @@ export function useCodex() {blocks.push(block)useChatStore.getState().updateMessageAgentBlocks(convId!, assistantMsg.id, [...blocks])}+ function updateBlockById(blockId: string, updates: Partial<AgentBlock>) {+ const idx = blocks.findIndex((b) => b.id === blockId)+ if (idx < 0) return+ blocks[idx] = { ...blocks[idx], ...updates }+ useChatStore.getState().updateMessageAgentBlocks(convId!, assistantMsg.id, [...blocks])+ }// Resolve providerconst { provider, modelId } = getProviderForModel(activeModel)@@ -242,26 +250,23 @@ export function useCodex() {// No tool calls → doneif (toolCalls.length === 0) break- // Execute tool calls- for (const tc of toolCalls) {- if (!runningRef.current || abort.signal.aborted) break+ // Phase 5b (v2.4.0) — parallel tool execution via tool-executor.+ if (!runningRef.current || abort.signal.aborted) break+ type BatchEntry = { tc: typeof toolCalls[number]; ac: AgentToolCall; blockId: string; injectedArgs: Record<string, any> }+ const batch: BatchEntry[] = []+ for (const tc of toolCalls) {const toolName = tc.function.nameconst toolArgs = { ...tc.function.arguments }// Inject working directory for file/shell tools (skip if workDir is just '.' or empty)const hasValidWorkDir = workDir && workDir !== '.' && workDir.length > 2if (toolName === 'shell_execute' && !toolArgs.cwd) {- if (hasValidWorkDir) {- toolArgs.cwd = workDir- }- // Without a valid cwd, shell_execute will use default — add timeout guard+ if (hasValidWorkDir) toolArgs.cwd = workDirif (!toolArgs.timeout) toolArgs.timeout = 30000}if (toolName === 'code_execute' && !toolArgs.cwd) {- if (hasValidWorkDir) {- toolArgs.cwd = workDir- }+ if (hasValidWorkDir) toolArgs.cwd = workDirif (!toolArgs.timeout) toolArgs.timeout = 30000}// Resolve relative file paths against working directory@@ -272,78 +277,141 @@ export function useCodex() {}}- // Create tool call block (visible in chat)const toolCallId = uuid()- const agentToolCall: AgentToolCall = {+ const blockId = uuid()+ const ac: AgentToolCall = {id: toolCallId, toolName, args: toolArgs,status: 'running', timestamp: Date.now(),}addBlock({- id: uuid(), phase: 'tool_call', content: `Running: ${toolName}`,- toolCall: agentToolCall, timestamp: Date.now(),+ id: blockId, phase: 'tool_call', content: `Running: ${toolName}`,+ toolCall: ac, toolCalls: [ac], timestamp: Date.now(),})+ batch.push({ tc, ac, blockId, injectedArgs: toolArgs })+ }- // Execute with timeout guard (60s max to prevent freeze)- const startTime = Date.now()- const toolTimeout = 60000- let result: string- try {- result = await Promise.race([- toolRegistry.execute(toolName, toolArgs),- new Promise<string>((_, reject) =>- setTimeout(() => reject(new Error('Tool execution timed out (60s)')), toolTimeout)- ),- ])- } catch (timeoutErr) {- result = `Error: ${(timeoutErr as Error).message}`- }- const duration = Date.now() - startTime- const isError = result.startsWith('Error:')-- // Update block with result- agentToolCall.status = isError ? 'failed' : 'completed'- agentToolCall.result = isError ? undefined : result- agentToolCall.error = isError ? result : undefined- agentToolCall.duration = duration- const lastBlock = blocks[blocks.length - 1]- if (lastBlock) {- lastBlock.toolCall = { ...agentToolCall }- lastBlock.content = isError ? `Failed: ${toolName}` : `Completed: ${toolName}`- useChatStore.getState().updateMessageAgentBlocks(convId!, assistantMsg.id, [...blocks])- }+ const requests: ExecutionRequest[] = batch.map((e) => ({+ id: e.ac.id,+ toolName: e.ac.toolName,+ args: e.injectedArgs,+ }))+ const auditIds = new Map<string, string>()++ // 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([+ toolRegistry.execute(name, args),+ new Promise<string>((_, reject) =>+ setTimeout(() => reject(new Error('Tool execution timed out (60s)')), 60000)+ ),+ ])++ const results = await executeParallel(requests, {+ getTool: (name) => {+ const td = toolRegistry.getToolByName(name)+ return td ? { name: td.name, inputSchema: td.inputSchema } : undefined+ },+ execute: (name: string, args: Record<string, any>) => withTimeout(name, args),+ // Codex is auto-approve (coding agent runs unattended). The+ // awaitApproval hook is intentionally omitted so the executor+ // dispatches immediately.+ recordAudit: (entry) => {+ if (!convId) return+ if (entry.kind === 'start') {+ const aid = useToolAuditStore.getState().record({+ convId,+ toolCallId: entry.id,+ toolName: entry.toolName,+ args: entry.args,+ startedAt: entry.startedAt,+ parentToolCallId: entry.parentToolCallId,+ })+ auditIds.set(entry.id, aid)+ } else {+ const aid = auditIds.get(entry.id)+ if (aid) {+ useToolAuditStore.getState().complete(aid, {+ status: entry.status,+ completedAt: entry.completedAt,+ resultPreview: entry.resultPreview,+ error: entry.error,+ errorHint: entry.errorHint,+ cacheHit: entry.cacheHit,+ })+ }+ }+ },+ abortSignal: abort.signal,+ })- // Also add codex event for the event log- if (toolName === 'shell_execute' || toolName === 'code_execute') {+ for (const entry of batch) {+ const result = results.find((r) => r.id === entry.ac.id)+ if (!result) continue+ applyResultToToolCall(entry.ac, result)+ const isError = result.status === 'failed'+ updateBlockById(entry.blockId, {+ toolCall: { ...entry.ac },+ toolCalls: [{ ...entry.ac }],+ content:+ result.status === 'completed'+ ? `Completed: ${entry.ac.toolName}`+ : result.status === 'cached'+ ? `Cached: ${entry.ac.toolName}`+ : `Failed: ${entry.ac.toolName}`,+ })++ // Codex event log parity with the old path.+ const resultStr = entry.ac.result ?? entry.ac.error ?? ''+ if (entry.ac.toolName === 'shell_execute' || entry.ac.toolName === 'code_execute') {codexStore.addEvent(convId, {- id: uuid(), type: 'terminal_output', content: result, timestamp: Date.now(),+ id: uuid(), type: 'terminal_output', content: resultStr, timestamp: Date.now(),})- } else if (toolName === 'file_write') {+ } else if (entry.ac.toolName === 'file_write') {codexStore.addEvent(convId, {- id: uuid(), type: 'file_change', content: result,- filePath: toolArgs.path, timestamp: Date.now(),+ id: uuid(), type: 'file_change', content: resultStr,+ filePath: entry.injectedArgs.path, timestamp: Date.now(),})} else if (isError) {codexStore.addEvent(convId, {- id: uuid(), type: 'error', content: result, timestamp: Date.now(),+ id: uuid(), type: 'error', content: resultStr, timestamp: Date.now(),})}+ }- // Append to message history- if (providerId === 'openai' || providerId === 'anthropic') {- messages.push({ role: 'assistant', content: turnContent || '', tool_calls: [tc] })- messages.push({ role: 'tool', content: result, tool_call_id: tc.id })- } else if (strategy === 'native') {- messages.push({- role: 'assistant', content: turnContent || '',- tool_calls: [{ function: { name: toolName, arguments: toolArgs } }],- })- messages.push({ role: 'tool', content: result })- } else {+ // Feed results back into LLM history (batched per-provider shape).+ const resultTextFor = (r: typeof results[number]): string => {+ if (r.status === 'completed' || r.status === 'cached') return r.result ?? ''+ return r.errorHint ? `${r.error ?? 'Tool failed'} — ${r.errorHint}` : (r.error ?? 'Tool failed')+ }++ if (providerId === 'openai' || providerId === 'anthropic') {+ messages.push({ role: 'assistant', content: turnContent || '', tool_calls: toolCalls })+ for (const { tc } of batch) {+ const result = results.find((r) => r.id === batch.find((b) => b.tc === tc)?.ac.id)!+ messages.push({ role: 'tool', content: resultTextFor(result), tool_call_id: tc.id })+ }+ } else if (strategy === 'native') {+ messages.push({+ role: 'assistant',+ content: turnContent || '',+ tool_calls: batch.map((e) => ({+ function: { name: e.ac.toolName, arguments: e.injectedArgs },+ })),+ })+ for (const { tc } of batch) {+ const result = results.find((r) => r.id === batch.find((b) => b.tc === tc)?.ac.id)!+ messages.push({ role: 'tool', content: resultTextFor(result) })+ }+ } else {+ for (const entry of batch) {+ const result = results.find((r) => r.id === entry.ac.id)!messages.push({role: 'assistant',- content: `<tool_call>\n{"name": "${toolName}", "arguments": ${JSON.stringify(toolArgs)}}\n</tool_call>`,+ content: `<tool_call>\n{"name": "${entry.ac.toolName}", "arguments": ${JSON.stringify(entry.injectedArgs)}}\n</tool_call>`,})- messages.push({ role: 'user', content: buildHermesToolResult(toolName, result) })+ messages.push({ role: 'user', content: buildHermesToolResult(entry.ac.toolName, resultTextFor(result)) })}}}