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.

v2.5.0 polish: uselu coding-agent view parity + image-gen WS-resilience fix

purple0467b1a648db
diff --git a/src/api/agents/__tests__/sub-agent.test.ts b/src/api/agents/__tests__/sub-agent.test.ts
index a3eb8e37..4f76c3e8 100644
--- a/src/api/agents/__tests__/sub-agent.test.ts
+++ b/src/api/agents/__tests__/sub-agent.test.ts
@@ -1,7 +1,7 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import {
DELEGATE_TASK_TOOL_DEF,
- SUB_AGENT_MAX_DEPTH,
+ SUB_AGENT_MAX_PARALLEL,
SUB_AGENT_BUDGET,
buildDelegateExecutor,
_getDepth,
@@ -16,8 +16,9 @@ describe('sub-agent — tool definition', () => {
expect(DELEGATE_TASK_TOOL_DEF.inputSchema.required).toContain('goal')
})
- it('description contains the nesting warning', () => {
- expect(DELEGATE_TASK_TOOL_DEF.description).toMatch(/nesting depth is 2/i)
+ it('description contains the recursion + parallel hints', () => {
+ expect(DELEGATE_TASK_TOOL_DEF.description).toMatch(/recursion is filtered/i)
+ expect(DELEGATE_TASK_TOOL_DEF.description).toMatch(/PARALLELIZE/i)
})
})
@@ -72,42 +73,76 @@ describe('sub-agent — buildDelegateExecutor', () => {
expect(_getDepth()).toBe(0)
})
- it('refuses once MAX_DEPTH is reached', async () => {
- _setDepth(SUB_AGENT_MAX_DEPTH)
+ it('refuses once MAX_PARALLEL in-flight is reached', async () => {
+ _setDepth(SUB_AGENT_MAX_PARALLEL)
const runner = vi.fn(async () => 'should not run')
const exec = buildDelegateExecutor(runner)
const out = await exec({ goal: 'x' })
- expect(out).toMatch(/Maximum sub-agent nesting depth/)
+ expect(out).toMatch(/Maximum sub-agent concurrency/)
expect(runner).not.toHaveBeenCalled()
// And the tracker is not nudged by a refused call.
- expect(_getDepth()).toBe(SUB_AGENT_MAX_DEPTH)
+ expect(_getDepth()).toBe(SUB_AGENT_MAX_PARALLEL)
})
- it('allows a call at depth = MAX_DEPTH - 1 (recursive boundary)', async () => {
- _setDepth(SUB_AGENT_MAX_DEPTH - 1)
+ it('allows a call at MAX_PARALLEL - 1 (boundary)', async () => {
+ _setDepth(SUB_AGENT_MAX_PARALLEL - 1)
const runner = vi.fn(async () => 'ok')
const exec = buildDelegateExecutor(runner)
const out = await exec({ goal: 'x' })
expect(out).toBe('ok')
- expect(_getDepth()).toBe(SUB_AGENT_MAX_DEPTH - 1)
+ expect(_getDepth()).toBe(SUB_AGENT_MAX_PARALLEL - 1)
})
- it('serialises concurrent calls via shared depth counter (approximate)', async () => {
- // Two simultaneous executors, each with its own goal. Both increment
- // _depth on the way in; neither should see > 2 depth even when
- // interleaved, because _depth is incremented synchronously before
- // the async runner awaits.
+ // ── Parallel siblings (Bonus, 2026-05) ─────────────────────────
+
+ it('runs three parallel siblings concurrently — no false refusals', async () => {
let observedMax = 0
- const runner = async () => {
+ const starts: number[] = []
+ const runner = async (goal: string) => {
+ starts.push(Date.now())
observedMax = Math.max(observedMax, _getDepth())
- await new Promise((r) => setTimeout(r, 5))
- return 'done'
+ await new Promise((r) => setTimeout(r, 10))
+ return `done:${goal}`
}
const exec = buildDelegateExecutor(runner)
- await Promise.all([exec({ goal: 'a' }), exec({ goal: 'b' })])
- // Two concurrent calls both pass the guard at depth 0 and 1, so the
- // observed max is SUB_AGENT_MAX_DEPTH. A THIRD concurrent call would
- // be refused before the runner fires.
- expect(observedMax).toBeLessThanOrEqual(SUB_AGENT_MAX_DEPTH)
+ const out = await Promise.all([
+ exec({ goal: 'a' }),
+ exec({ goal: 'b' }),
+ exec({ goal: 'c' }),
+ ])
+ expect(out).toEqual(['done:a', 'done:b', 'done:c'])
+ // All three should be in flight at the same time → observedMax = 3.
+ expect(observedMax).toBe(3)
+ // And every refusal would have been "should not run" — none returned.
+ expect(out.every((s) => !s.startsWith('Error'))).toBe(true)
+ })
+
+ it('a 5th parallel sibling is refused (cap is 4)', async () => {
+ _setDepth(0)
+ const runner = vi.fn(async () => {
+ await new Promise((r) => setTimeout(r, 20))
+ return 'ok'
+ })
+ const exec = buildDelegateExecutor(runner)
+ const five = [
+ exec({ goal: 'a' }),
+ exec({ goal: 'b' }),
+ exec({ goal: 'c' }),
+ exec({ goal: 'd' }),
+ exec({ goal: 'e' }),
+ ]
+ const settled = await Promise.all(five)
+ const refused = settled.filter((s) => /Maximum sub-agent concurrency/.test(s))
+ expect(refused).toHaveLength(1)
+ expect(runner).toHaveBeenCalledTimes(4)
+ })
+
+ it('after a refusal, the next call succeeds once a slot frees', async () => {
+ _setDepth(SUB_AGENT_MAX_PARALLEL)
+ const runner = vi.fn(async () => 'ok')
+ const exec = buildDelegateExecutor(runner)
+ expect(await exec({ goal: 'x' })).toMatch(/Maximum sub-agent concurrency/)
+ _setDepth(0)
+ expect(await exec({ goal: 'x' })).toBe('ok')
})
})
diff --git a/src/api/agents/sub-agent.ts b/src/api/agents/sub-agent.ts
index 0549dec0..9550188c 100644
--- a/src/api/agents/sub-agent.ts
+++ b/src/api/agents/sub-agent.ts
@@ -21,9 +21,22 @@ import { explainError as explainToolError } from './error-hints'
// pulls DELEGATE_TASK_TOOL_DEF + buildDelegateExecutor from this file at
// module init.
-/** Max sub-agent nesting depth. Incremented on every delegate_task call. */
+/**
+ * Max sub-agent nesting depth. Kept for symmetry with the original Phase
+ * 13 design; the tool-registry filter (sub-agent never sees
+ * `delegate_task`) already enforces non-recursion, so this is a soft
+ * safety net rather than the primary guard.
+ */
export const SUB_AGENT_MAX_DEPTH = 2
+/**
+ * Max sub-agents in flight at the same time (Bonus, 2026-05). Parallel
+ * siblings let the model fan out research tasks — e.g. "for each of these
+ * 4 files, summarize the public surface" — without the historic serial
+ * pressure from the depth counter doubling as a concurrency gate.
+ */
+export const SUB_AGENT_MAX_PARALLEL = 4
+
/** Tight caps so a sub-agent cannot runaway inside the parent's budget. */
export const SUB_AGENT_BUDGET = { maxToolCalls: 10, maxIterations: 5 } as const
@@ -33,7 +46,9 @@ export const DELEGATE_TASK_TOOL_DEF: MCPToolDefinition = {
'Spawn a focused sub-agent to work on a sub-goal autonomously. '
+ 'USE for self-contained research or analysis tasks that would pollute the main conversation with tool-call chatter. '
+ 'The sub-agent has its own tight budget (max 10 tool calls, 5 ReAct iterations) and returns a concise final answer. '
- + 'DO NOT call from inside another delegate_task — max nesting depth is 2. '
+ + 'PARALLELIZE: emit multiple delegate_task tool calls in the SAME assistant turn '
+ + 'to fan out (e.g. one sub-agent per file) — up to 4 run concurrently. '
+ + 'DO NOT call from inside another delegate_task — recursion is filtered by the harness. '
+ 'NOT a replacement for a regular tool call when one direct tool would do.',
inputSchema: {
type: 'object',
@@ -54,19 +69,24 @@ export const DELEGATE_TASK_TOOL_DEF: MCPToolDefinition = {
}
/**
- * Depth tracker — module-scoped so nested sub-agents across async
- * boundaries stay bounded. Reset only by successful return or thrown
+ * In-flight counter — module-scoped so parallel siblings + nested
+ * children share one bound. Reset only by successful return or thrown
* error; see the try/finally in the executor.
+ *
+ * Pre-Bonus this was named `_depth` and doubled as a concurrency gate,
+ * which made three parallel siblings impossible. Now strictly counts
+ * concurrent sub-agents; the description forbids recursion and the
+ * registry filter enforces it.
*/
-let _depth = 0
+let _inFlight = 0
/** Exposed for tests. */
export function _getDepth(): number {
- return _depth
+ return _inFlight
}
/** Exposed for tests. */
export function _setDepth(n: number): void {
- _depth = n
+ _inFlight = n
}
export type SubAgentRunner = (
@@ -139,7 +159,7 @@ export async function defaultSubAgentRunner(
const td = registry.getToolByName(name)
return td ? { name: td.name, inputSchema: td.inputSchema } : undefined
},
- execute: (name, args) => registry.execute(name, args),
+ execute: ((name: string, args: Record<string, any>) => registry.execute(name, args)) as any,
explainError: (toolName, err) => explainToolError(toolName, err),
})
@@ -165,21 +185,21 @@ export function buildDelegateExecutor(
runner: SubAgentRunner = defaultSubAgentRunner
): (args: Record<string, any>) => Promise<string> {
return async (args: Record<string, any>) => {
- if (_depth >= SUB_AGENT_MAX_DEPTH) {
- return 'Error: Maximum sub-agent nesting depth (2) reached. Continue the task yourself.'
+ if (_inFlight >= SUB_AGENT_MAX_PARALLEL) {
+ return `Error: Maximum sub-agent concurrency (${SUB_AGENT_MAX_PARALLEL}) reached. Wait for a running sub-agent to finish, or continue the task yourself.`
}
const goal = typeof args.goal === 'string' ? args.goal.trim() : ''
if (!goal) return 'Error: delegate_task requires a "goal" argument.'
const context = typeof args.context === 'string' ? args.context.trim() : ''
- _depth++
+ _inFlight++
try {
const budget = new AgentBudget({ ...SUB_AGENT_BUDGET })
return await runner(goal, context, { budget })
} catch (err) {
return `Error: ${err instanceof Error ? err.message : String(err)}`
} finally {
- _depth--
+ _inFlight--
}
}
}
diff --git a/src/api/comfyui-ws.ts b/src/api/comfyui-ws.ts
index 1ccdc50b..0fa3f4c2 100644
--- a/src/api/comfyui-ws.ts
+++ b/src/api/comfyui-ws.ts
@@ -102,7 +102,19 @@ class ComfyWSClient {
clearTimeout(timer)
this._connected = false
this.connectPromise = null
- // onclose will fire after onerror
+ // CRITICAL: reject so callers don't hang. A WS error fires onerror
+ // and we clear the connect timeout above — if we don't reject here,
+ // the connect() promise NEVER settles and `await comfyWS.connect()`
+ // hangs forever. That's exactly what happened when ComfyUI was
+ // started without `--enable-cors-header` (e.g. a user-run / external
+ // ComfyUI, or the dev auto-starter): ComfyUI's origin-only CSRF
+ // middleware rejects the WebView's cross-origin upgrade, the WS
+ // errors, and image/video generation got stuck on "Submitting to
+ // ComfyUI…" with no progress and no result. Rejecting lets useCreate
+ // fall back to /history polling so the result still appears (it only
+ // loses the live progress bar). onclose still fires after this and
+ // schedules a reconnect; reject on a settled promise is a no-op.
+ reject(new Error('WebSocket connection error'))
}
} catch {
clearTimeout(timer)
diff --git a/src/api/providers/ollama-provider.ts b/src/api/providers/ollama-provider.ts
index b6e03091..1bcbe798 100644
--- a/src/api/providers/ollama-provider.ts
+++ b/src/api/providers/ollama-provider.ts
@@ -132,10 +132,7 @@ export class OllamaProvider implements ProviderClient {
}
if (!res.ok) {
- throw new ProviderError(
- await this.extractError(res, 'Chat failed', model),
- 'ollama', 'network', res.status,
- )
+ throw await this.buildError(res, 'Chat failed', model)
}
for await (const chunk of parseNDJSONStream<OllamaChatChunk>(res)) {
@@ -212,10 +209,7 @@ export class OllamaProvider implements ProviderClient {
}
if (!res.ok) {
- throw new ProviderError(
- await this.extractError(res, 'Tool calling failed', model),
- 'ollama', 'network', res.status,
- )
+ throw await this.buildError(res, 'Tool calling failed', model)
}
const data = await res.json()
@@ -311,18 +305,43 @@ export class OllamaProvider implements ProviderClient {
// ── Helpers ────────────────────────────────────────────────
- private async extractError(res: Response, fallback: string, model?: string): Promise<string> {
+ /**
+ * Classify a non-ok Ollama response and wrap it in `ProviderError`. The
+ * resulting error carries:
+ * - `code` — one of `ollama_missing_blob`, `ollama_stale_manifest`,
+ * or generic `network` so UI catch sites can branch (and feed the
+ * model-health store via lib/sync-ollama-health.ts) without
+ * re-parsing the message.
+ * - `model` — threaded through from chatStream/chatWithTools so the
+ * UI can name the affected model in a one-click "ollama pull <model>"
+ * repair flow. Missing-blob errors only carry the on-disk blob hash,
+ * not the model name, so we pass `model` into parseOllamaError as the
+ * fallback (Bug C) — that populates `parsed.model`, which
+ * chatStyleMessage then uses for the user-facing wording.
+ *
+ * Pure function: no store side-effects, no UI imports. The caller
+ * (useChat via syncOllamaHealthFromError) translates the error code into
+ * a store update.
+ *
+ * Shares the detection logic with loadModel / unloadModel via
+ * ollama-errors. The regex there matches chat, completion, AND generate
+ * (the Lichtschalter path uses /api/generate with an empty prompt for
+ * preload — same error class).
+ */
+ private async buildError(res: Response, fallback: string, model?: string): Promise<ProviderError> {
+ const status = res.status
try {
- // Share the detection logic with loadModel / unloadModel via ollama-errors.
- // The regex there matches chat, completion, AND generate (the Lichtschalter
- // path uses /api/generate with an empty prompt for preload — same error class).
- // Bug C: thread the request's `model` arg through so missing-blob errors,
- // which only carry the on-disk blob hash, can name the model in the UI.
const { parseOllamaError, chatStyleMessage } = await import('../../lib/ollama-errors')
const parsed = await parseOllamaError(res, fallback, model)
- return chatStyleMessage(parsed)
+ const message = chatStyleMessage(parsed)
+ let code = 'network'
+ if (parsed.kind === 'missing-blob') code = 'ollama_missing_blob'
+ else if (parsed.kind === 'stale-manifest') code = 'ollama_stale_manifest'
+ // Prefer the parsed model name (e.g. from a stale-manifest string that
+ // carries it) and fall back to the request's model arg.
+ return new ProviderError(message, 'ollama', code, status, parsed.model || model)
} catch {
- return fallback
+ return new ProviderError(fallback, 'ollama', 'network', status, model)
}
}
}
diff --git a/src/api/providers/types.ts b/src/api/providers/types.ts
index e1d0ea12..4aab4bc3 100644
--- a/src/api/providers/types.ts
+++ b/src/api/providers/types.ts
@@ -172,13 +172,32 @@ export interface ProviderClient {
// ── Provider Error ────────────────────────────────────────────
export class ProviderError extends Error {
+ // Explicit fields (not constructor parameter-properties): the build runs
+ // under `erasableSyntaxOnly`, which forbids TS parameter-properties.
+ readonly provider: ProviderId
+ /** 'auth' | 'rate_limit' | 'not_found' | 'network' | 'ollama_missing_blob' | 'ollama_stale_manifest' */
+ readonly code?: string
+ readonly status?: number
+ /**
+ * Provider-specific extra context. Used by UI catch sites to update the
+ * model-health store (Ollama missing-blob / stale-manifest) without importing
+ * zustand from inside the provider — keeps the API layer decoupled from app
+ * state. See lib/sync-ollama-health.ts.
+ */
+ readonly model?: string
+
constructor(
message: string,
- public readonly provider: ProviderId,
- public readonly code?: string, // 'auth', 'rate_limit', 'not_found', 'network'
- public readonly status?: number,
+ provider: ProviderId,
+ code?: string,
+ status?: number,
+ model?: string,
) {
super(message)
this.name = 'ProviderError'
+ this.provider = provider
+ this.code = code
+ this.status = status
+ this.model = model
}
}
diff --git a/src/components/chat/CodexEventBlock.tsx b/src/components/chat/CodexEventBlock.tsx
index b8dc44ca..16dce5a4 100644
--- a/src/components/chat/CodexEventBlock.tsx
+++ b/src/components/chat/CodexEventBlock.tsx
@@ -1,6 +1,7 @@
import { Terminal, FileEdit, Brain, AlertCircle, CheckCircle, ChevronDown } from 'lucide-react'
import { useState } from 'react'
import type { CodexEvent } from '../../types/codex'
+import { DiffView } from './DiffView'
interface Props {
event: CodexEvent
@@ -35,6 +36,7 @@ export function CodexEventBlock({ event }: Props) {
const Icon = icons[event.type as keyof typeof icons] || CheckCircle
const color = colors[event.type as keyof typeof colors] || 'text-gray-400'
const label = labels[event.type as keyof typeof labels] || event.type
+ const hasDiff = event.type === 'file_change' && Boolean(event.diff)
return (
<div className="mb-0.5">
@@ -49,17 +51,21 @@ export function CodexEventBlock({ event }: Props) {
{open && (
<div className="pl-4 pb-1">
- <pre className={`text-[0.58rem] leading-relaxed rounded px-2 py-1 overflow-auto scrollbar-thin max-h-[250px] ${
- event.type === 'terminal_output'
- ? 'bg-black/20 text-green-300/70'
- : event.type === 'error'
- ? 'bg-red-500/5 text-red-400/80'
- : event.type === 'reasoning'
- ? 'text-blue-200/40 italic'
- : 'bg-white/[0.02] text-gray-400'
- }`}>
- {event.content}
- </pre>
+ {hasDiff ? (
+ <DiffView diff={event.diff!} />
+ ) : (
+ <pre className={`text-[0.58rem] leading-relaxed rounded px-2 py-1 overflow-auto scrollbar-thin max-h-[250px] ${
+ event.type === 'terminal_output'
+ ? 'bg-black/20 text-green-300/70'
+ : event.type === 'error'
+ ? 'bg-red-500/5 text-red-400/80'
+ : event.type === 'reasoning'
+ ? 'text-blue-200/40 italic'
+ : 'bg-white/[0.02] text-gray-400'
+ }`}>
+ {event.content}
+ </pre>
+ )}
</div>
)}
</div>
diff --git a/src/components/chat/CodexView.tsx b/src/components/chat/CodexView.tsx
index 342a8c7a..f86e5a41 100644
--- a/src/components/chat/CodexView.tsx
+++ b/src/components/chat/CodexView.tsx
@@ -133,21 +133,71 @@ export function CodexView() {
))}
</div>
)}
- {/* Tool call blocks */}
- {msg.role === 'assistant' && msg.agentBlocks && msg.agentBlocks.length > 0 && (
- <div className="space-y-0">
- {msg.agentBlocks
- .filter(b => b.phase === 'tool_call' && b.toolCall)
- .map(block => (
- <ToolCallBlock key={block.id} toolCall={block.toolCall!} />
- ))}
- </div>
- )}
+ {/* Interleaved blocks (Codex 2026-05) — when the
+ assistant turn produced per-iteration 'answer'
+ blocks, render tool_call + answer blocks in
+ chronological order so commentary sits BETWEEN tool
+ calls instead of all text bunching at the bottom.
+ Falls back to the legacy split (tool-calls only,
+ full text below) for older chats that have only
+ tool_call blocks. */}
+ {msg.role === 'assistant' && msg.agentBlocks && msg.agentBlocks.length > 0
+ ? (() => {
+ const hasAnswerBlock = msg.agentBlocks!.some(
+ (b) => b.phase === 'answer' && b.content.trim(),
+ )
+ if (hasAnswerBlock) {
+ return (
+ <div className="space-y-1">
+ {[...msg.agentBlocks!]
+ .filter(
+ (b) =>
+ (b.phase === 'tool_call' && b.toolCall) ||
+ (b.phase === 'answer' && b.content.trim()),
+ )
+ .sort((a, b) => a.timestamp - b.timestamp)
+ .map((block) => {
+ if (block.phase === 'tool_call' && block.toolCall) {
+ return (
+ <ToolCallBlock key={block.id} toolCall={block.toolCall} />
+ )
+ }
+ if (block.phase === 'answer' && block.content.trim()) {
+ return (
+ <div key={block.id} className="px-1 py-0.5">
+ <div className="text-[0.75rem] leading-relaxed">
+ <MarkdownRenderer
+ content={stripChannelTags(block.content)}
+ />
+ </div>
+ </div>
+ )
+ }
+ return null
+ })}
+ </div>
+ )
+ }
+ return (
+ <div className="space-y-0">
+ {msg.agentBlocks!
+ .filter((b) => b.phase === 'tool_call' && b.toolCall)
+ .map((block) => (
+ <ToolCallBlock key={block.id} toolCall={block.toolCall!} />
+ ))}
+ </div>
+ )
+ })()
+ : null}
- {/* Text content — assistant drops the bubble entirely
- to match the regular Chat view (per user feedback).
- User keeps theirs as the right-aligned anchor. */}
- {cleanContent && (
+ {/* Text content — user bubble always; assistant only
+ when there are no per-iteration answer blocks (the
+ interleave path above already rendered them inline).
+ Assistant drops the bubble entirely to match the
+ regular Chat view; user keeps theirs as the
+ right-aligned anchor. */}
+ {cleanContent && (msg.role === 'user' ||
+ !(msg.agentBlocks && msg.agentBlocks.some((b) => b.phase === 'answer' && b.content.trim()))) && (
<div className={
msg.role === 'user'
? 'rounded-lg px-2.5 py-1.5 bg-gray-100 dark:bg-white/[0.06] border border-gray-200 dark:border-white/[0.08]'
diff --git a/src/components/chat/FileTree.tsx b/src/components/chat/FileTree.tsx
index b03b2000..dbf4c760 100644
--- a/src/components/chat/FileTree.tsx
+++ b/src/components/chat/FileTree.tsx
@@ -12,10 +12,12 @@ export function FileTree() {
const setFileTree = useCodexStore((s) => s.setFileTree)
const setWorkingDirectory = useCodexStore((s) => s.setWorkingDirectory)
const [loading, setLoading] = useState(false)
+ const [error, setError] = useState<string | null>(null)
const loadDirectory = async (dir: string) => {
if (!dir.trim()) return
setLoading(true)
+ setError(null)
try {
const result = await toolRegistry.execute('file_list', { path: dir })
const lines = result.split('\n').filter(Boolean)
@@ -30,8 +32,9 @@ export function FileTree() {
setFileTree(nodes)
setWorkingDirectory(dir)
- } catch {
+ } catch (e) {
setFileTree([])
+ setError(e instanceof Error ? e.message : 'Failed to read directory')
} finally {
setLoading(false)
}
@@ -111,6 +114,8 @@ export function FileTree() {
<div className="flex-1 overflow-y-auto scrollbar-thin p-1">
{loading ? (
<p className="text-[0.5rem] text-gray-400 dark:text-gray-600 px-1 py-2">Loading...</p>
+ ) : error ? (
+ <p className="text-[0.5rem] text-red-500/80 px-1 py-2">{error}</p>
) : fileTree.length === 0 ? (
<p className="text-[0.5rem] text-gray-400 dark:text-gray-600 px-1 py-2">
{workingDirectory ? 'Empty directory' : 'Click above to set a folder'}
diff --git a/src/components/chat/MessageBubble.tsx b/src/components/chat/MessageBubble.tsx
index 52129dd6..1d687d17 100644
--- a/src/components/chat/MessageBubble.tsx
+++ b/src/components/chat/MessageBubble.tsx
@@ -116,15 +116,21 @@ export function MessageBubble({ message, onRegenerate, onEdit, pendingApprovalId
<ThinkingBlock thinking={message.thinking} />
)}
- {/* Agent Mode: render tool_call + reflection blocks chronologically.
- Reflection blocks were added for #29 follow-up — narration the
- model emitted between tool calls used to be wiped on the next
- iteration; now it persists as a collapsible block, in the
- order the model produced it. */}
+ {/* Agent Mode: render tool_call + reflection + answer blocks
+ chronologically. Reflection blocks persist narration the model
+ emitted between tool calls (added for #29 follow-up). Answer
+ blocks (2026-05) carry each iteration's outgoing text so the
+ tool calls don't all stack above a wall of summary at the
+ bottom — every provider, every model. */}
{!isUser && message.agentBlocks && message.agentBlocks.length > 0 && (
<>
{[...message.agentBlocks]
- .filter((b) => b.phase === 'tool_call' || b.phase === 'reflection')
+ .filter(
+ (b) =>
+ b.phase === 'tool_call' ||
+ b.phase === 'reflection' ||
+ (b.phase === 'answer' && b.content.trim()),
+ )
.sort((a, b) => a.timestamp - b.timestamp)
.map((block) => {
if (block.phase === 'tool_call' && block.toolCall) {
@@ -141,6 +147,15 @@ export function MessageBubble({ message, onRegenerate, onEdit, pendingApprovalId
if (block.phase === 'reflection') {
return <ReflectionBlock key={block.id} content={block.content} />
}
+ if (block.phase === 'answer') {
+ return (
+ <div key={block.id} className="px-1 py-0.5">
+ <div className="text-[0.8rem] leading-relaxed">
+ <MarkdownRenderer content={block.content} />
+ </div>
+ </div>
+ )
+ }
return null
})}
</>
@@ -207,24 +222,36 @@ export function MessageBubble({ message, onRegenerate, onEdit, pendingApprovalId
) : isUser ? (
<p className="text-[0.78rem] leading-relaxed text-gray-800 dark:text-gray-200 whitespace-pre-wrap">{message.content}</p>
) : (
- <div className="text-[0.78rem] leading-relaxed">
- <MarkdownRenderer content={message.content} />
- {suggestAgent && (
- <div className="mt-2 flex items-start gap-2 px-2 py-1.5 rounded-md border border-amber-400/30 bg-amber-500/10 text-[0.65rem] text-amber-700 dark:text-amber-200">
- <Wrench size={11} className="mt-0.5 shrink-0" />
- <div className="flex-1">
- <p className="font-medium">This model tried to call a tool, but Agent Mode is off for this chat.</p>
- <p className="opacity-80 mt-0.5">Turn it on to let the model actually execute tools (read files, run commands, browse). Until then it'll keep emitting JSON that nothing reads.</p>
- </div>
- <button
- onClick={() => activeConversationId && toggleAgentMode(activeConversationId)}
- className="shrink-0 px-2 py-0.5 rounded border border-amber-400/40 hover:bg-amber-500/20 transition-colors font-medium"
- >
- Enable Agent
- </button>
+ // Answer-blocks (when present) already rendered the per-iteration
+ // text chronologically above; skip message.content here to avoid
+ // a duplicate dump at the bottom. Falls back to message.content
+ // for legacy chats / non-agent messages without answer blocks.
+ (() => {
+ const hasAnswerBlock = !!message.agentBlocks?.some(
+ (b) => b.phase === 'answer' && b.content.trim(),
+ )
+ if (hasAnswerBlock) return null
+ return (
+ <div className="text-[0.78rem] leading-relaxed">
+ <MarkdownRenderer content={message.content} />
+ {suggestAgent && (
+ <div className="mt-2 flex items-start gap-2 px-2 py-1.5 rounded-md border border-amber-400/30 bg-amber-500/10 text-[0.65rem] text-amber-700 dark:text-amber-200">
+ <Wrench size={11} className="mt-0.5 shrink-0" />
+ <div className="flex-1">
+ <p className="font-medium">This model tried to call a tool, but Agent Mode is off for this chat.</p>
+ <p className="opacity-80 mt-0.5">Turn it on to let the model actually execute tools (read files, run commands, browse). Until then it'll keep emitting JSON that nothing reads.</p>
+ </div>
+ <button
+ onClick={() => activeConversationId && toggleAgentMode(activeConversationId)}
+ className="shrink-0 px-2 py-0.5 rounded border border-amber-400/40 hover:bg-amber-500/20 transition-colors font-medium"
+ >
+ Enable Agent
+ </button>
+ </div>
+ )}
</div>
- )}
- </div>
+ )
+ })()
)}
{!isEditing && (
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 3b741d82..ea83a8b8 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -1,7 +1,7 @@
import { useRef, useState, useCallback } from 'react'
import { v4 as uuid } from 'uuid'
import { chatNonStreaming } from '../api/agents'
-import { setActiveChatId, clearActiveChatId, chatWorkspaceSlug, setActiveWorkspace, setActiveAgentModel } from '../api/agent-context'
+import { setActiveChatId, clearActiveChatId, chatWorkspaceSlug, setActiveWorkspace, setActiveAgentModel, renderWorkspaceSection } from '../api/agent-context'
import { isOllamaLocal } from '../api/backend'
import { resolveWorkspace } from '../api/agents/workspace-resolve'
import { useAgentModeStore } from '../stores/agentModeStore'
@@ -376,6 +376,17 @@ export function useAgentChat() {
? buildHermesToolPrompt(hermesToolDefs) + (systemPrompt ? `\n\n${systemPrompt}` : '')
: buildAgentSystemPrompt(systemPrompt)
+ // Multi-Repo (Sprint C #8): when the agent workspace has extra paths,
+ // append a "Workspaces" section so the model can reference them by
+ // absolute path. Tool resolution still anchors relatives at the
+ // primary path via chatCtx → activeWorkspace.
+ {
+ const ws = useAgentModeStore.getState().workspaces[convId]
+ if (ws?.kind === 'folder' && (ws.extraPaths?.length ?? 0) > 0) {
+ agentSystemPrompt += renderWorkspaceSection(ws)
+ }
+ }
+
// Caveman mode: append as response style modifier AFTER agent instructions
// This ensures the model understands its agent role first, then applies terse style
if (settings.cavemanMode && settings.cavemanMode !== 'off') {
diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.ts
index b6022d6c..bf59fba9 100644
--- a/src/hooks/useChat.ts
+++ b/src/hooks/useChat.ts
@@ -13,6 +13,7 @@ import { useAgentChat } from "./useAgentChat"
import { useMemory } from "./useMemory"
import { useAgentModeStore } from "../stores/agentModeStore"
import { getProviderForModel, getProviderIdFromModel } from "../api/providers"
+import { syncOllamaHealthFromError } from "../lib/sync-ollama-health"
import { isThinkingCompatible, isPlainTextPlanner } from "../lib/model-compatibility"
import { stripNonCanonicalTags, finalStripThinkingTags } from "../lib/thinking-stripper"
import type { ChatStreamChunk } from "../api/providers/types"
@@ -315,6 +316,12 @@ export function useChat() {
}
} catch (err) {
if ((err as Error).name !== "AbortError") {
+ // Bug C — translate Ollama provider errors into health-store
+ // updates so the header chip + top banner light up reactively.
+ // Helper-extracted so additional catch sites (useABCompare etc.)
+ // can call the same translation without re-implementing it.
+ syncOllamaHealthFromError(err)
+
const errorMsg = (err as any).code === 'auth'
? (err as Error).message
: (err as any).code === 'rate_limit'
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index b8922f2b..7a79a81d 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -47,6 +47,19 @@ function diagLog(_tag: string, _data: unknown): void {
/* release: no-op */
}
+// Review-mode system prompt (B13). In review mode this REPLACES the base
+// CODEX_SYSTEM_PROMPT entirely — the autonomy/build contract is the wrong
+// framing for a read-only reviewer and would fight the executor gate. The
+// list-stripping below (REVIEW_MODE_FORBIDDEN_TOOLS) still enforces
+// read-only programmatically even if the model tries a write tool anyway.
+const CODEX_REVIEW_SYSTEM_PROMPT = `You are Codex in REVIEW MODE — a read-only code reviewer inside Locally Uncensored. You DO NOT modify any files, run any commands, or change any state. Your job is to read code with file_read / file_list / file_search / git_diff / git_log and return INLINE COMMENTS only.
+
+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, shell_execute, code_execute, run_tests, git_commit, git_push, gh_pr_create, image_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.
+- 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.`
+
const CODEX_SYSTEM_PROMPT = `You are Codex, an autonomous coding agent inside Locally Uncensored. You execute coding tasks end-to-end by reading files, writing code, and running shell commands. You MUST use tools — never guess file contents.
AUTONOMY CONTRACT (read carefully):
@@ -99,6 +112,10 @@ const REVIEW_MODE_FORBIDDEN_TOOLS = new Set([
'run_tests',
'image_generate',
'run_workflow',
+ // Parity with uselu's review blocklist — a reviewer must not capture the
+ // screen or hand work off to a sub-agent that could mutate state.
+ 'screenshot',
+ 'delegate_task',
])
// `.lurules` reader — backendCall wraps the desktop Tauri `file_read`
@@ -233,8 +250,14 @@ export function useCodex() {
// Build permissions — auto-approve reads, confirm writes
const permissions = usePermissionStore.getState().getEffectivePermissions(convId)
- // System prompt with working directory
- let systemPrompt = `${CODEX_SYSTEM_PROMPT}\n\nWorking directory: ${workDir}`
+ // System prompt with working directory. Review mode swaps the base
+ // prompt to lock the model into read-only behaviour — the
+ // list-stripping below (REVIEW_MODE_FORBIDDEN_TOOLS) still enforces it
+ // programmatically even if the model tries to call a write tool anyway.
+ const reviewMode = settings.codexReviewMode === true
+ let systemPrompt = reviewMode
+ ? `${CODEX_REVIEW_SYSTEM_PROMPT}\n\nWorking directory: ${workDir}`
+ : `${CODEX_SYSTEM_PROMPT}\n\nWorking directory: ${workDir}`
// Memory injection — parity with Chat + Agent. Codex was the only
// surface that ignored the memory system; now it sees remembered
@@ -274,16 +297,11 @@ export function useCodex() {
systemPrompt += '\n\nBefore answering, reason through your thinking inside <think></think> tags. Your thinking will be hidden from the user. After thinking, provide your answer outside the tags.'
}
- // Code-Review Mode banner (B13). Tells the model up front that it
- // is in review-only mode so it doesn't try to call write tools that
- // the filter below would just strip — saving an iteration where the
- // model would otherwise discover the missing tool by tool-error.
- if (settings.codexReviewMode) {
- systemPrompt += `\n\nCODE-REVIEW MODE (active):
-- You have READ-ONLY access. Do NOT call file_write, shell_execute, code_execute, git_commit, git_push, project_init, gh_pr_create, run_tests, image_generate, or run_workflow.
-- Inspect the codebase using file_read, file_list, file_search, git_status, git_log, git_diff, pr_resume.
-- Deliver your review as inline comments and a final summary. Reference files and line numbers explicitly. Suggest changes in prose — do not apply them.`
- }
+ // Code-Review Mode (B13) — the dedicated CODEX_REVIEW_SYSTEM_PROMPT
+ // above already replaced the base prompt with the read-only contract,
+ // so no extra banner append is needed here. The list-stripping in the
+ // tool-build path (REVIEW_MODE_FORBIDDEN_TOOLS) remains the
+ // belt-and-braces programmatic guard.
// Caveman mode: append as response style modifier after Codex instructions
if (settings.cavemanMode && settings.cavemanMode !== 'off') {
@@ -728,6 +746,17 @@ export function useCodex() {
if (turnContent) {
fullContent += (fullContent ? '\n\n' : '') + turnContent
useChatStore.getState().updateMessageContent(convId, assistantMsg.id, fullContent)
+ // Interleaving (2026-05) — also push the iteration's text as an
+ // 'answer' block so the renderer can put it BETWEEN the previous
+ // and next tool calls instead of stacking every step's commentary
+ // at the bottom. The fullContent path stays as the persisted
+ // history payload for back-compat with older chats.
+ addBlock({
+ id: uuid(),
+ phase: 'answer',
+ content: turnContent,
+ timestamp: Date.now(),
+ })
}
// No tool calls → done
@@ -813,6 +842,26 @@ export function useCodex() {
}))
const auditIds = new Map<string, string>()
+ // Pre-read the on-disk version of every file_write target so we can
+ // emit a unified diff alongside the file_change event regardless of
+ // stage mode. Missing files become an empty old version (the diff
+ // renders as a pure insert). Errors are swallowed — a failing
+ // pre-read just means the file_change event won't carry a diff,
+ // never blocks the write.
+ const oldContents = new Map<string, string>()
+ await Promise.all(
+ batch
+ .filter((e) => e.ac.toolName === 'file_write' && typeof e.injectedArgs.path === 'string')
+ .map(async (e) => {
+ try {
+ const r = await backendCall<{ content?: string }>('file_read', { path: e.injectedArgs.path })
+ oldContents.set(e.ac.id, r?.content ?? '')
+ } catch {
+ oldContents.set(e.ac.id, '')
+ }
+ }),
+ )
+
// 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).
@@ -926,9 +975,24 @@ export function useCodex() {
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.
+ 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, timestamp: Date.now(),
+ filePath: entry.injectedArgs.path,
+ diff: diff || undefined,
+ timestamp: Date.now(),
})
} else if (isError) {
codexStore.addEvent(convId, {
diff --git a/src/lib/sync-ollama-health.ts b/src/lib/sync-ollama-health.ts
new file mode 100644
index 00000000..0d129eaa
--- /dev/null
+++ b/src/lib/sync-ollama-health.ts
@@ -0,0 +1,35 @@
+/**
+ * Mirror a typed Ollama provider error into the shared health store.
+ *
+ * The provider layer is intentionally store-free (see ProviderError
+ * docstring in api/providers/types.ts) — that means every UI catch site
+ * that wants the header chip + top banner to update needs to translate the
+ * error code into a store call itself. This helper is that translation,
+ * kept in one place so the mapping `code → store action` doesn't drift
+ * between catch sites.
+ *
+ * Desktop note: the desktop `modelHealthStore` tracks a single
+ * `staleModels` list (its fix and UI treatment — StaleModelsBanner
+ * "Refresh All" + Header chip — are identical for both failure modes).
+ * Both `ollama_stale_manifest` AND `ollama_missing_blob` share the exact
+ * same recovery (`ollama pull <model>`), so both route into `staleModels`
+ * here. (uselu's web build keeps a separate `missingBlobModels` array +
+ * `markMissingBlob` action; desktop has no such slot, so we fold both
+ * codes into the one list the store actually exposes.)
+ *
+ * Pure side-effect — no return value. Safe to call with any unknown
+ * `err`; only acts on `ProviderError` with the recognised codes.
+ */
+
+import { ProviderError } from '../api/providers/types'
+import { useModelHealthStore } from '../stores/modelHealthStore'
+
+export function syncOllamaHealthFromError(err: unknown): void {
+ if (!(err instanceof ProviderError) || !err.model) return
+ if (err.code !== 'ollama_missing_blob' && err.code !== 'ollama_stale_manifest') return
+
+ const store = useModelHealthStore.getState()
+ if (!store.staleModels.includes(err.model)) {
+ store.setStaleModels([...store.staleModels, err.model])
+ }
+}