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+media): cancel reliability, VRAM-swap recovery, web upload proxy, chat-tools banner

purple0f4a582a8ed5
diff --git a/src/api/__tests__/vram-handoff.test.ts b/src/api/__tests__/vram-handoff.test.ts
index dbf64cb2..b23ba987 100644
--- a/src/api/__tests__/vram-handoff.test.ts
+++ b/src/api/__tests__/vram-handoff.test.ts
@@ -412,9 +412,11 @@ describe('vramHandoffGenerate — finally always restores the text model', () =>
await vramHandoffGenerate('image', { prompt: 'a fox' })
// 5GB + ~4GB sd15 = 9GB < 24GB → fits → no eviction.
expect(unloadModel).not.toHaveBeenCalled()
- // …but ComfyUI VRAM is still freed afterwards (cleanup), and no reload was
- // needed because nothing was evicted.
- expect(freeMemory).toHaveBeenCalled()
+ // Bug C (David 2026-06-16): when nothing was evicted we now SKIP the ComfyUI
+ // freeMemory in the finally so the checkpoint stays resident and the NEXT
+ // generation reuses it warm instead of cold-loading every time. Nothing
+ // evicted → no reload either.
+ expect(freeMemory).not.toHaveBeenCalled()
expect(loadModel).not.toHaveBeenCalled()
})
diff --git a/src/api/comfyui.ts b/src/api/comfyui.ts
index 3935bc76..7bca9bbf 100644
--- a/src/api/comfyui.ts
+++ b/src/api/comfyui.ts
@@ -924,6 +924,24 @@ export async function cancelGeneration(): Promise<void> {
} catch { /* best effort */ }
}
+/**
+ * Clear ComfyUI's PENDING queue (David 2026-06-16). /interrupt only stops the
+ * job that is currently executing; anything still queued (e.g. a duplicate that
+ * slipped in, or a second gen the model emitted) would start the instant the
+ * running one ends. On a user "Stop" we want EVERYTHING gone, so we clear the
+ * queue too. Best-effort — a failure here must never block the cancel path.
+ */
+export async function clearComfyQueue(): Promise<void> {
+ try {
+ await localFetch(comfyuiUrl('/queue'), {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ clear: true }),
+ timeoutMs: COMFY_STATS_TIMEOUT_MS,
+ })
+ } catch { /* best effort */ }
+}
+
export async function freeMemory(): Promise<void> {
try {
await localFetch(comfyuiUrl('/free'), {
diff --git a/src/api/vram-handoff.ts b/src/api/vram-handoff.ts
index a00596ad..648c8fbe 100644
--- a/src/api/vram-handoff.ts
+++ b/src/api/vram-handoff.ts
@@ -55,6 +55,8 @@ import {
submitWorkflow,
getHistory,
freeMemory,
+ cancelGeneration,
+ clearComfyQueue,
extractComfyOutputFiles,
getImageUrl,
classifyModel,
@@ -351,7 +353,9 @@ async function ensureComfyRunning(timeoutMs = 90_000): Promise<boolean> {
}
const deadline = Date.now() + timeoutMs
while (Date.now() < deadline) {
- await sleep(1500)
+ // Bail fast if the user cancelled during the cold start (the caller checks
+ // _genCancelRequested right after us and reports it as "cancelled").
+ if ((await raceCancel(sleep(1500))) === CANCELLED) return false
if (await comfyIsRunning()) return true
}
return false
@@ -476,6 +480,56 @@ function sleep(ms: number): Promise<void> {
// reload-in-finally of call #1 can never overlap the generate of call #2.
let _inFlight: Promise<unknown> = Promise.resolve()
+// ── User-initiated cancel (David 2026-06-16) ────────────────────────────────
+// The agent's AbortController never reached the ComfyUI poll loop, so "Stop"
+// left ComfyUI rendering (a ~500 s SVD video kept burning the GPU after the UI
+// said it stopped). This module-level flag + ComfyUI /interrupt give the
+// in-chat cancel button a REAL abort. Only one generation runs at a time
+// (serialised via _inFlight), so one flag suffices.
+//
+// David 2026-06-16 (bug B): a bare flag checked only BETWEEN getHistory calls
+// wasn't enough — `image_generate` Stop "hung at stopping…". The hang: each
+// poll tick blocks in `await getHistory` (15 s cap) while ComfyUI COLD-LOADS the
+// checkpoint (RealVisXL is a long, non-interruptible load), and /interrupt is a
+// no-op during a model load. So the flag wasn't re-checked for up to 15 s and
+// the UI sat on "stopping…". Fix: a notify-promise (_cancelWait) that every long
+// await RACES against, so Stop bails within milliseconds regardless of which
+// phase we're in (eviction, ComfyUI cold-start, model-load, or sampling). We
+// also clear the ComfyUI queue, not just /interrupt, so a queued item can't
+// start after the running one is interrupted. runHandoff's finally still
+// restores the text model into VRAM exactly as before.
+const CANCELLED = '__lu_cancelled__' as const
+
+let _genCancelRequested = false
+let _cancelNotify: (() => void) | null = null
+// A promise that resolves to CANCELLED the instant Stop is pressed. Re-armed per
+// run by resetCancel() and built ONCE per gen (not per raceCancel call) so a long
+// poll doesn't accumulate thousands of derived `.then` promises on it.
+let _cancelSignal: Promise<typeof CANCELLED> = new Promise<typeof CANCELLED>(() => { /* until reset */ })
+
+/** Re-arm the cancel channel at the start of each generation. */
+function resetCancel(): void {
+ _genCancelRequested = false
+ _cancelSignal = new Promise<typeof CANCELLED>((resolve) => { _cancelNotify = () => resolve(CANCELLED) })
+}
+
+/**
+ * Race a long await against a user cancel. Returns the wrapped promise's value
+ * normally, or the CANCELLED sentinel the moment Stop is pressed — so a 15 s
+ * getHistory tick or a 90 s ComfyUI cold-start can't keep "stopping…" on screen.
+ */
+function raceCancel<T>(p: Promise<T>): Promise<T | typeof CANCELLED> {
+ if (_genCancelRequested) return Promise.resolve(CANCELLED)
+ return Promise.race([p, _cancelSignal])
+}
+
+export function requestGenerationCancel(): void {
+ _genCancelRequested = true
+ _cancelNotify?.() // wake every pending raceCancel immediately
+ void cancelGeneration() // /interrupt the running job (no-op mid model-load)
+ void clearComfyQueue() // drop anything still queued so it can't start next
+}
+
// Last image LU actually produced this session. Small models routinely pass a
// hallucinated filename (e.g. "locally_saved_image.png") to a follow-up
// video_generate; when the given name can't be resolved we fall back to this so
@@ -523,6 +577,9 @@ export async function vramHandoffGenerate(kind: 'image' | 'video', args: VramHan
}
async function runHandoff(kind: 'image' | 'video', args: VramHandoffArgs): Promise<string> {
+ // Fresh run — re-arm the cancel channel (clears any flag/notify left over from
+ // a previous cancelled gen).
+ resetCancel()
// Robustness for small local models (gemma4:e4b live): they frequently emit a
// snake_case `input_image` alias and sometimes omit `prompt` on a video call.
// Normalize the alias so the I2V path still finds the source image.
@@ -752,9 +809,16 @@ async function runHandoff(kind: 'image' | 'video', args: VramHandoffArgs): Promi
}
}
+ // Cancelled while freeing VRAM / waiting for eviction — bail before we even
+ // touch ComfyUI. The finally still restores the text model.
+ if (_genCancelRequested) return `${label(kind)} generation cancelled.`
+
// ── (c) GENERATE ───────────────────────────────────────────────
emitHandoff('loading_image_model', { kind, detail: targetModel })
const up = await ensureComfyRunning()
+ // ensureComfyRunning returns false on a cancel too — distinguish so Stop
+ // reads as "cancelled", not the misleading "ComfyUI did not start".
+ if (_genCancelRequested) return `${label(kind)} generation cancelled.`
if (!up) {
// Surface clearly; the finally block still restores the text model.
emitHandoff('error', { kind, detail: 'ComfyUI did not start' })
@@ -763,9 +827,21 @@ async function runHandoff(kind: 'image' | 'video', args: VramHandoffArgs): Promi
emitHandoff('generating', { kind, detail: targetModel })
- const result = kind === 'image'
- ? await generateImage(prompt, targetModel, args)
- : await generateVideo(prompt, targetModel, videoBackend, args)
+ // Race the WHOLE generation against the cancel signal — not just the poll
+ // loop. David 2026-06-16 (web build): "Stop" sat on "stopping…" forever
+ // because generateImage was stuck BEFORE the poll loop (fetchCaps /
+ // buildDynamicWorkflow — /object_info fetches that can hang through a web
+ // proxy), and the cancel flag was only checked inside pollAndExtract /
+ // ensureComfyRunning. Wrapping the entire generate call means Stop returns
+ // "cancelled" within ms from ANY phase (caps fetch, workflow build, image
+ // upload, submit, poll). The abandoned promise keeps running in the
+ // background but its output is ignored; requestGenerationCancel already
+ // fired /interrupt + queue-clear, and the finally restores the text model.
+ const genPromise = kind === 'image'
+ ? generateImage(prompt, targetModel, args)
+ : generateVideo(prompt, targetModel, videoBackend, args)
+ const result = await raceCancel(genPromise)
+ if (result === CANCELLED) return `${label(kind)} generation cancelled.`
return result
} finally {
// ── (d) HANDOFF-BACK — ALWAYS (success, failure, timeout) ──────
@@ -773,14 +849,44 @@ async function runHandoff(kind: 'image' | 'video', args: VramHandoffArgs): Promi
// best-effort reload the text model. The reload is non-fatal: if it throws,
// Ollama will lazy-load on the user's next message anyway.
emitHandoff('restoring_text', { kind, detail: evictedModel ?? evictedLms?.id ?? undefined })
- try {
- await freeMemory()
- } catch { /* best effort */ }
+ // David 2026-06-16 (bug C — RealVisXL "6 min+"): only force a ComfyUI VRAM
+ // unload when we ACTUALLY evicted a text model (it needs the room to reload)
+ // or the user cancelled (stop the burn). When nothing was evicted — the
+ // common image case, where the small chat model and the SDXL checkpoint
+ // co-exist — keep ComfyUI's checkpoint resident so the NEXT generation
+ // reuses it warm instead of paying the full cold reload every single time.
+ if (evictedModel || evictedLms || _genCancelRequested) {
+ try {
+ await freeMemory()
+ } catch { /* best effort */ }
+ }
if (evictedModel) {
try {
await loadModel(evictedModel)
} catch (e) {
- log.warn('vram_handoff.reload_failed', { textModel: evictedModel, err: String(e) })
+ // A heavy video model (e.g. wan2.2 5B on a 12 GB GPU) can leave ComfyUI
+ // holding a wedged CUDA context that blocks Ollama from re-initializing
+ // the text model: loadModel throws "CUDA error: shared object
+ // initialization failed" (David 2026-06-16, E2E). It is NOT an OOM — VRAM
+ // is already free — and it survives even an Ollama restart; the only thing
+ // that clears it is stopping ComfyUI's process to release its CUDA context.
+ // So on that failure class, stop ComfyUI and retry the reload ONCE, so the
+ // next chat turn finds the model loaded instead of a dead backend. Reactive
+ // by design: svd / lighter models never throw here, so they never pay the
+ // ComfyUI restart (the next generation lazily restarts it via ensureComfyRunning).
+ const msg = String(e instanceof Error ? e.message : e)
+ log.warn('vram_handoff.reload_failed', { textModel: evictedModel, err: msg })
+ if (/cuda|shared object|terminated|0xc0000409|llama[ -](?:runner|server)/i.test(msg)) {
+ try {
+ log.warn('vram_handoff.reload_cuda_wedge_recover', { textModel: evictedModel })
+ await backendCall('stop_comfyui')
+ await sleep(5000) // let the GPU/driver settle after ComfyUI releases the context
+ await loadModel(evictedModel)
+ log.info('vram_handoff.reload_cuda_wedge_recovered', { textModel: evictedModel })
+ } catch (e2) {
+ log.warn('vram_handoff.reload_retry_failed', { textModel: evictedModel, err: String(e2 instanceof Error ? e2.message : e2) })
+ }
+ }
}
}
if (evictedLms) {
@@ -1086,8 +1192,16 @@ async function generateVideo(
async function pollAndExtract(promptId: string, prompt: string, kindLabel: string, timeoutMs: number): Promise<string> {
const deadline = Date.now() + timeoutMs
while (Date.now() < deadline) {
- await sleep(1000)
- const history = await getHistory(promptId)
+ // User hit the in-chat cancel button — ComfyUI was already sent /interrupt
+ // + queue-clear by requestGenerationCancel(); stop polling so runHandoff's
+ // finally can restore the text model into VRAM instead of waiting out the
+ // timeout. RACE both the sleep AND the getHistory against the cancel signal
+ // (bug B): a cold checkpoint load makes getHistory block for up to its 15 s
+ // cap, so a between-ticks-only check kept "stopping…" on screen for seconds.
+ if (_genCancelRequested) return `${kindLabel} generation cancelled.`
+ if ((await raceCancel(sleep(1000))) === CANCELLED) return `${kindLabel} generation cancelled.`
+ const history = await raceCancel(getHistory(promptId))
+ if (history === CANCELLED) return `${kindLabel} generation cancelled.`
if (history?.status?.completed) {
const outputs = history.outputs ?? {}
for (const nodeId of Object.keys(outputs)) {
diff --git a/src/components/chat/MessageBubble.tsx b/src/components/chat/MessageBubble.tsx
index ff3b5196..f2d45448 100644
--- a/src/components/chat/MessageBubble.tsx
+++ b/src/components/chat/MessageBubble.tsx
@@ -49,9 +49,16 @@ export function MessageBubble({ message, onRegenerate, onEdit, pendingApprovalId
const activeModel = useModelStore((s) => s.activeModel)
const toggleAgentMode = useAgentModeStore((s) => s.toggleAgentMode)
const userAvatarDataUrl = useSettingsStore((s) => s.settings.userAvatarDataUrl)
+ // Chat Tools (v2.5.3) gives plain chat web/file/image/video WITHOUT Agent Mode.
+ // When it's on, the "turn Agent Mode on" banners below are wrong + contradictory
+ // (the tool IS available in normal chat) — they predate Chat Tools and only
+ // checked `!isAgentActive`. Suppress them when Chat Tools is enabled. David
+ // 2026-06-16: web build, Agent off + Chat Tools on, image_generate emitted →
+ // bubble showed "Turn Agent Mode on" even though the tool was already running.
+ const chatToolsEnabled = useSettingsStore((s) => s.settings.chatToolsEnabled !== false)
const suggestAgent = useMemo(() => {
- if (isUser || isAgentActive || !activeConversationId || !activeModel) return false
+ if (isUser || isAgentActive || chatToolsEnabled || !activeConversationId || !activeModel) return false
if (!message.content || message.content.length < 10) return false
// The repair helper extracts {name, arguments}-shaped JSON blocks, plus
// <tool_call>...</tool_call> Hermes tags. If anything came out, the
@@ -61,7 +68,7 @@ export function MessageBubble({ message, onRegenerate, onEdit, pendingApprovalId
// Only nudge when the model is on the agent-allow-list. Showing this
// banner on a non-agent-capable model would be a dead-end.
return isAgentCompatible(activeModel)
- }, [isUser, isAgentActive, activeConversationId, activeModel, message.content])
+ }, [isUser, isAgentActive, chatToolsEnabled, activeConversationId, activeModel, message.content])
// Thought-only completion (live find 2026-06-11): the model reasoned —
// usually about calling a tool it doesn't have in a non-agent chat — and
@@ -72,8 +79,8 @@ export function MessageBubble({ message, onRegenerate, onEdit, pendingApprovalId
const thoughtOnly = !isUser && !(message.content || '').trim() && !!(message.thinking || '').trim()
&& (!isLast || !!message.usage)
const thoughtOnlyToolIntent = useMemo(
- () => thoughtOnly && !isAgentActive && looksLikeToolIntent(message.thinking || ''),
- [thoughtOnly, isAgentActive, message.thinking],
+ () => thoughtOnly && !isAgentActive && !chatToolsEnabled && looksLikeToolIntent(message.thinking || ''),
+ [thoughtOnly, isAgentActive, chatToolsEnabled, message.thinking],
)
useEffect(() => {
diff --git a/src/components/chat/ToolCallBlock.tsx b/src/components/chat/ToolCallBlock.tsx
index e64737fa..239a7577 100644
--- a/src/components/chat/ToolCallBlock.tsx
+++ b/src/components/chat/ToolCallBlock.tsx
@@ -4,7 +4,9 @@ import { Search, Globe, FileText, FileEdit, Terminal, Image, Film, Loader2, Chec
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 { requestGenerationCancel } from '../../api/vram-handoff'
// F1 (konata3602 commitment 2026-05-23) + render fix (konata3602 bug 2026-06-07)
// — when image_generate / video_generate / screenshot produce a ComfyUI output,
@@ -111,6 +113,11 @@ export function ToolCallBlock({ toolCall, onApprove, onReject }: Props) {
const isRunning = toolCall.status === 'running'
const isPending = toolCall.status === 'pending_approval'
const isFailed = toolCall.status === 'failed' || toolCall.status === 'rejected'
+ // Real cancel (David 2026-06-16): only image/video generation supports a true
+ // abort (ComfyUI /interrupt + loop abort). Local "cancelling" state flips the
+ // mini button to a "stopping…" indicator the moment it's clicked.
+ const isGenTool = toolCall.toolName === 'image_generate' || toolCall.toolName === 'video_generate'
+ const [cancelling, setCancelling] = useState(false)
// Inline media preview URL (image_generate / video_generate / screenshot).
// Computed once; rendered ALWAYS-visible below the header (even while the
@@ -147,24 +154,50 @@ export function ToolCallBlock({ toolCall, onApprove, onReject }: Props) {
return (
<div className="mb-0.5">
{/* Header line — monochrome, only status icon has subtle color */}
- <button
- onClick={() => setOpen(!open)}
- className="flex items-center gap-1.5 py-0.5 text-left hover:opacity-80 transition-opacity w-full"
- >
- <ToolIcon size={10} className="text-gray-500 dark:text-gray-500 shrink-0" />
- <span className="text-[0.65rem] text-gray-600 dark:text-gray-400">{toolCall.toolName}</span>
- <StatusIcon size={9} className={`shrink-0 ${
- toolCall.status === 'completed' ? 'text-gray-400 dark:text-gray-500' :
- isFailed ? 'text-red-400/60' :
- isPending ? 'text-amber-400/60' :
- 'text-gray-500'
- } ${isRunning ? 'animate-spin' : ''}`} />
- {toolCall.duration != null && (
- <span className="text-[0.5rem] text-gray-500 dark:text-gray-600">
- {toolCall.duration < 1000 ? `${toolCall.duration}ms` : `${(toolCall.duration / 1000).toFixed(1)}s`}
- </span>
+ <div className="flex items-center gap-1">
+ <button
+ onClick={() => setOpen(!open)}
+ className="flex items-center gap-1.5 py-0.5 text-left hover:opacity-80 transition-opacity flex-1 min-w-0"
+ >
+ <ToolIcon size={10} className="text-gray-500 dark:text-gray-500 shrink-0" />
+ <span className="text-[0.65rem] text-gray-600 dark:text-gray-400">{toolCall.toolName}</span>
+ <StatusIcon size={9} className={`shrink-0 ${
+ toolCall.status === 'completed' ? 'text-gray-400 dark:text-gray-500' :
+ isFailed ? 'text-red-400/60' :
+ isPending ? 'text-amber-400/60' :
+ 'text-gray-500'
+ } ${isRunning ? 'animate-spin' : ''}`} />
+ {toolCall.duration != null && (
+ <span className="text-[0.5rem] text-gray-500 dark:text-gray-600">
+ {toolCall.duration < 1000 ? `${toolCall.duration}ms` : `${(toolCall.duration / 1000).toFixed(1)}s`}
+ </span>
+ )}
+ </button>
+ {/* Real abort (David 2026-06-16): stop a running image/video generation.
+ Fires ComfyUI /interrupt AND aborts the agent loop so it won't
+ auto-start a replacement. VRAM is restored by runHandoff's finally. */}
+ {isRunning && isGenTool && (
+ cancelling ? (
+ <span className="flex items-center gap-1 text-[0.55rem] text-gray-400 dark:text-gray-500 shrink-0 pr-1">
+ <Loader2 size={9} className="animate-spin" /> stopping…
+ </span>
+ ) : (
+ <button
+ onClick={(e) => {
+ e.stopPropagation()
+ setCancelling(true)
+ requestGenerationCancel()
+ const { generating, aborters } = useGenerationStore.getState()
+ Object.keys(generating).forEach((cid) => aborters[cid]?.())
+ }}
+ title="Stop generation"
+ className="flex items-center gap-1 px-1.5 py-0.5 rounded text-[0.55rem] font-medium text-red-700 dark:text-red-300 bg-red-500/10 hover:bg-red-500/15 border border-red-500/20 dark:border-red-500/25 transition-colors shrink-0"
+ >
+ <X size={10} /> Stop
+ </button>
+ )
)}
- </button>
+ </div>
{/* Model-Picker (v2.5.3) — LU's own pre-VRAM-swap model choice, shown
while the executor gate awaits the pick. Falls back to the mini
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index d228dfd9..9f2dc584 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -263,6 +263,31 @@ export function useAgentChat() {
}
}
+ // ── Re-entry guard (double-submit) ──────────────────────────────────
+ // An accidental double-send (two Enters before the React `isGenerating`
+ // prop flips Send → Stop) used to start a SECOND agent loop on this hook.
+ // Both loops share the streaming refs AND each keeps its OWN per-turn
+ // over-generation caps (maxImageGen/maxVideoGen), so each fired its own
+ // image/video tool — live repro: ONE prompt sent twice ran video_generate
+ // 4× (gemma4:e4b + SVD-XT, David 2026-06-16). Claim the lock synchronously
+ // HERE — strategy resolution above can await, the critical section (message
+ // add, ref reset, the loop) is all below — so the racing second call bails
+ // before duplicating anything. Released in the finally (runningRef=false).
+ if (runningRef.current) {
+ log.info('agent.duplicate_send_blocked', { activeModel })
+ return
+ }
+ runningRef.current = true
+ // Flip the INPUT gate true in the SAME synchronous beat as the ref (David
+ // 2026-06-16, bug A). The input shows Send vs Stop off `isAgentRunning`,
+ // which used to flip true only ~80 lines down — AFTER the RAG + memory-
+ // retrieval awaits. In that window runningRef was already true (so the guard
+ // silently dropped a resend) while the input still showed Send, so the first
+ // message right after a generation looked like it "didn't go through". Both
+ // signals now go true together here and false together in the finally; the
+ // only early return before the try (no conv) resets both.
+ setIsAgentRunning(true)
+
// Create or get conversation
let convId = store.activeConversationId
if (!convId) {
@@ -337,7 +362,7 @@ export function useAgentChat() {
// Build conversation context
const conv = useChatStore.getState().conversations.find((c) => c.id === convId)
- if (!conv) return
+ if (!conv) { runningRef.current = false; setIsAgentRunning(false); return }
// RAG context injection
// Per-chat persona toggle — default OFF. Only apply persona prompt
@@ -348,7 +373,10 @@ export function useAgentChat() {
const ragEnabled = ragState.ragEnabled[convId] ?? false
if (ragEnabled) {
- await ragState.loadChunksFromDB(convId)
+ // Guard the lock: a throw here (before the main try/finally below) would
+ // otherwise leave runningRef stuck true and wedge the chat (the re-entry
+ // guard set it above). Degrade gracefully to no RAG context on failure.
+ try { await ragState.loadChunksFromDB(convId) } catch (e) { log.error('RAG chunk load failed', { e }) }
const chunks = ragState.getConversationChunks(convId)
if (chunks.length > 0) {
try {
@@ -422,20 +450,25 @@ export function useAgentChat() {
}
// 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') {
- const { CAVEMAN_PROMPTS } = await import('../lib/constants')
- const cavemanPrompt = CAVEMAN_PROMPTS[settings.cavemanMode]
- if (cavemanPrompt) {
- agentSystemPrompt += `\n\nResponse style: ${cavemanPrompt}`
+ // This ensures the model understands its agent role first, then applies terse
+ // style. Wrapped so a failed dynamic import can't throw OUT of the setup
+ // region (which runs before the main try/finally) and leave runningRef +
+ // isAgentRunning stuck true — that would wedge the chat (bug A class).
+ let cavemanReminder = ''
+ try {
+ if (settings.cavemanMode && settings.cavemanMode !== 'off') {
+ const { CAVEMAN_PROMPTS, CAVEMAN_REMINDERS } = await import('../lib/constants')
+ const cavemanPrompt = CAVEMAN_PROMPTS[settings.cavemanMode]
+ if (cavemanPrompt) {
+ agentSystemPrompt += `\n\nResponse style: ${cavemanPrompt}`
+ }
+ // Per-message Caveman reminder for non-thinking models
+ cavemanReminder = CAVEMAN_REMINDERS?.[settings.cavemanMode as 'lite' | 'full' | 'ultra'] || ''
}
+ } catch (e) {
+ log.warn('agent.caveman_load_failed', { e: String(e) })
}
- // Per-message Caveman reminder for non-thinking models
- const cavemanReminder = (settings.cavemanMode && settings.cavemanMode !== 'off')
- ? (await import('../lib/constants')).CAVEMAN_REMINDERS?.[settings.cavemanMode as 'lite' | 'full' | 'ultra'] || ''
- : ''
-
// Build messages array
let agentMessages: ChatMessage[] = [
...(agentSystemPrompt ? [{ role: 'system' as const, content: agentSystemPrompt }] : []),
@@ -512,6 +545,12 @@ export function useAgentChat() {
const maxVideoGen = wantsVideo && videoAllowed ? 1 : 0
let imageGenDone = 0
let videoGenDone = 0
+ // Track whether the generated media was actually fed back to the model
+ // (vision feedback). When it wasn't — video is never fed back, and a
+ // text-only model can't see an image — we suppress the generic "your media
+ // is above" closing line so the finished tool call + inline media stands on
+ // its own with no hollow comment behind it (David 2026-06-16).
+ let visionFeedbackGiven = false
let mediaSteered = false
let mediaSynthesized = false
let forceNoThink = false
@@ -1203,6 +1242,7 @@ export function useAgentChat() {
const vf = await buildVisionFeedback(modelToUse, tc.function.name, result.result)
if (vf) {
agentMessages.push(vf as unknown as ChatMessage)
+ visionFeedbackGiven = true
log.info('agent.vision_feedback_attached', { tool: tc.function.name })
break // one image per batch is enough context
}
@@ -1237,11 +1277,18 @@ export function useAgentChat() {
// 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.'
+ // Only add a generic closing line when the model actually SAW the
+ // media (vision feedback was sent — image + vision-capable model).
+ // For video (never fed back) or a text-only model, contentRef stays
+ // empty: the bubble shows just the completed tool call with its inline
+ // image/video, no robotic "your video is above" (David 2026-06-16).
+ if (visionFeedbackGiven) {
+ 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[] = []
diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.ts
index c1b69550..faffd766 100644
--- a/src/stores/settingsStore.ts
+++ b/src/stores/settingsStore.ts
@@ -21,7 +21,12 @@ import { DEFAULT_SETTINGS, BUILT_IN_PERSONAS } from '../lib/constants'
// preferredVideoT2VModel / preferredVideoI2VModel (all default '' = "ask
// before the VRAM swap"). Same additive merge path — existing users simply
// see the picker on their next generation.
-const STORE_VERSION = 9
+// v10 (2026-06-16): one-time RESET of those three picker preferences. Video had
+// kept a silently-saved model and only offered "Change model"; David wants the
+// full picker to come FIRST again on both image AND video. Clearing the saved
+// picks once on upgrade makes the picker the default until the user deliberately
+// saves a model again via the picker's Remember.
+const STORE_VERSION = 10
interface SettingsState {
settings: Settings
@@ -92,10 +97,19 @@ export const useSettingsStore = create<SettingsState>()(
migrate: (persisted: any, version: number) => {
if (version < STORE_VERSION) {
const customPersonas = (persisted.personas || []).filter((p: Persona) => !p.isBuiltIn)
+ // Merge new default settings into existing (fills missing fields like thinkingEnabled)
+ const mergedSettings = { ...DEFAULT_SETTINGS, ...(persisted.settings || {}) }
+ // v10: clear the saved model-picker preferences ONCE so the picker is
+ // shown first again on image + video (David 2026-06-16). The additive
+ // merge above would otherwise preserve a previously-saved pick.
+ if (version < 10) {
+ mergedSettings.preferredImageModel = ''
+ mergedSettings.preferredVideoT2VModel = ''
+ mergedSettings.preferredVideoI2VModel = ''
+ }
return {
...persisted,
- // Merge new default settings into existing (fills missing fields like thinkingEnabled)
- settings: { ...DEFAULT_SETTINGS, ...(persisted.settings || {}) },
+ settings: mergedSettings,
personas: [...BUILT_IN_PERSONAS, ...customPersonas],
activePersonaId: persisted.activePersonaId || 'unrestricted',
_version: STORE_VERSION,
diff --git a/vite.config.ts b/vite.config.ts
index 7d62e6f0..9c886c8d 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -405,19 +405,31 @@ function comfyLauncher(): Plugin {
process.on('SIGINT', () => { stopComfy(); process.exit() })
process.on('SIGTERM', () => { stopComfy(); process.exit() })
- // API: ComfyUI POST proxy (workaround for Vite 8 blocking POST via proxy)
+ // API: ComfyUI POST proxy (workaround for Vite 8 blocking POST via proxy).
+ // David 2026-06-16 — konata's "Failed to upload image: HTTP 400" (web build
+ // via SSH-tunneled `npm run dev`) reproduced HERE: this proxy used to buffer
+ // the body as a STRING (`body += chunk` corrupts binary image bytes) and
+ // HARDCODE Content-Type: application/json (strips the multipart/form-data
+ // boundary). JSON POSTs (submit/history) survived; the I2V image upload
+ // (/upload/image, multipart) reached ComfyUI as garbage → 400. Fix: buffer
+ // the raw bytes intact and forward the REAL Content-Type (with its boundary)
+ // + Content-Length, so multipart uploads pass through unchanged.
server.middlewares.use('/comfyui', (req, res, next) => {
if (req.method !== 'POST') return next()
const targetPath = (req.url || '').replace(/^\/comfyui/, '') || '/'
- let body = ''
- req.on('data', (chunk: any) => { body += chunk })
+ const inChunks: Buffer[] = []
+ req.on('data', (chunk: Buffer) => { inChunks.push(chunk) })
req.on('end', () => {
+ const body = Buffer.concat(inChunks)
const proxyReq = http.request({
hostname: '127.0.0.1',
port: 8188,
path: targetPath,
method: 'POST',
- headers: { 'Content-Type': 'application/json' },
+ headers: {
+ 'Content-Type': (req.headers['content-type'] as string) || 'application/json',
+ 'Content-Length': body.length,
+ },
}, (proxyRes) => {
const chunks: Buffer[] = []
proxyRes.on('data', (c: Buffer) => chunks.push(c))