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.

fix(chat-agent): stop over-loop, strip JSON leaks, fix context overflow, stream thinking live

purpleb70fc4f063e5
diff --git a/src/api/__tests__/vram-handoff.test.ts b/src/api/__tests__/vram-handoff.test.ts
index cffee748..bc37f52e 100644
--- a/src/api/__tests__/vram-handoff.test.ts
+++ b/src/api/__tests__/vram-handoff.test.ts
@@ -81,7 +81,7 @@ vi.mock('../agent-context', () => ({
// settingsStore is the real module — pure, no services. The orchestrator reads
// settings.exclusiveVramMode through it; default DEFAULT_SETTINGS = 'auto'.
-import { decideUnload, vramHandoffGenerate, pollGone, resolveClip } from '../vram-handoff'
+import { decideUnload, vramHandoffGenerate, pollGone, resolveClip, resolveModelName } from '../vram-handoff'
import { useSettingsStore } from '../../stores/settingsStore'
const GB = 1024 * 1024 * 1024
@@ -483,3 +483,36 @@ describe('vramHandoffGenerate — ComfyUI lifecycle', () => {
expect(out).toContain('Image generated: out.png')
})
})
+
+describe('resolveModelName — fuzzy model match (David 2026-06-04: "FramePack" must be enough)', () => {
+ const installed = [
+ { name: 'FramePackI2V_HY_fp8_e4m3fn.safetensors' },
+ { name: 'svd_xt_1_1.safetensors' },
+ { name: 'wan2.1_t2v_1.3B_bf16.safetensors' },
+ { name: 'sd_xl_base_1.0.safetensors' },
+ ]
+ it('resolves a casual "FramePack" to the exact installed filename', () => {
+ expect(resolveModelName('FramePack', installed)).toBe('FramePackI2V_HY_fp8_e4m3fn.safetensors')
+ })
+ it('resolves case-insensitively ("framepack")', () => {
+ expect(resolveModelName('framepack', installed)).toBe('FramePackI2V_HY_fp8_e4m3fn.safetensors')
+ })
+ it('resolves "SVD" → svd_xt_1_1', () => {
+ expect(resolveModelName('SVD', installed)).toBe('svd_xt_1_1.safetensors')
+ })
+ it('resolves "wan" → the wan t2v model', () => {
+ expect(resolveModelName('wan', installed)).toBe('wan2.1_t2v_1.3B_bf16.safetensors')
+ })
+ it('resolves an exact filename unchanged', () => {
+ expect(resolveModelName('svd_xt_1_1.safetensors', installed)).toBe('svd_xt_1_1.safetensors')
+ })
+ it('resolves "sdxl" via substring to the SDXL base', () => {
+ expect(resolveModelName('sdxl', installed)).toBe('sd_xl_base_1.0.safetensors')
+ })
+ it('returns null when nothing matches (caller reports it, no silent wrong model)', () => {
+ expect(resolveModelName('totally-unknown-xyz', installed)).toBeNull()
+ })
+ it('returns null for an empty installed list', () => {
+ expect(resolveModelName('FramePack', [])).toBeNull()
+ })
+})
diff --git a/src/api/vram-handoff.ts b/src/api/vram-handoff.ts
index 9f153de3..3163da6e 100644
--- a/src/api/vram-handoff.ts
+++ b/src/api/vram-handoff.ts
@@ -69,6 +69,43 @@ import type { ModelCapabilities } from './comfyui-nodes'
import { getActiveAgentModel } from './agent-context'
import { log } from '../lib/logger'
+/**
+ * Resolve a casual model name the user/LLM typed (e.g. "FramePack", "wan",
+ * "sdxl") to an actually-installed model FILENAME. David 2026-06-04: no end user
+ * types `FramePackI2V_HY_fp8_e4m3fn.safetensors`. Tries, in order: normalized
+ * exact match, requested-is-substring-of-model, model-is-substring, then token
+ * overlap. Returns null when nothing matches confidently, so the caller reports
+ * it instead of silently generating with the wrong model.
+ */
+export function resolveModelName(
+ requested: string,
+ installed: { name: string }[],
+): string | null {
+ const norm = (s: string) =>
+ s.toLowerCase().replace(/\.(safetensors|ckpt|pt|pth|gguf|sft|bin)$/i, '').replace(/[^a-z0-9]+/g, '')
+ const r = norm(requested)
+ if (!r || installed.length === 0) return null
+ // 1) exact normalized filename match
+ let hit = installed.find((m) => norm(m.name) === r)
+ if (hit) return hit.name
+ // 2) casual name contained in a model filename ("framepack" → "framepacki2v…")
+ hit = installed.find((m) => norm(m.name).includes(r))
+ if (hit) return hit.name
+ // 3) a model filename contained in the (longer) requested string
+ hit = installed.find((m) => norm(m.name).length >= 3 && r.includes(norm(m.name)))
+ if (hit) return hit.name
+ // 4) token overlap — most request words appear in the model filename
+ const tokens = requested.toLowerCase().split(/[^a-z0-9]+/).filter((t) => t.length > 2)
+ let best: { name: string } | null = null
+ let bestScore = 0
+ for (const m of installed) {
+ const mn = norm(m.name)
+ const score = tokens.filter((t) => mn.includes(t)).length
+ if (score > bestScore) { bestScore = score; best = m }
+ }
+ return best && bestScore > 0 ? best.name : null
+}
+
export type HandoffPhase =
| 'deciding'
| 'freeing_vram'
@@ -433,7 +470,16 @@ async function runHandoff(kind: 'image' | 'video', args: VramHandoffArgs): Promi
emitHandoff('error', { kind, detail: 'no image model installed' })
return 'Error: No image model installed. Download one from Models → Discover (e.g. "FLUX.1 [schnell] FP8", "Z-Image Turbo", or "Juggernaut XL V9") and try again.'
}
- targetModel = typeof args.model === 'string' && args.model ? args.model : models[0].name
+ if (typeof args.model === 'string' && args.model) {
+ const resolved = resolveModelName(args.model, models)
+ if (!resolved) {
+ emitHandoff('error', { kind, detail: 'model not found' })
+ return `Error: No installed image model matches "${args.model}". Installed: ${models.map((m) => m.name).join(', ')}. Try one of those names (a partial name like "FLUX" or "SDXL" works).`
+ }
+ targetModel = resolved
+ } else {
+ targetModel = models[0].name
+ }
} else {
const [models, backend] = await Promise.all([getVideoModels(), detectVideoBackend()])
const wantI2V = typeof args.inputImage === 'string' && !!args.inputImage
@@ -445,7 +491,16 @@ async function runHandoff(kind: 'image' | 'video', args: VramHandoffArgs): Promi
emitHandoff('error', { kind, detail: 'no i2v model installed' })
return 'Error: Image-to-video needs an I2V model such as SVD. Install one from Models → Discover (e.g. "SVD-XT 1.1 — Image to Video"), then try again.'
}
- targetModel = typeof args.model === 'string' && args.model ? args.model : i2vModels[0].name
+ if (typeof args.model === 'string' && args.model) {
+ const resolved = resolveModelName(args.model, i2vModels)
+ if (!resolved) {
+ emitHandoff('error', { kind, detail: 'i2v model not found' })
+ return `Error: No installed image-to-video model matches "${args.model}". Installed I2V: ${i2vModels.map((m) => m.name).join(', ')}. A partial name like "SVD" or "FramePack" works.`
+ }
+ targetModel = resolved
+ } else {
+ targetModel = i2vModels[0].name
+ }
videoBackend = backend
} else {
// Text-to-video must NOT pick an image-to-video-only checkpoint (SVD /
@@ -457,7 +512,16 @@ async function runHandoff(kind: 'image' | 'video', args: VramHandoffArgs): Promi
emitHandoff('error', { kind, detail: 'no text-to-video model installed' })
return 'Error: No text-to-video model installed. Download one from Models → Discover (e.g. "Wan 2.1 — 1.3B (Lightweight)" for 8-10 GB VRAM or "HunyuanVideo 1.5 T2V FP8" for 12+ GB) — or generate an image first and animate it with an I2V model like "SVD-XT 1.1".'
}
- targetModel = typeof args.model === 'string' && args.model ? args.model : t2vModels[0].name
+ if (typeof args.model === 'string' && args.model) {
+ const resolved = resolveModelName(args.model, t2vModels)
+ if (!resolved) {
+ emitHandoff('error', { kind, detail: 't2v model not found' })
+ return `Error: No installed text-to-video model matches "${args.model}". Installed T2V: ${t2vModels.map((m) => m.name).join(', ')}. A partial name like "Wan" or "Hunyuan" works.`
+ }
+ targetModel = resolved
+ } else {
+ targetModel = t2vModels[0].name
+ }
videoBackend = backend
}
}
diff --git a/src/components/chat/MessageBubble.tsx b/src/components/chat/MessageBubble.tsx
index 1d687d17..5d1a920b 100644
--- a/src/components/chat/MessageBubble.tsx
+++ b/src/components/chat/MessageBubble.tsx
@@ -111,9 +111,10 @@ export function MessageBubble({ message, onRegenerate, onEdit, pendingApprovalId
</div>
<div className="max-w-[80%] space-y-0.5">
- {/* Thinking block */}
+ {/* Thinking block — auto-expands while this (last) turn is still
+ producing so the reasoning streams LIVE, then collapses (David 2026-06-04). */}
{!isUser && message.thinking && (
- <ThinkingBlock thinking={message.thinking} />
+ <ThinkingBlock thinking={message.thinking} streaming={!!isLast && !message.content?.trim()} />
)}
{/* Agent Mode: render tool_call + reflection + answer blocks
diff --git a/src/components/chat/ThinkingBlock.tsx b/src/components/chat/ThinkingBlock.tsx
index a2d2ad97..dffa78db 100644
--- a/src/components/chat/ThinkingBlock.tsx
+++ b/src/components/chat/ThinkingBlock.tsx
@@ -1,21 +1,29 @@
-import { useState } from 'react'
+import { useState, useEffect } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { ChevronDown, Brain } from 'lucide-react'
import { MarkdownRenderer } from './MarkdownRenderer'
interface Props {
thinking: string
+ /** True while the model is actively producing this turn. Auto-expands the
+ * block so the reasoning is visible STREAMING in real time (David 2026-06-04),
+ * then auto-collapses once the turn finishes. The user can still toggle. */
+ streaming?: boolean
}
-export function ThinkingBlock({ thinking }: Props) {
- const [open, setOpen] = useState(false)
+export function ThinkingBlock({ thinking, streaming }: Props) {
+ // null = follow `streaming` automatically; true/false = user override.
+ const [userToggled, setUserToggled] = useState<boolean | null>(null)
+ const open = userToggled !== null ? userToggled : !!streaming
+ // When the turn ends, drop the manual override so the NEXT turn auto-expands.
+ useEffect(() => { if (!streaming) setUserToggled(null) }, [streaming])
if (!thinking) return null
return (
<div className="mb-0.5">
<button
- onClick={() => setOpen(!open)}
+ onClick={() => setUserToggled(!open)}
className="flex items-center gap-1.5 py-0.5 text-left hover:opacity-80 transition-opacity"
aria-label="Toggle thinking details"
>
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index f45b8d5a..1d4bbc5f 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -22,7 +22,7 @@ import { getToolPermission, executeAgentTool, AGENT_TOOL_DEFS } from '../api/too
import { getToolCallingStrategy, type ToolCallingStrategy } from '../lib/model-compatibility'
import { log } from '../lib/logger'
import { buildHermesToolPrompt, buildHermesToolResult, parseHermesToolCalls, stripToolCallTags, hasToolCallTags } from '../api/hermes-tool-calling'
-import { parseLooseToolCalls, stripMatchedCalls, canonicalToolName } from '../lib/loose-tool-parse'
+import { parseLooseToolCalls, stripMatchedCalls, stripToolCallText, canonicalToolName } from '../lib/loose-tool-parse'
import { buildVisionFeedback } from '../api/vision-feedback'
import { compactMessages, getModelMaxTokens } from '../lib/context-compaction'
import { useMemoryStore } from '../stores/memoryStore'
@@ -455,6 +455,29 @@ export function useAgentChat() {
agentMaxIterations: settings.agentMaxIterations ?? 25,
})
+ // ── Over-loop guard (David 2026-06-04) ──────────────────────────────
+ // LIVE: "mach mir ein bild von einer katze" made the SAME image 13× then
+ // invented new prompts and ran 4min+. Root cause: the loop only ends at 0
+ // tool calls, so a chatty model keeps emitting image_generate/video_generate.
+ // Fix: generate ONLY what the user asked for, exactly once each, then stop —
+ // plus a duplicate-call breaker so any tool repeated with identical args is
+ // skipped. Caps derive from the user's actual request.
+ const userPromptText =
+ [...agentMessages].reverse().find((m) => m.role === 'user')?.content || ''
+ 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
+ let imageGenDone = 0
+ let videoGenDone = 0
+ let mediaSteered = false
+ let mediaSynthesized = false
+ let forceNoThink = false
+ let dudRetried = false
+ const executedCallKeys = new Set<string>()
+ const callKey = (tc: { function: { name: string; arguments: unknown } }) =>
+ tc.function.name + '|' + JSON.stringify(tc.function.arguments ?? {})
+
try {
// ── Agent Loop ──────────────────────────────────────────
while (runningRef.current && !abort.signal.aborted) {
@@ -477,11 +500,16 @@ export function useAgentChat() {
// thinking mode; the stripper removes the tags silently.
const canThinkAgent = isThinkingCompatible(activeModel)
const plainPlanAgent = isPlainTextPlanner(activeModel)
- const thinkOpt: boolean | undefined = canThinkAgent
- ? (settings.thinkingEnabled === false && plainPlanAgent
- ? undefined
- : settings.thinkingEnabled === true)
- : undefined
+ // forceNoThink: set by the dud-turn recovery below — a thinking model
+ // (gemma4) dumped its whole answer into the thinking channel and emitted
+ // nothing usable, so we retry this turn with thinking OFF.
+ const thinkOpt: boolean | undefined = forceNoThink
+ ? (canThinkAgent ? false : undefined)
+ : canThinkAgent
+ ? (settings.thinkingEnabled === false && plainPlanAgent
+ ? undefined
+ : settings.thinkingEnabled === true)
+ : undefined
const chatOptions = {
temperature: settings.temperature,
@@ -489,13 +517,19 @@ export function useAgentChat() {
topK: settings.topK,
maxTokens: settings.maxTokens || undefined,
// Bug AA v2.5.0 — Kj103x. Same num_ctx override flow as useChat.
- contextWindow: settings.contextWindowOverride || undefined,
+ // David 2026-06-04: default the AGENT context to 8192 (not the model's
+ // 4096 default) so feeding a generated image back for vision feedback
+ // doesn't overflow ("request 5667 > available 4096" → HTTP 400 →
+ // "Agent error: Connection failed" after gemma's image). 8192 is within
+ // both installed models' real limits.
+ contextWindow: settings.contextWindowOverride || 8192,
thinking: thinkOpt as unknown as boolean,
signal: abort.signal,
}
- // Context compaction
- const maxCtx = await getModelMaxTokens(activeModel)
+ // Context compaction — keep the trim target in sync with the 8192 num_ctx
+ // above so a generated image fed back for vision isn't trimmed right out.
+ const maxCtx = Math.max(await getModelMaxTokens(activeModel), settings.contextWindowOverride || 8192)
agentMessages = compactMessages(
agentMessages as OllamaChatMessage[],
Math.floor(maxCtx * 0.8)
@@ -525,7 +559,7 @@ export function useAgentChat() {
function: { name: t.name, description: t.description, parameters: t.inputSchema },
}))
- let turn: { content: string; toolCalls: ToolCall[]; thinking?: string }
+ let turn!: { content: string; toolCalls: ToolCall[]; thinking?: string }
if (providerId === 'ollama') {
// Streaming path — parity with desktop Codex. Without this
// the user stared at a frozen chat for 30-90 s while Gemma
@@ -542,46 +576,24 @@ export function useAgentChat() {
removeBlock(convId!, assistantMessage.id, thinkingBlockId)
}
}
- try {
- turn = await streamOllamaChatWithTools(
- modelToUse,
- agentMessages,
- tools,
- {
- temperature: chatOptions.temperature,
- thinking: chatOptions.thinking,
- maxTokens: chatOptions.maxTokens,
- // Bug AA v2.5.0 — keep num_ctx override across the tool loop.
- contextWindow: chatOptions.contextWindow,
- signal: abort.signal,
- },
- (c) => {
- dropThinkingBlock()
- // Live-update the visible content. Same accumulator
- // pattern as Codex: each chunk is the FULL content so
- // far, not a delta — assign directly.
- contentRef.current = c
- scheduleUIUpdate()
- },
- (t) => {
- dropThinkingBlock()
- if (settings.thinkingEnabled === true) {
- thinkingRef.current = t
- scheduleUIUpdate()
- }
- },
- )
- } catch (thinkErr: any) {
- if (thinkErr?.message?.includes('does not support thinking') || thinkErr?.statusCode === 400) {
+ // Connection-failure retry (David 2026-06-04): right after a VRAM
+ // hand-off reloads the text model, the very next call can race the
+ // still-warming model and die as "Agent error: Connection failed"
+ // (seen on gemma4 after its image). Retry transient errors a couple
+ // times before surfacing. The inner branch still handles the
+ // does-not-support-thinking downgrade.
+ let connRetries = 0
+ for (;;) {
+ try {
turn = await streamOllamaChatWithTools(
modelToUse,
agentMessages,
tools,
{
temperature: chatOptions.temperature,
- thinking: undefined,
+ thinking: chatOptions.thinking,
maxTokens: chatOptions.maxTokens,
- // Bug AA v2.5.0 — keep num_ctx override on the no-think retry too.
+ // Bug AA v2.5.0 — keep num_ctx override across the tool loop.
contextWindow: chatOptions.contextWindow,
signal: abort.signal,
},
@@ -590,9 +602,47 @@ export function useAgentChat() {
contentRef.current = c
scheduleUIUpdate()
},
- () => {},
+ (t) => {
+ dropThinkingBlock()
+ if (settings.thinkingEnabled === true) {
+ thinkingRef.current = t
+ scheduleUIUpdate()
+ }
+ },
)
- } else {
+ break
+ } catch (thinkErr: any) {
+ if (thinkErr?.message?.includes('does not support thinking') || thinkErr?.statusCode === 400) {
+ turn = await streamOllamaChatWithTools(
+ modelToUse,
+ agentMessages,
+ tools,
+ {
+ temperature: chatOptions.temperature,
+ thinking: undefined,
+ maxTokens: chatOptions.maxTokens,
+ contextWindow: chatOptions.contextWindow,
+ signal: abort.signal,
+ },
+ (c) => {
+ dropThinkingBlock()
+ contentRef.current = c
+ scheduleUIUpdate()
+ },
+ () => {},
+ )
+ break
+ }
+ // Retry ONLY transient failures. A 4xx (e.g. context overflow) is
+ // deterministic — retrying just repeats it, so let it surface.
+ const sc = typeof thinkErr?.statusCode === 'number' ? thinkErr.statusCode : 0
+ const transient = thinkErr?.name !== 'AbortError' && !(sc >= 400 && sc < 500)
+ if (transient && connRetries < 2) {
+ connRetries++
+ log.warn('agent.model_call_retry', { attempt: connRetries, err: String(thinkErr?.message || thinkErr) })
+ await new Promise((r) => setTimeout(r, 1500 * connRetries))
+ continue
+ }
throw thinkErr
}
}
@@ -698,7 +748,94 @@ export function useAgentChat() {
}
}
- const isFinalTurn = toolCalls.length === 0
+ // Clean any tool-call text the model echoed into its prose (David
+ // 2026-06-04) — raw JSON like {"name":"image_generate",…} was leaking
+ // into the chat as a "notes"/JSON block. Runs even when a proper native
+ // call was emitted alongside the echo. Tool args/results stay in the
+ // agent's internal history; this only cleans the visible bubble.
+ turnContent = stripToolCallText(turnContent, knownToolNames)
+
+ // Over-loop guard: keep only the media the user asked for (once each) and
+ // drop any tool call that exactly repeats one already run this turn.
+ if (toolCalls.length > 0) {
+ let allowImg = maxImageGen - imageGenDone
+ let allowVid = maxVideoGen - videoGenDone
+ let blocked = false
+ const kept: ToolCall[] = []
+ for (const tc of toolCalls) {
+ const name = tc.function.name
+ if (name === 'image_generate') {
+ if (allowImg > 0) { allowImg--; kept.push(tc) } else { blocked = true }
+ } else if (name === 'video_generate') {
+ if (allowVid > 0) { allowVid--; kept.push(tc) } else { blocked = true }
+ } else if (executedCallKeys.has(callKey(tc))) {
+ blocked = true
+ } else {
+ kept.push(tc)
+ }
+ }
+ if (kept.length !== toolCalls.length) {
+ log.info('agent.over_loop_blocked', {
+ kept: kept.map((t) => t.function.name),
+ dropped: toolCalls.length - kept.length,
+ })
+ }
+ toolCalls = kept
+ // Everything filtered out → the requested work is already done. Steer
+ // the model to a short final reply ONCE; if it STILL only emits blocked
+ // calls, fall through to the empty-content summary and stop cleanly.
+ if (toolCalls.length === 0 && blocked) {
+ if (!mediaSteered) {
+ mediaSteered = true
+ if (turnContent.trim()) {
+ addBlock(convId!, assistantMessage.id, {
+ id: uuid(), phase: 'reflection', content: turnContent, timestamp: Date.now(),
+ })
+ }
+ agentMessages.push({
+ role: 'user',
+ content:
+ 'Stop — the media you were asked for is already created and shown. Write ONLY a short, friendly closing line to the user in their own language (e.g. that their picture/clip is ready). Do not output JSON, do not repeat this note, and do not call any tool.',
+ } as ChatMessage)
+ continue
+ }
+ contentRef.current = turnContent
+ scheduleUIUpdate()
+ break
+ }
+ }
+
+ let isFinalTurn = toolCalls.length === 0
+ // Dud turn (David 2026-06-04): the model produced empty content + no tool
+ // call → the user used to see ONLY a thinking bubble, no answer.
+ if (isFinalTurn && !turnContent.trim() && executedCallKeys.size === 0) {
+ // 1st dud → retry once with thinking OFF (gemma4 dumps its whole
+ // response into the thinking channel and emits nothing usable).
+ if (!dudRetried && canThinkAgent && !forceNoThink) {
+ dudRetried = true
+ forceNoThink = true
+ log.info('agent.dud_turn_retry_no_think', { model: activeModel })
+ continue
+ }
+ // Still nothing AND the user clearly asked for media → a weak model
+ // (gemma4:e4b) often can't emit the tool call at all. Deliver what was
+ // asked by SYNTHESIZING the generation call from the user's prompt, so
+ // "mach mir ein bild von X" works even when the model flakes.
+ if (!mediaSynthesized &&
+ ((wantsImage && maxImageGen > 0 && imageGenDone === 0) ||
+ (wantsVideo && maxVideoGen > 0 && videoGenDone === 0))) {
+ mediaSynthesized = true
+ const useVideo = wantsVideo && maxVideoGen > 0 && videoGenDone === 0
+ toolCalls = [{
+ function: {
+ name: useVideo ? 'video_generate' : 'image_generate',
+ arguments: { prompt: extractMediaPrompt(userPromptText) },
+ },
+ }] as ToolCall[]
+ isFinalTurn = false
+ log.info('agent.media_fallback_synthesized', { tool: toolCalls[0].function.name })
+ }
+ }
if (isFinalTurn) {
contentRef.current = turnContent
thinkingRef.current = turnThinking
@@ -826,6 +963,14 @@ export function useAgentChat() {
const result = results.find((r) => r.id === entry.ac.id)
if (!result) continue
applyResultToToolCall(entry.ac, result)
+ // Over-loop accounting (David 2026-06-04): remember every executed call
+ // (so an identical repeat is skipped) and count successful media gens
+ // against the per-turn cap that stops "13× the same cat".
+ executedCallKeys.add(callKey(entry.tc))
+ if (result.status === 'completed' || result.status === 'cached') {
+ if (entry.ac.toolName === 'image_generate') imageGenDone++
+ else if (entry.ac.toolName === 'video_generate') videoGenDone++
+ }
const contentLabel =
result.status === 'completed'
? `Completed: ${entry.ac.toolName}`
@@ -868,6 +1013,18 @@ export function useAgentChat() {
// failed
return r.errorHint ? `${r.error ?? 'Tool failed'} — ${r.errorHint}` : (r.error ?? 'Tool failed')
}
+ // After a successful image/video gen, nudge a NATURAL closing comment so
+ // the model doesn't silently loop another generation (David 2026-06-04).
+ // The media-cap is the hard stop; this makes the normal path end with a
+ // friendly sentence instead of a blocked-then-steered robotic one.
+ const mediaNote = (name: string, r: typeof results[number]): string => {
+ if ((r.status === 'completed' || r.status === 'cached') &&
+ (name === 'image_generate' || name === 'video_generate')) {
+ const kind = name === 'video_generate' ? 'video' : 'image'
+ return `\n\n(The ${kind} is now displayed to the user. Respond with a short, natural comment in the user's language. Do NOT generate another ${kind} unless the user explicitly asks.)`
+ }
+ return ''
+ }
if (providerId === 'openai' || providerId === 'anthropic') {
agentMessages.push({
@@ -879,7 +1036,7 @@ export function useAgentChat() {
const result = results.find((r) => r.id === batch.find((b) => b.tc === tc)?.ac.id)!
agentMessages.push({
role: 'tool',
- content: resultTextFor(result),
+ content: resultTextFor(result) + mediaNote(tc.function.name, result),
tool_call_id: tc.id,
})
}
@@ -895,7 +1052,7 @@ export function useAgentChat() {
const result = results.find((r) => r.id === batch.find((b) => b.tc === tc)?.ac.id)!
agentMessages.push({
role: 'tool',
- content: resultTextFor(result),
+ content: resultTextFor(result) + mediaNote(tc.function.name, result),
})
}
} else {
@@ -907,7 +1064,7 @@ export function useAgentChat() {
})
agentMessages.push({
role: 'user',
- content: buildHermesToolResult(tc.function.name, resultTextFor(result)),
+ content: buildHermesToolResult(tc.function.name, resultTextFor(result) + mediaNote(tc.function.name, result)),
})
}
}
@@ -956,15 +1113,25 @@ export function useAgentChat() {
)
const writes = completedTools.filter((b) => b.toolCall?.toolName === 'file_write').length
const reads = completedTools.filter((b) => b.toolCall?.toolName === 'file_read').length
- const otherOk = completedTools.length - writes - reads
- const parts: string[] = []
- if (writes) parts.push(`${writes} file${writes === 1 ? '' : 's'} written`)
- if (reads) parts.push(`${reads} file${reads === 1 ? '' : 's'} read`)
- if (otherOk) parts.push(`${otherOk} operation${otherOk === 1 ? '' : 's'} completed`)
- if (failedTools.length) parts.push(`${failedTools.length} failed`)
- contentRef.current = parts.length
- ? `Task completed: ${parts.join(', ')}.`
- : 'Task completed.'
+ // Media-aware closing: if a picture/clip was produced, say so warmly
+ // instead of a robotic "1 operation completed" (David 2026-06-04).
+ if (imageGenDone > 0 || videoGenDone > 0) {
+ contentRef.current = imageGenDone > 0 && videoGenDone > 0
+ ? 'Fertig — dein Bild und dein Video sind oben. / Done — your image and video are above.'
+ : videoGenDone > 0
+ ? 'Fertig — dein Video ist oben. / Done — your video is above.'
+ : 'Fertig — dein Bild ist oben. / Done — your image is above.'
+ } else {
+ const otherOk = completedTools.length - writes - reads
+ const parts: string[] = []
+ if (writes) parts.push(`${writes} file${writes === 1 ? '' : 's'} written`)
+ if (reads) parts.push(`${reads} file${reads === 1 ? '' : 's'} read`)
+ if (otherOk) parts.push(`${otherOk} operation${otherOk === 1 ? '' : 's'} completed`)
+ if (failedTools.length) parts.push(`${failedTools.length} failed`)
+ contentRef.current = parts.length
+ ? `Task completed: ${parts.join(', ')}.`
+ : "I couldn't produce a response for that. Please rephrase, or turn off Think and send again."
+ }
}
// Final store update
@@ -1054,6 +1221,21 @@ export function useAgentChat() {
// ── Agent System Prompt Builder ─────────────────────────────────
+/**
+ * Turn a user request like "mach mir ein bild von einem hund" into a clean
+ * generation prompt ("einem hund") by stripping the leading command phrase
+ * (DE + EN). Used by the dud-turn media fallback when a weak model can't emit
+ * the tool call itself. Falls back to the full text if nothing strips.
+ */
+export function extractMediaPrompt(text: string): string {
+ const p = String(text || '').trim()
+ const stripped = p.replace(
+ /^(bitte\s+)?(mach(e|st)?|erstell(e)?|generier(e)?|zeichne|mal(e|en)?|create|make|draw|generate|gib\s+mir|show\s+me|zeig(e)?\s+mir)\s+(mir\s+)?(ein(e|en)?\s+)?(bild(er)?|foto|image|picture|pic|video|clip|grafik|illustration|animation)\s*(von|of|mit|with|from|über|about)?\s*/i,
+ '',
+ ).trim()
+ return stripped || p
+}
+
function buildAgentSystemPrompt(basePrompt: string): string {
const agentInstructions = `You are an autonomous AI agent inside Locally Uncensored with full access to this computer. You execute tasks end-to-end by using tools — you do NOT just describe what to do.
diff --git a/src/lib/__tests__/loose-tool-parse.test.ts b/src/lib/__tests__/loose-tool-parse.test.ts
index e293d08f..b090f56a 100644
--- a/src/lib/__tests__/loose-tool-parse.test.ts
+++ b/src/lib/__tests__/loose-tool-parse.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
-import { parseLooseToolCalls, stripMatchedCalls, canonicalToolName } from '../loose-tool-parse'
+import { parseLooseToolCalls, stripMatchedCalls, stripToolCallText, canonicalToolName } from '../loose-tool-parse'
const KNOWN = ['image_generate', 'video_generate', 'web_search', 'file_write']
@@ -129,3 +129,38 @@ describe('stripMatchedCalls', () => {
expect(stripped.toLowerCase()).toContain('okay')
})
})
+
+describe('stripToolCallText — keep raw tool-call JSON out of the visible bubble', () => {
+ it('strips a bare {"name","arguments"} object, keeps the prose (David 2026-06-04 leak)', () => {
+ const txt = 'Hier ist dein Bild.\n{ "name": "image_generate", "arguments": { "prompt": "eine katze" } }'
+ const out = stripToolCallText(txt, KNOWN)
+ expect(out).toContain('Hier ist dein Bild.')
+ expect(out).not.toContain('"name"')
+ expect(out).not.toContain('image_generate')
+ })
+
+ it('strips a fenced ```json tool call but keeps surrounding prose', () => {
+ const txt = 'Okay:\n```json\n{ "name": "image_generate", "arguments": { "prompt": "a cat" } }\n```'
+ const out = stripToolCallText(txt, KNOWN)
+ expect(out).not.toContain('image_generate')
+ expect(out.toLowerCase()).toContain('okay')
+ })
+
+ it('strips function-call syntax echoed alongside a native call', () => {
+ const out = stripToolCallText('Generating now image_generate(prompt="a fox")', KNOWN)
+ expect(out).not.toContain('image_generate(')
+ })
+
+ it('leaves ordinary prose untouched', () => {
+ expect(stripToolCallText('The cube is small and red.', KNOWN)).toBe('The cube is small and red.')
+ })
+
+ it('keeps a non-tool JSON object (no known tool name) intact', () => {
+ const out = stripToolCallText('Result: {"foo": 1, "bar": 2}', KNOWN)
+ expect(out).toContain('foo')
+ })
+
+ it('returns empty when the content is ONLY a tool call', () => {
+ expect(stripToolCallText('{ "name": "video_generate", "arguments": { "seconds": 4 } }', KNOWN)).toBe('')
+ })
+})
diff --git a/src/lib/loose-tool-parse.ts b/src/lib/loose-tool-parse.ts
index 655c2941..104c0899 100644
--- a/src/lib/loose-tool-parse.ts
+++ b/src/lib/loose-tool-parse.ts
@@ -75,8 +75,8 @@ function parseCallArgs(inner: string): Record<string, unknown> {
}
/** Find bare/fenced JSON objects that name a known tool: {"name":"X","arguments":{…}}. */
-function parseJsonObjectCalls(text: string, known: Set<string>): LooseToolCall[] {
- const calls: LooseToolCall[] = []
+function parseJsonObjectCalls(text: string, known: Set<string>): { call: LooseToolCall; snippet: string }[] {
+ const calls: { call: LooseToolCall; snippet: string }[] = []
// Scan every top-level-ish {...} candidate. Cheap brace-scan; repairJson
// tolerates trailing commas / single quotes / unquoted keys.
const candidates: string[] = []
@@ -103,7 +103,9 @@ function parseJsonObjectCalls(text: string, known: Set<string>): LooseToolCall[]
const name = parsed.name || parsed.tool || parsed.tool_name || parsed.function
if (typeof name === 'string' && known.has(name)) {
const a = parsed.arguments || parsed.parameters || parsed.args || parsed.params || {}
- calls.push({ name, arguments: (a && typeof a === 'object') ? a : {} })
+ // Report the source snippet so the caller can strip the raw JSON object
+ // from the visible prose (otherwise it leaks as a "notes"/JSON block).
+ calls.push({ call: { name, arguments: (a && typeof a === 'object') ? a : {} }, snippet: cand })
}
}
return calls
@@ -141,8 +143,8 @@ export function parseLooseToolCalls(text: string, known: string[]): LooseParseRe
while ((tm = tagRe.exec(text)) !== null) matched.push(tm[0])
}
- // 2) JSON objects naming a known tool.
- for (const c of parseJsonObjectCalls(text, knownSet)) push(c, '')
+ // 2) JSON objects naming a known tool (snippet reported so prose can be cleaned).
+ for (const { call, snippet } of parseJsonObjectCalls(text, knownSet)) push(call, snippet)
// 3) Function-call syntax name( ... ) — only for known tool names.
for (const name of knownSet) {
@@ -202,3 +204,32 @@ export function stripMatchedCalls(text: string, matched: string[]): string {
// Tidy leftover empty code fences / blank lines.
return out.replace(/```(?:json|python|tool_code)?\s*```/gi, '').replace(/\n{3,}/g, '\n\n').trim()
}
+
+/**
+ * Strip ANY recognizable tool-call text (JSON object, function-syntax, Hermes
+ * tag, or a fenced ```json block that is actually a call) out of a model's
+ * VISIBLE prose. Unlike the loose-parse → strip path (which only runs when the
+ * native channel produced nothing), this is meant to run on EVERY turn's
+ * content so a model that emits a proper native call AND echoes the same call
+ * as text doesn't leak raw JSON into the chat as a "notes"/JSON block.
+ *
+ * Only `known` tool names are recognized, so ordinary prose with stray braces
+ * is left intact. Tool args/results remain in the agent's internal history —
+ * this only cleans what the USER sees in the bubble.
+ */
+export function stripToolCallText(text: string, known: string[]): string {
+ if (!text || !text.trim()) return ''
+ const { matched } = parseLooseToolCalls(text, known)
+ let out = stripMatchedCalls(text, matched)
+ // Drop fenced code blocks whose body is a tool call (```json {"name":…}```).
+ out = out.replace(/```(?:json|tool_code|tool|python)?\s*([\s\S]*?)```/gi, (m, inner) => {
+ const looksLikeCall =
+ /["']?(?:name|tool|function)["']?\s*[:=]/.test(inner) &&
+ /["']?(?:arguments|parameters|params|prompt)["']?\s*[:=]/.test(inner)
+ return looksLikeCall ? '' : m
+ })
+ return out
+ .replace(/```(?:json|tool_code)?\s*```/gi, '')
+ .replace(/\n{3,}/g, '\n\n')
+ .trim()
+}