The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(chat): stop treating a failed image as a delivered one (D#81)
purple1c0a557a01e2
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex 6ba8afd8..c233b5dc 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -22,6 +22,8 @@ import { isMultimodalUnsupportedError, MULTIMODAL_UNSUPPORTED_MESSAGE } from '..import { log } from '../lib/logger'import { buildHermesToolPrompt, buildHermesToolResult, parseHermesToolCalls, stripToolCallTags, hasToolCallTags } from '../api/hermes-tool-calling'import { parseLooseToolCalls, stripMatchedCalls, stripToolCallText, canonicalToolName } from '../lib/loose-tool-parse'+import { mediaCallSucceeded } from '../lib/media-result'+import { summarizeTurn } from '../lib/turn-summary'import { buildVisionFeedback } from '../api/vision-feedback'import { compactMessages, getModelMaxTokens, estimateTokens } from '../lib/context-compaction'import { getModelContextCached } from '../api/ollama'@@ -1177,25 +1179,37 @@ export function useAgentChat() {// (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') {+ // D#81 (TheRealNovelist, 2026-07-21): a ComfyUI 400/500 does not reject+ // — the media tools RETURN their error as a normal result string, so+ // status is 'completed' and every consumer below used to treat a failed+ // generation as a delivered one. Reclassify it once, here, and the cap,+ // the label, the memory write and the "is now displayed" note all+ // follow. Non-media tools are unaffected.+ const mediaOk = mediaCallSucceeded(entry.ac.toolName, entry.ac.result)+ if (!mediaOk) entry.ac.status = 'failed'+ if ((result.status === 'completed' || result.status === 'cached') && mediaOk) {if (entry.ac.toolName === 'image_generate') imageGenDone++else if (entry.ac.toolName === 'video_generate') videoGenDone++}const contentLabel =- result.status === 'completed'- ? `Completed: ${entry.ac.toolName}`- : result.status === 'cached'- ? `Cached: ${entry.ac.toolName}`- : result.status === 'rejected'- ? `Rejected: ${entry.ac.toolName}`- : `Failed: ${entry.ac.toolName}`+ !mediaOk+ ? `Failed: ${entry.ac.toolName}`+ : result.status === 'completed'+ ? `Completed: ${entry.ac.toolName}`+ : result.status === 'cached'+ ? `Cached: ${entry.ac.toolName}`+ : result.status === 'rejected'+ ? `Rejected: ${entry.ac.toolName}`+ : `Failed: ${entry.ac.toolName}`updateBlockById(convId!, assistantMessage.id, entry.blockId, {toolCall: { ...entry.ac },toolCalls: [{ ...entry.ac }],content: contentLabel,})- if ((result.status === 'completed' || result.status === 'cached') && entry.ac.result) {+ // `mediaOk` guard: without it a ComfyUI error text was written into the+ // PERSISTENT cross-conversation memory store as a 'reference' fact.+ if ((result.status === 'completed' || result.status === 'cached') && entry.ac.result && mediaOk) {const argsShort = JSON.stringify(entry.ac.args).substring(0, 100)const resultShort = entry.ac.result.substring(0, 200)useMemoryStore.getState().addMemory({@@ -1236,6 +1250,10 @@ export function useAgentChat() {// 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 => {+ // Never claim the media is on screen when the generation failed (D#81)+ // — that injected sentence is what made the model cheerfully announce+ // an image the user never got.+ if (!mediaCallSucceeded(name, r.result)) return ''if ((r.status === 'completed' || r.status === 'cached') &&(name === 'image_generate' || name === 'video_generate')) {const kind = name === 'video_generate' ? 'video' : 'image'@@ -1331,41 +1349,21 @@ export function useAgentChat() {// from the actually-completed blocks so there is always a final// answer at the bottom of the bubble.if (!contentRef.current.trim()) {- const blocks = blocksRef.current- const completedTools = blocks.filter(- (b) => b.phase === 'tool_call' && b.toolCall?.status === 'completed'- )- const failedTools = blocks.filter(- (b) => b.phase === 'tool_call' && b.toolCall?.status === 'failed'- )- const writes = completedTools.filter((b) => b.toolCall?.toolName === 'file_write').length- const reads = completedTools.filter((b) => b.toolCall?.toolName === 'file_read').length- // 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) {- // 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[] = []- 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."- }+ // Closing line when the model said nothing itself. Pure logic lives in+ // summarizeTurn so the D#81 rules (a failed picture is not a completed+ // task, and its reason gets shown) are locked by tests.+ contentRef.current = summarizeTurn({+ calls: blocksRef.current+ .filter((b) => b.phase === 'tool_call' && b.toolCall)+ .map((b) => ({+ toolName: b.toolCall!.toolName,+ status: b.toolCall!.status,+ result: b.toolCall!.result,+ })),+ imageGenDone,+ videoGenDone,+ visionFeedbackGiven,+ })}// Final store updatediff --git a/src/lib/__tests__/media-result.test.ts b/src/lib/__tests__/media-result.test.tsnew file mode 100644index 00000000..0b77815f--- /dev/null+++ b/src/lib/__tests__/media-result.test.ts@@ -0,0 +1,83 @@+import { describe, it, expect } from 'vitest'+import { isMediaFailureResult, isMediaTool, mediaCallSucceeded } from '../media-result'++// D#81 (TheRealNovelist, 2026-07-21): "sometimes when I requested an image, it+// bugs out and not send an image, and it change the entire context for the chat+// … after image make an 400 or 500 error code."+//+// Root cause: the media tools never reject. Every failure comes back as a+// RESOLVED result string, so the tool call is 'completed' and the chat layer+// counted it as a delivered image, wrote the error into long-term memory, and+// injected "(The image is now displayed to the user…)" into the model's context.+// These lock the classifier that stops all four.++describe('media-result — failed generations must not pass as delivered media', () => {+ // Exact strings emitted by src/api/vram-handoff.ts + src/api/mcp/tool-registry.ts+ const REAL_FAILURES = [+ 'Image generation failed: ComfyUI rejected workflow: 400 Bad Request',+ 'Video generation failed: CUDA out of memory',+ 'Cannot generate: wan2.1 supports at most 81 frames (you requested 200).',+ 'Error: fetch failed',+ 'Image generation completed but no output produced.',+ 'Video generation timed out after 10 minutes.',+ ]++ const REAL_SUCCESSES = [+ 'Generated image: http://localhost:8188/view?filename=LU_00012_.png&type=output',+ 'Generated video: /comfyui/view?filename=LU_00003_.mp4&type=output',+ 'Saved to /view?filename=out.webp&type=output',+ ]++ describe('isMediaFailureResult', () => {+ for (const text of REAL_FAILURES) {+ it(`flags: ${text.slice(0, 46)}`, () => {+ expect(isMediaFailureResult(text)).toBe(true)+ })+ }++ for (const text of REAL_SUCCESSES) {+ it(`passes: ${text.slice(0, 46)}`, () => {+ expect(isMediaFailureResult(text)).toBe(false)+ })+ }++ it('treats a missing result as not-delivered', () => {+ expect(isMediaFailureResult(undefined)).toBe(true)+ expect(isMediaFailureResult(null)).toBe(true)+ expect(isMediaFailureResult('')).toBe(true)+ })++ it('does not trip on prose that merely mentions failure', () => {+ // Conservative by design: only our own failure shapes count, so an unknown+ // success format is never misread as an error.+ expect(isMediaFailureResult('Generated image of a failed rocket launch: /view?filename=a.png')).toBe(false)+ })+ })++ describe('isMediaTool', () => {+ it('covers exactly the two generating tools', () => {+ expect(isMediaTool('image_generate')).toBe(true)+ expect(isMediaTool('video_generate')).toBe(true)+ expect(isMediaTool('file_read')).toBe(false)+ expect(isMediaTool('screenshot')).toBe(false)+ })+ })++ describe('mediaCallSucceeded', () => {+ it('THE FIX: a ComfyUI 400 no longer counts as a delivered image', () => {+ expect(mediaCallSucceeded('image_generate', REAL_FAILURES[0])).toBe(false)+ })++ it('a real generation still counts as delivered', () => {+ expect(mediaCallSucceeded('image_generate', REAL_SUCCESSES[0])).toBe(true)+ expect(mediaCallSucceeded('video_generate', REAL_SUCCESSES[1])).toBe(true)+ })++ it('never reclassifies a non-media tool, whatever its result says', () => {+ // A grep hit containing the word "Error:" must stay a completed file_search.+ expect(mediaCallSucceeded('file_search', 'Error: not found')).toBe(true)+ expect(mediaCallSucceeded('shell_execute', 'Cannot generate: whatever')).toBe(true)+ expect(mediaCallSucceeded('file_read', '')).toBe(true)+ })+ })+})diff --git a/src/lib/__tests__/turn-summary.test.ts b/src/lib/__tests__/turn-summary.test.tsnew file mode 100644index 00000000..522874d9--- /dev/null+++ b/src/lib/__tests__/turn-summary.test.ts@@ -0,0 +1,119 @@+import { describe, it, expect } from 'vitest'+import { summarizeTurn, type TurnToolCall } from '../turn-summary'++// D#81, second half. The first half stopped a failed generation from counting+// as a delivered one. This half is about what the user then reads. The model+// usually says nothing after calling image_generate, so this text IS the reply.++const failedImage = (result: string): TurnToolCall => ({+ toolName: 'image_generate',+ status: 'failed',+ result,+})++describe('summarizeTurn', () => {+ describe('a failed picture', () => {+ it('THE FIX: says what went wrong instead of "Task completed: 1 failed."', () => {+ const text = summarizeTurn({+ calls: [failedImage('Image generation failed: ComfyUI rejected workflow: 400 Bad Request')],+ imageGenDone: 0,+ videoGenDone: 0,+ visionFeedbackGiven: false,+ })+ expect(text).toContain('400 Bad Request')+ expect(text).not.toContain('Task completed')+ })++ it('never calls a turn completed when nothing completed', () => {+ const text = summarizeTurn({+ calls: [failedImage('Error: fetch failed')],+ imageGenDone: 0, videoGenDone: 0, visionFeedbackGiven: false,+ })+ expect(text.toLowerCase()).not.toContain('completed')+ })++ it('tells the user how to retry', () => {+ const text = summarizeTurn({+ calls: [failedImage('Cannot generate: wan2.1 supports at most 81 frames (you requested 200).')],+ imageGenDone: 0, videoGenDone: 0, visionFeedbackGiven: false,+ })+ expect(text).toContain('again')+ })++ it('names video when the video tool is the one that failed', () => {+ const text = summarizeTurn({+ calls: [{ toolName: 'video_generate', status: 'failed', result: 'Video generation timed out after 10 minutes.' }],+ imageGenDone: 0, videoGenDone: 0, visionFeedbackGiven: false,+ })+ expect(text).toContain('video')+ expect(text).toContain('timed out')+ })++ it('still says something useful when no reason came back', () => {+ const text = summarizeTurn({+ calls: [{ toolName: 'image_generate', status: 'failed', result: '' }],+ imageGenDone: 0, videoGenDone: 0, visionFeedbackGiven: false,+ })+ expect(text).toContain('ComfyUI')+ expect(text).not.toContain('undefined')+ })+ })++ describe('a picture that landed', () => {+ it('stays silent unless the model actually saw it', () => {+ const call: TurnToolCall = { toolName: 'image_generate', status: 'completed', result: '/view?filename=a.png' }+ expect(summarizeTurn({ calls: [call], imageGenDone: 1, videoGenDone: 0, visionFeedbackGiven: false })).toBe('')+ expect(summarizeTurn({ calls: [call], imageGenDone: 1, videoGenDone: 0, visionFeedbackGiven: true })).toContain('Bild')+ })++ it('mentions both when an image and a clip landed', () => {+ const text = summarizeTurn({+ calls: [], imageGenDone: 1, videoGenDone: 1, visionFeedbackGiven: true,+ })+ expect(text).toContain('Bild')+ expect(text).toContain('Video')+ })+ })++ describe('ordinary tool turns are unchanged', () => {+ it('counts writes and reads', () => {+ const text = summarizeTurn({+ calls: [+ { toolName: 'file_write', status: 'completed' },+ { toolName: 'file_read', status: 'completed' },+ { toolName: 'file_read', status: 'completed' },+ ],+ imageGenDone: 0, videoGenDone: 0, visionFeedbackGiven: false,+ })+ expect(text).toBe('Task completed: 1 file written, 2 files read.')+ })++ it('a partial run says partly done, not completed', () => {+ const text = summarizeTurn({+ calls: [+ { toolName: 'file_write', status: 'completed' },+ { toolName: 'shell_execute', status: 'failed', result: 'Error: exit 1' },+ ],+ imageGenDone: 0, videoGenDone: 0, visionFeedbackGiven: false,+ })+ expect(text).toContain('partly done')+ expect(text).toContain('1 step failed')+ })++ it('a non-media failure does not borrow the picture wording', () => {+ const text = summarizeTurn({+ calls: [{ toolName: 'web_search', status: 'failed', result: 'Error: fetch failed' }],+ imageGenDone: 0, videoGenDone: 0, visionFeedbackGiven: false,+ })+ expect(text).not.toContain('did not come out')+ expect(text).toContain('1 step failed')+ })++ it('falls back to the rephrase hint when nothing ran at all', () => {+ const text = summarizeTurn({+ calls: [], imageGenDone: 0, videoGenDone: 0, visionFeedbackGiven: false,+ })+ expect(text).toContain('rephrase')+ })+ })+})diff --git a/src/lib/media-result.ts b/src/lib/media-result.tsnew file mode 100644index 00000000..e9d2a9d1--- /dev/null+++ b/src/lib/media-result.ts@@ -0,0 +1,51 @@+// Did an image_generate / video_generate tool call actually produce media?+//+// The media tools never REJECT. Every failure path in vram-handoff.ts returns a+// human-readable string instead of throwing, and tool-registry.execute() turns+// even a real throw into a returned `Error: …` string. So the promise resolves,+// executeParallel records status 'completed', and the chat layer treats a+// ComfyUI 400/500 exactly like a delivered picture:+//+// - it counts against the per-turn media cap, so the model cannot retry+// - the block renders "Completed: image_generate" with a check mark+// - the failure text is written into long-term memory as a 'reference'+// - the model is told "(The image is now displayed to the user…)"+//+// That last one is the damaging part: the model reads an injected claim that the+// image exists, right next to the error saying it does not, and usually believes+// the injection. TheRealNovelist (D#81, 2026-07-21) saw exactly this — "it bugs+// out and not send an image, and it change the entire context for the chat …+// after image make an 400 or 500 error code".+//+// Deliberately conservative: this returns true only for failure shapes we+// actually emit. Anything unrecognised counts as success, so a media backend+// that returns some other success format is never misread as broken. The+// alternative (require a ComfyUI /view URL as proof) is stricter but would break+// any non-ComfyUI lane the moment one is added.++/** Failure strings produced by the media path. Verified against vram-handoff.ts+ * (`Cannot generate:`, `… generation failed:`, `… completed but no output+ * produced.`, `… timed out after N minutes.`) and tool-registry.ts (`Error:`). */+const MEDIA_FAILURE_RE =+ /^\s*(Error:|Cannot generate:)|generation failed:|generation timed out|completed but no output produced/i++/** True when a media tool result is a failure disguised as a completed call. */+export function isMediaFailureResult(result: string | null | undefined): boolean {+ if (!result) return true // no result at all is not a delivered image either+ return MEDIA_FAILURE_RE.test(result)+}++/** True when this tool name is one whose result carries generated media. */+export function isMediaTool(toolName: string): boolean {+ return toolName === 'image_generate' || toolName === 'video_generate'+}++/**+ * Did this tool call really deliver media? Non-media tools are passed through+ * unchanged (their own status is authoritative), so callers can use this as a+ * single gate without special-casing.+ */+export function mediaCallSucceeded(toolName: string, result: string | null | undefined): boolean {+ if (!isMediaTool(toolName)) return true+ return !isMediaFailureResult(result)+}diff --git a/src/lib/turn-summary.ts b/src/lib/turn-summary.tsnew file mode 100644index 00000000..bbf4dade--- /dev/null+++ b/src/lib/turn-summary.ts@@ -0,0 +1,82 @@+// The closing line an agent turn shows when the model itself said nothing.+//+// That is not a rare corner: a model very often calls image_generate and stops,+// leaving this function to write the entire visible reply. Which is why the old+// version mattered so much. It counted tool calls into "Task completed: 1+// failed." and dropped the reason on the floor, so a user whose ComfyUI+// returned a 400 saw a green sounding sentence, a block labelled "Failed:+// image_generate", and nothing at all about what went wrong. TheRealNovelist+// read that as the app losing the picture and scrambling the chat (D#81).+//+// Rules encoded here:+// - a failed picture is never a completed task+// - when a picture fails, the reason we already have gets shown+// - a partial run says partial, not completed++import { isMediaTool } from './media-result'++export interface TurnToolCall {+ toolName: string+ status?: string+ result?: string | null+}++export interface TurnSummaryInput {+ calls: TurnToolCall[]+ /** Media that really landed this turn, already validated by the caller. */+ imageGenDone: number+ videoGenDone: number+ /** True only when an image was fed back to a vision-capable model. */+ visionFeedbackGiven: boolean+}++const NOTHING_AT_ALL =+ "I couldn't produce a response for that. Please rephrase, or turn off Think and send again."++/**+ * Returns the text to show, or '' to leave the bubble empty (the tool block+ * already carries the picture, so a robotic "your video is above" only adds+ * noise · David 2026-06-16).+ */+export function summarizeTurn(input: TurnSummaryInput): string {+ const { calls, imageGenDone, videoGenDone, visionFeedbackGiven } = input+ const completed = calls.filter((c) => c.status === 'completed')+ const failed = calls.filter((c) => c.status === 'failed')++ if (imageGenDone > 0 || videoGenDone > 0) {+ if (!visionFeedbackGiven) return ''+ if (imageGenDone > 0 && videoGenDone > 0) {+ return 'Fertig, dein Bild und dein Video sind oben. / Done, your image and video are above.'+ }+ return videoGenDone > 0+ ? 'Fertig, dein Video ist oben. / Done, your video is above.'+ : 'Fertig, dein Bild ist oben. / Done, your image is above.'+ }++ // Nothing landed. If a picture or clip was attempted and failed, that is the+ // headline, and the tool already told us why.+ const failedMedia = failed.filter((c) => isMediaTool(c.toolName))+ if (failedMedia.length) {+ const kind = failedMedia.some((c) => c.toolName === 'video_generate') ? 'video' : 'image'+ const why = (failedMedia[0].result ?? '').trim()+ return why+ ? `That ${kind} did not come out: ${why}\n\nSay "again" to retry, or change the prompt or model and send it once more.`+ : `That ${kind} did not come out and no reason came back. Check that ComfyUI is still running, then try again.`+ }++ const writes = completed.filter((c) => c.toolName === 'file_write').length+ const reads = completed.filter((c) => c.toolName === 'file_read').length+ const otherOk = completed.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`)++ const failedNote = `${failed.length} step${failed.length === 1 ? '' : 's'} failed`+ if (parts.length) {+ return failed.length+ ? `Task partly done: ${parts.join(', ')}. ${failedNote}.`+ : `Task completed: ${parts.join(', ')}.`+ }+ return failed.length ? `That did not work out. ${failedNote}, nothing else ran.` : NOTHING_AT_ALL+}