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): the task survives the window, and the run's end stops hanging the app
purplea52b386c609f
diff --git a/src/api/__tests__/context-compaction.test.ts b/src/api/__tests__/context-compaction.test.tsindex db0b758b..5ad4c489 100644--- a/src/api/__tests__/context-compaction.test.ts+++ b/src/api/__tests__/context-compaction.test.ts@@ -79,15 +79,49 @@ describe('compactMessages', () => {{ role: 'assistant', content: 'Recent answer' },]const result = compactMessages(messages, 200)- expect(result.length).toBeLessThan(messages.length)+ // The token load shrinks; the message COUNT may not, because the pinned+ // task (audit C5) rides along where dropped content used to be.+ expect(estimateMessageTokens(result)).toBeLessThan(estimateMessageTokens(messages))// System prompt always preservedexpect(result[0].role).toBe('system')expect(result[0].content).toBe('System prompt')+ // The ORIGINAL TASK is pinned right after the system prompt (audit C5) —+ // before the pin, the oldest message was exactly the first to be dropped,+ // so a long run forgot what it was asked to do.+ expect(result[1].role).toBe('user')+ expect(result[1].content).toContain('First question')// Recent messages preservedconst lastMsg = result[result.length - 1]expect(lastMsg.content).toBe('Recent answer')})+ it('caps a giant pinned task instead of carrying it forever', () => {+ const messages: OllamaChatMessage[] = [+ { role: 'system', content: 'System prompt' },+ { role: 'user', content: 'fix this file: ' + 'x'.repeat(50_000) },+ ...Array.from({ length: 10 }, (_, i) => ({+ role: (i % 2 === 0 ? 'assistant' : 'user') as 'assistant' | 'user',+ content: `Message ${i} `.repeat(80),+ })),+ ]+ const result = compactMessages(messages, 500)+ const pinned = result[1]+ expect(pinned.role).toBe('user')+ expect(pinned.content).toContain('fix this file')+ expect(pinned.content.length).toBeLessThan(10_000)+ })++ it('does not duplicate the task when it already survived into the suffix', () => {+ const messages: OllamaChatMessage[] = [+ { role: 'system', content: 'System prompt' },+ { role: 'user', content: 'the only question' },+ { role: 'assistant', content: 'Answer '.repeat(400) },+ ]+ const result = compactMessages(messages, 120)+ const userCopies = result.filter((m) => m.role === 'user' && m.content.includes('the only question'))+ expect(userCopies.length).toBe(1)+ })+it('preserves system prompt always', () => {const messages: OllamaChatMessage[] = [{ role: 'system', content: 'Important system prompt' },diff --git a/src/components/chat/CodexEventBlock.tsx b/src/components/chat/CodexEventBlock.tsxindex 16dce5a4..26f30afd 100644--- a/src/components/chat/CodexEventBlock.tsx+++ b/src/components/chat/CodexEventBlock.tsx@@ -1,5 +1,5 @@import { Terminal, FileEdit, Brain, AlertCircle, CheckCircle, ChevronDown } from 'lucide-react'-import { useState } from 'react'+import { useState, memo } from 'react'import type { CodexEvent } from '../../types/codex'import { DiffView } from './DiffView'@@ -7,7 +7,11 @@ interface Props {event: CodexEvent}-export function CodexEventBlock({ event }: Props) {+// memo (audit D2): events are append-only, so every existing block can skip+// re-rendering while the transcript streams.+export const CodexEventBlock = memo(CodexEventBlockImpl)++function CodexEventBlockImpl({ event }: Props) {const [open, setOpen] = useState(event.type === 'error')if (event.type === 'instruction' || event.type === 'done') return nulldiff --git a/src/components/chat/ToolCallBlock.tsx b/src/components/chat/ToolCallBlock.tsxindex 8fa77998..7e309b81 100644--- a/src/components/chat/ToolCallBlock.tsx+++ b/src/components/chat/ToolCallBlock.tsx@@ -1,11 +1,12 @@-import { useState } from 'react'+import { useState, memo } from 'react'import { motion, AnimatePresence } from 'framer-motion'-import { Search, Globe, FileText, FileEdit, Terminal, Image, Film, Loader2, Check, X, Clock, AlertCircle, FolderOpen, Cpu, Monitor, GitBranch, Database, Download } from 'lucide-react'+import { Search, Globe, FileText, FileEdit, Terminal, Image, Film, Loader2, Check, X, Clock, AlertCircle, FolderOpen, Cpu, Monitor, GitBranch, GitCompare, GitCommitHorizontal, GitPullRequest, FlaskConical, History, Users, Database, Download } from 'lucide-react'import type { AgentToolCall } from '../../types/agent-mode'import { getComfyHost, getComfyPort, downloadComfyFile } from '../../api/backend'import { useModelPickStore } from '../../stores/modelPickStore'import { useGenerationStore } from '../../stores/generationStore'import { ModelPickerCard, ChangeModelInline, pickKindForToolCall } from './ModelPickerCard'+import { DiffView } from './DiffView'import { requestGenerationCancel } from '../../api/vram-handoff'// F1 (konata3602 commitment 2026-05-23) + render fix (konata3602 bug 2026-06-07)@@ -100,21 +101,40 @@ interface Props {onReject?: () => void}+// Complete over the registry (audit D4): 16 of 29 tools had no entry and fell+// back to the Terminal icon, so a git_commit looked like a shell command and+// a surgical file_edit like a plain write. Every builtin has a face now.const TOOL_ICONS: Record<string, typeof Search> = {web_search: Search,web_fetch: Globe,file_read: FileText,file_write: FileEdit,+ file_edit: FileEdit,file_list: FolderOpen,file_search: Search,code_execute: Terminal,shell_execute: Terminal,+ shell_execute_background: History,+ shell_task_status: History,+ shell_task_list: History,+ shell_task_kill: X,+ git_status: GitBranch,+ git_diff: GitCompare,+ git_log: GitBranch,+ git_commit: GitCommitHorizontal,+ git_push: GitBranch,+ gh_pr_create: GitPullRequest,+ pr_resume: GitPullRequest,+ project_init: FolderOpen,+ run_tests: FlaskConical,system_info: Cpu,process_list: Cpu,screenshot: Monitor,image_generate: Image,video_generate: Film,run_workflow: GitBranch,+ delegate_task: Users,+ get_current_time: Clock,}const STATUS_ICONS = {@@ -127,7 +147,12 @@ const STATUS_ICONS = {cached: Database,}-export function ToolCallBlock({ toolCall, onApprove, onReject }: Props) {+// memo (audit D2): the Codex/Agent transcript re-renders on every streamed+// frame, and each un-memoised block re-rendered with it. Block updates+// replace the toolCall object, so reference equality is the right check.+export const ToolCallBlock = memo(ToolCallBlockImpl)++function ToolCallBlockImpl({ toolCall, onApprove, onReject }: Props) {// Default: collapsed (closed)const [open, setOpen] = useState(toolCall.status === 'pending_approval')@@ -331,9 +356,17 @@ export function ToolCallBlock({ toolCall, onApprove, onReject }: Props) {{JSON.stringify(toolCall.args, null, 2)}</pre>+ {/* Diff for the write tools (audit D5): a change view where a+ change happened, not raw result text. */}+ {toolCall.diff && (+ <div className="max-h-[300px] overflow-auto scrollbar-thin">+ <DiffView diff={toolCall.diff} />+ </div>+ )}+{/* Result (raw text). The inline media preview now rendersalways-visible above the collapsible (konata 2026-06-07). */}- {toolCall.result && (+ {toolCall.result && !toolCall.diff && (<pre className="text-[0.55rem] leading-relaxed text-gray-600 dark:text-gray-400 bg-gray-50 dark:bg-white/[0.02] rounded px-2 py-1 overflow-auto scrollbar-thin max-h-[300px]">{toolCall.result}</pre>diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.tsindex 6c9fc2cf..cda0765b 100644--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@ -775,9 +775,30 @@ export function useCodex() {// I am the Coding Agent…" line never lands in the chat. The// post-stream echoDetected branch then drops the buffer entirely and// forces a silent retry.+ //+ // Coalesced per animation frame (audit D1) — Chat and Agent already+ // did this; Codex wrote the store on every token, which re-rendered+ // the whole transcript per token on long answers. settleLivePaint()+ // cancels the queued frame the moment the stream call returns, so a+ // stale frame can never fire AFTER a final direct write and repaint+ // old content over it.+ let livePaintPending: string | null = null+ let livePaintFrame = false+ const settleLivePaint = () => {+ livePaintPending = null+ }const liveContent = (c: string) => {if (echoRetriesRemaining > 0 && isSystemPromptEcho(c)) return- useChatStore.getState().updateMessageContent(convId!, assistantMsg.id, fullContent ? fullContent + '\n\n' + c : c)+ livePaintPending = fullContent ? fullContent + '\n\n' + c : c+ if (livePaintFrame) return+ livePaintFrame = true+ requestAnimationFrame(() => {+ livePaintFrame = false+ if (livePaintPending !== null) {+ useChatStore.getState().updateMessageContent(convId!, assistantMsg.id, livePaintPending)+ livePaintPending = null+ }+ })}if (strategy === 'native') {@@ -907,6 +928,7 @@ export function useCodex() {throw thinkErr}}+ settleLivePaint()toolCalls = turn.toolCallsturnContent = turn.content || ''// Real consumed-context usage for THIS coding turn (system + tools +@@ -1002,6 +1024,7 @@ export function useCodex() {throw thinkErr}}+ settleLivePaint()toolCalls = turn.toolCallsturnContent = turn.content || ''if (turn.promptEvalCount || turn.evalCount) {@@ -1052,7 +1075,10 @@ export function useCodex() {},)shown += display.flush()- if (shown) liveContent(shown)+ // Final paint DIRECT + settle the coalesced frame, so a queued+ // stale frame can never fire after the writes below (audit D1).+ settleLivePaint()+ if (shown) useChatStore.getState().updateMessageContent(convId!, assistantMsg.id, fullContent ? fullContent + '\n\n' + shown : shown)const raw = hermesTurn.contentif (hasToolCallTags(raw)) {toolCalls = parseHermesToolCalls(raw).map(tc => ({@@ -1570,43 +1596,21 @@ export function useCodex() {if (!result) continueapplyResultToToolCall(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: resultStr, timestamp: Date.now(),- })- } else if (entry.ac.toolName === 'file_write') {- // Attach a unified diff to EVERY file_change event (not only in- // stage mode). Pre-read above captured the on-disk version; a- // missing file yields an all-add hunk. Empty diff → omit.+ // Unified diff for the write tools — computed BEFORE the block+ // update so the ToolCallBlock itself can render it (audit D5; the+ // diff used to live only on the Codex event log, so the Agent view+ // showed raw text where a change view belonged).+ let acDiff: string | undefined+ if (entry.ac.toolName === 'file_write') {+ // Pre-read above captured the on-disk version; a missing file+ // yields an all-add hunk. Empty diff → omit.const oldText = oldContents.get(entry.ac.id) ?? ''const newText =typeof entry.injectedArgs.content === 'string'? entry.injectedArgs.content: ''- const diff = computeUnifiedDiff(- entry.injectedArgs.path,- oldText,- newText,- )- codexStore.addEvent(convId, {- id: uuid(), type: 'file_change', content: resultStr,- filePath: entry.injectedArgs.path,- diff: diff || undefined,- timestamp: Date.now(),- })+ acDiff = computeUnifiedDiff(entry.injectedArgs.path, oldText, newText) || undefined} else if (entry.ac.toolName === 'file_edit') {// Surgical edit — the tool only received old_string/new_string, so// reconstruct the new content from the pre-read + the unique@@ -1618,13 +1622,34 @@ export function useCodex() {typeof entry.injectedArgs.old_string === 'string' ? entry.injectedArgs.old_string : '',typeof entry.injectedArgs.new_string === 'string' ? entry.injectedArgs.new_string : '',)- const diff = applied.ok- ? computeUnifiedDiff(entry.injectedArgs.path, oldText, applied.content ?? '')+ acDiff = applied.ok+ ? computeUnifiedDiff(entry.injectedArgs.path, oldText, applied.content ?? '') || undefined: undefined+ }+ if (acDiff) entry.ac.diff = acDiff++ 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: resultStr, timestamp: Date.now(),+ })+ } else if (entry.ac.toolName === 'file_write' || entry.ac.toolName === 'file_edit') {codexStore.addEvent(convId, {id: uuid(), type: 'file_change', content: resultStr,filePath: entry.injectedArgs.path,- diff: diff || undefined,+ diff: acDiff,timestamp: Date.now(),})} else if (isError) {@@ -1789,27 +1814,37 @@ export function useCodex() {// the chat store. On the next turn, the history builder includes// them in the API payload so the model sees what it did before.// Hidden messages are filtered out by MessageBubble rendering.- const toolHistory = messages.slice(messagesStartLen)+ //+ // Capped + batched (audit E2). Uncapped, a 200-iteration run persisted+ // hundreds of hidden messages of up to 60k chars each — tens of MB in+ // one conversation, reserialised on every later persist. And the old+ // one-set()-per-message insert loop was the visible hang at run end.+ // The most recent chain is what the next turn actually needs; older+ // steps are summarised by the visible transcript anyway.+ const toolHistoryAll = messages.slice(messagesStartLen)+ const HIDDEN_HISTORY_MAX = 60+ let toolHistory = toolHistoryAll.slice(-HIDDEN_HISTORY_MAX)+ // Never start the kept slice on an orphan tool result — strict+ // providers 422 a result whose call fell outside the window.+ while (toolHistory.length > 0 && toolHistory[0].role === 'tool') toolHistory = toolHistory.slice(1)if (toolHistory.length > 0 && convId) {const store = useChatStore.getState()// Find the assistant message we just filled so we can insert BEFORE itconst convNow = store.conversations.find(c => c.id === convId)const assistantIdx = convNow?.messages.findIndex(m => m.id === assistantMsg.id) ?? -1if (assistantIdx > 0) {- for (const tm of toolHistory) {- store.insertMessageBefore(convId, assistantMsg.id, {- id: uuid(),- role: tm.role as 'assistant' | 'tool',- content: tm.content || '',- timestamp: Date.now(),- hidden: true,- tool_calls: tm.tool_calls as any,- // Persist the tool-result linkage so the next turn's history- // builder can replay it — without this, follow-up turns 422 on- // lu-cloud (see types/chat.ts Message.tool_call_id, Bug 4).- tool_call_id: tm.tool_call_id,- })- }+ store.insertMessagesBefore(convId, assistantMsg.id, toolHistory.map((tm) => ({+ id: uuid(),+ role: tm.role as 'assistant' | 'tool',+ content: tm.content || '',+ timestamp: Date.now(),+ hidden: true,+ tool_calls: tm.tool_calls as any,+ // Persist the tool-result linkage so the next turn's history+ // builder can replay it — without this, follow-up turns 422 on+ // lu-cloud (see types/chat.ts Message.tool_call_id, Bug 4).+ tool_call_id: tm.tool_call_id,+ })))}}diff --git a/src/lib/context-compaction.ts b/src/lib/context-compaction.tsindex 8eccd4de..ce2ceb25 100644--- a/src/lib/context-compaction.ts+++ b/src/lib/context-compaction.ts@@ -78,6 +78,10 @@ export async function getModelMaxTokens(modelName: string): Promise<number> {const KEEP_RECENT = 4 // Always keep at least the last N messages untouched+/** How much of the pinned first user message survives compaction. Enough for+ * any real instruction; a pasted 200 KB file does not ride along forever. */+const PINNED_TASK_MAX_CHARS = 8000+/*** True for a message that is a tool RESULT — either the native `tool` role or* a Hermes `<tool_response>` carried on a user message. Used to trim a leading@@ -140,14 +144,33 @@ export function compactMessages(: m,)+ // Pin the TASK (audit C5). The oldest message is the user's actual+ // instruction, and the suffix window is precisely the mechanism that drops+ // it first — after which a 30-minute run works on whatever the recent tool+ // results imply instead of what was asked. Keep the first user message+ // (capped) out of the drop zone, alongside the system prompt.+ const firstUserIdx = capped.findIndex((m) => m.role === 'user')+ const pinnedTask =+ firstUserIdx >= 0 && typeof capped[firstUserIdx].content === 'string'+ ? {+ ...capped[firstUserIdx],+ content:+ capped[firstUserIdx].content.length > PINNED_TASK_MAX_CHARS+ ? truncateToolResult(capped[firstUserIdx].content, PINNED_TASK_MAX_CHARS)+ : capped[firstUserIdx].content,+ }+ : null+ const pinnedTokens = pinnedTask ? estimateMessageTokens([pinnedTask]) : 0+// Accumulate a recent suffix that fits, newest-first. Keep at least// KEEP_RECENT messages even when that exceeds budget (recent context is the// most valuable), otherwise stop as soon as the next message would overflow.+ const suffixBudget = Math.max(0, budget - pinnedTokens)const kept: OllamaChatMessage[] = []let used = 0for (let i = capped.length - 1; i >= 0; i--) {const t = estimateMessageTokens([capped[i]])- if (used + t > budget && kept.length >= KEEP_RECENT) break+ if (used + t > suffixBudget && kept.length >= KEEP_RECENT) breakkept.unshift(capped[i])used += t}@@ -158,9 +181,16 @@ export function compactMessages(kept.shift()}- const droppedCount = capped.length - kept.length+ // The pin is only needed when the first user message did NOT survive into+ // the suffix on its own.+ const pinNeeded = pinnedTask !== null && !kept.includes(capped[firstUserIdx])++ const droppedCount = capped.length - kept.length - (pinNeeded ? 1 : 0)const compacted: OllamaChatMessage[] = []if (systemMsg) compacted.push(systemMsg)+ if (pinNeeded && pinnedTask) {+ compacted.push(pinnedTask)+ }if (droppedCount > 0) {// Wording matters here: the old notice ("Re-read any file you still need// with file_read.") actively FED a re-read loop — every iteration the@@ -168,7 +198,7 @@ export function compactMessages(// recovery path but make it single-shot and anti-repeat.compacted.push({role: 'system',- content: `[${droppedCount} earlier message${droppedCount === 1 ? '' : 's'} were trimmed to fit the context window. Results you already saw still hold. If a detail is genuinely missing, re-read that specific file once; never repeat a call that already ran.]`,+ content: `[${droppedCount} earlier message${droppedCount === 1 ? '' : 's'} were trimmed to fit the context window. The original task above still stands. Results you already saw still hold. If a detail is genuinely missing, re-read that specific file once; never repeat a call that already ran.]`,})}compacted.push(...kept)diff --git a/src/stores/chatStore.ts b/src/stores/chatStore.tsindex 938428bf..262f2179 100644--- a/src/stores/chatStore.ts+++ b/src/stores/chatStore.ts@@ -43,6 +43,7 @@ interface ChatState {setConversationPersonaEnabled: (id: string, enabled: boolean) => voidaddMessage: (conversationId: string, message: Message) => voidinsertMessageBefore: (conversationId: string, beforeId: string, message: Message) => void+ insertMessagesBefore: (conversationId: string, beforeId: string, messages: Message[]) => voidupdateMessageContent: (conversationId: string, messageId: string, content: string) => voidupdateMessageThinking: (conversationId: string, messageId: string, thinking: string) => voidupdateMessageUsage: (conversationId: string, messageId: string, usage: { promptTokens: number; completionTokens: number; totalTokens: number; estimated?: boolean }) => void@@ -204,6 +205,23 @@ export const useChatStore = create<ChatState>()(}),})),+ // Batch variant (audit E2): the Codex run-end used to insert its whole+ // tool history in a loop, one set() per message — several hundred store+ // updates back to back, each cloning the conversation array while the+ // coalesced persist serialised behind it. That was the visible hang at+ // the end of a long run. One set(), one clone, one persist.+ insertMessagesBefore: (conversationId, beforeId, messages) =>+ set((state) => ({+ conversations: state.conversations.map((c) => {+ if (c.id !== conversationId) return c+ const idx = c.messages.findIndex((m) => m.id === beforeId)+ const msgs = [...c.messages]+ if (idx < 0) msgs.push(...messages)+ else msgs.splice(idx, 0, ...messages)+ return { ...c, messages: msgs, updatedAt: Date.now() }+ }),+ })),+updateMessageContent: (conversationId, messageId, content) =>set((state) => ({conversations: state.conversations.map((c) =>diff --git a/src/types/agent-mode.ts b/src/types/agent-mode.tsindex 32ef82d5..d197376c 100644--- a/src/types/agent-mode.ts+++ b/src/types/agent-mode.ts@@ -88,6 +88,9 @@ export interface AgentToolCall {parentToolCallId?: string/** True when args passed JSON-schema validation (Phase 4). */schemaValidated?: boolean+ /** Unified diff for file_write/file_edit, rendered by ToolCallBlock+ * (audit D5) instead of raw result text. */+ diff?: string/** Group key for serial execution within a parallel batch (Phase 5).* Writes to the same file path or the singleton "shell" share a key. */sideEffectKey?: string