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): a generated image outlives the window it was made in
purple7f7a46ea8ffe
diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.tsindex dc684321..a2bf4968 100644--- a/src/api/mcp/builtin-tools.ts+++ b/src/api/mcp/builtin-tools.ts@@ -12,7 +12,8 @@ import { applyUniqueEdit } from '../../lib/surgical-edit'import { sliceFileReadResult } from '../../lib/file-read-window'import { writeTodos, summarizeTodos } from '../../stores/todoStore'import { isMlxImageHost, generateMlxImageDataUrl, listMlxImageModels, type MlxImageModel } from '../mlx-image'-import { getVideoStatus, listVideoModels, generateVideo as generateMlxVideo, getVideoProgress, cancelVideo, readVideoAsBlobUrl, type VideoModel } from '../mlx-video'+import { getVideoStatus, listVideoModels, generateVideo as generateMlxVideo, getVideoProgress, cancelVideo, type VideoModel } from '../mlx-video'+import { pathToFileUrl } from '../../lib/local-media-url'/*** Helper: current chat id (+ folder workspace) as a fragment to spread into@@ -1312,20 +1313,6 @@ function resolveMlxModel<T extends { id: string; name: string }>()}-/** Decode a `data:image/png;base64,...` result into a compact `blob:` URL —- * same b64 → Blob → createObjectURL pattern as readVideoAsBlobUrl- * (mlx-video.ts). Keeps the multi-hundred-KB PNG OUT of the tool-result- * string that gets fed back into the model's context; only the short- * blob: URL (which the CSP's img-src already allows) goes there. */-function pngDataUrlToObjectUrl(dataUrl: string): string {- const comma = dataUrl.indexOf(',')- const b64 = comma >= 0 ? dataUrl.slice(comma + 1) : dataUrl- const bin = atob(b64)- const bytes = new Uint8Array(bin.length)- for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)- return URL.createObjectURL(new Blob([bytes], { type: 'image/png' }))-}-function sleep(ms: number): Promise<void> {return new Promise((r) => setTimeout(r, ms))}@@ -1362,7 +1349,7 @@ async function executeImageGenerateMlx(prompt: string, merged: Record<string, an}try {- const { dataUrl } = await generateMlxImageDataUrl({+ const { dataUrl, localPath } = await generateMlxImageDataUrl({prompt,model: model.id,steps: typeof merged.steps === 'number' ? merged.steps : undefined,@@ -1371,9 +1358,20 @@ async function executeImageGenerateMlx(prompt: string, merged: Record<string, anheight: typeof merged.height === 'number' ? merged.height : undefined,negativePrompt: typeof merged.negativePrompt === 'string' ? merged.negativePrompt : undefined,})+ // B3: the result string is PERSISTED with the conversation, so what goes on+ // this line has to outlive the window. The Rust side already wrote the PNG+ // to disk before handing back the bytes, so the path is both stable and+ // free. A blob: URL here used to leak (never revoked) AND die on the next+ // launch, which quietly emptied every generated picture out of the history.+ if (localPath) {+ const filename = localPath.split(/[\\/]/).pop() || `mlx-${Date.now()}.png`+ return `Image generated: ${filename} (prompt: "${prompt}")\n${pathToFileUrl(localPath)}`+ }+ // No path means the disk write failed on the Rust side. The bytes are still+ // in hand, so show them rather than losing the render; a data: URL is+ // self-contained and revokes nothing, it is only bulky.const filename = `mlx-${Date.now()}.png`- const url = pngDataUrlToObjectUrl(dataUrl)- return `Image generated: ${filename} (prompt: "${prompt}")\n${url}`+ return `Image generated: ${filename} (prompt: "${prompt}")\n${dataUrl}`} catch (e) {return `Image generation failed: ${e instanceof Error ? e.message : String(e)}`}@@ -1455,13 +1453,12 @@ async function executeVideoGenerateMlx(prompt: string, merged: Record<string, anreturn `Video generation failed: ${e instanceof Error ? e.message : String(e)}`}if (prog.status === 'complete') {- try {- const blobUrl = await readVideoAsBlobUrl(job.output)- const filename = job.output.split(/[\\/]/).pop() || `mlx-${Date.now()}.mp4`- return `Video generated: ${filename} (prompt: "${prompt}")\n${blobUrl}`- } catch (e) {- return `Video generation failed: could not read output — ${e instanceof Error ? e.message : String(e)}`- }+ // Same rule as the image path: the file is already on disk, so the+ // result carries its path and the viewer rebuilds a blob on demand. The+ // old readVideoAsBlobUrl here pulled the whole clip into memory, never+ // released it, and left a dead URL behind after a restart.+ const filename = job.output.split(/[\\/]/).pop() || `mlx-${Date.now()}.mp4`+ return `Video generated: ${filename} (prompt: "${prompt}")\n${pathToFileUrl(job.output)}`}if (prog.status === 'error') {return `Video generation failed: ${prog.error || 'mlx-video failed'}`diff --git a/src/components/chat/ToolCallBlock.tsx b/src/components/chat/ToolCallBlock.tsxindex 7e309b81..6449c9b2 100644--- a/src/components/chat/ToolCallBlock.tsx+++ b/src/components/chat/ToolCallBlock.tsx@@ -1,4 +1,4 @@-import { useState, memo } from 'react'+import { useState, useEffect, memo } from 'react'import { motion, AnimatePresence } from 'framer-motion'import { Search, Globe, FileText, FileEdit, Terminal, Image, Film, Loader2, Check, X, Clock, AlertCircle, FolderOpen, Cpu, Monitor, GitBranch, GitCompare, GitCommitHorizontal, GitPullRequest, FlaskConical, History, Users, Database, Download } from 'lucide-react'import type { AgentToolCall } from '../../types/agent-mode'@@ -8,6 +8,7 @@ import { useGenerationStore } from '../../stores/generationStore'import { ModelPickerCard, ChangeModelInline, pickKindForToolCall } from './ModelPickerCard'import { DiffView } from './DiffView'import { requestGenerationCancel } from '../../api/vram-handoff'+import { fileUrlToPath, readLocalFileAsBlobUrl } from '../../lib/local-media-url'// F1 (konata3602 commitment 2026-05-23) + render fix (konata3602 bug 2026-06-07)// — when image_generate / video_generate / screenshot produce a ComfyUI output,@@ -75,16 +76,61 @@ export function comfyViewParams(url: string | null | undefined): { filename: str// Mac MLX media (hard rule: local image/video on Mac is MLX, never ComfyUI —// see api/mcp/builtin-tools.ts's executeImageGenerateMlx / executeVideoGenerateMlx).// There is no ComfyUI /view route for these, so the result carries a local-// `blob:` (or, defensively, `data:`) URL created in THIS webview session-// instead. Same F1 result shape as the ComfyUI path — `<kind> generated:-// <file> (prompt: "...")\n<url>` — just a different url scheme. Exported for-// unit testing.+// `file://` URL pointing at the render the Rust side already wrote to disk.+// Same F1 result shape as the ComfyUI path — `<kind> generated: <file>+// (prompt: "...")\n<url>` — just a different url scheme. Exported for unit+// testing.export function localMediaUrlFromResult(result: string | null | undefined): string | null {if (!result) return null- const m = result.match(/(blob:[^\s)\]]+|data:[a-z0-9.+-]+\/[a-z0-9.+-]+;base64,[^\s)\]]+)/i)+ // `file://` is the 2.6.3 form (B3): the result carries the PATH of a file the+ // app already wrote, so it still resolves after a restart. `blob:` only+ // appears in conversations recorded BEFORE that change, where it is already+ // dead; it stays matched so those messages can say so plainly.+ const m = result.match(/(file:\/\/[^\s)\]]+|blob:[^\s)\]]+|data:[a-z0-9.+-]+\/[a-z0-9.+-]+;base64,[^\s)\]]+)/i)return m ? m[1] : null}+/**+ * Resolve a `file://` result line into something an element can display.+ *+ * The blob is created when the block mounts and revoked when it unmounts, so a+ * long conversation full of generated images holds exactly the ones on screen+ * rather than every one ever produced. Anything that is not one of our file+ * URLs is handed straight back.+ */+function useDisplayableMediaUrl(url: string | null): { url: string | null; missing: boolean } {+ const path = url ? fileUrlToPath(url) : null+ // Nothing creates a blob: URL for a tool result any more, so one appearing in+ // a stored result necessarily came from an earlier session and its blob died+ // with that window. Saying so beats rendering a broken picture frame.+ const staleBlob = !!url && url.startsWith('blob:')+ const [resolved, setResolved] = useState<string | null>(null)+ const [missing, setMissing] = useState(false)++ useEffect(() => {+ if (!path) { setResolved(null); setMissing(false); return }+ let live = true+ let made: string | null = null+ setMissing(false)+ readLocalFileAsBlobUrl(path)+ .then((blobUrl) => {+ // Unmounted while reading: revoke immediately, nothing will show it.+ if (!live) { URL.revokeObjectURL(blobUrl); return }+ made = blobUrl+ setResolved(blobUrl)+ })+ .catch(() => { if (live) setMissing(true) })+ return () => {+ live = false+ if (made) URL.revokeObjectURL(made)+ }+ }, [path])++ if (staleBlob) return { url: null, missing: true }+ if (!path) return { url, missing: false }+ return { url: resolved, missing }+}+// Pull the "<file>" back out of the "<kind> generated: <file> (prompt: …"// prefix so the local-media Download button can suggest a real filename// (blob:/data: URLs carry no filename of their own, unlike a ComfyUI /view@@ -176,7 +222,10 @@ function ToolCallBlockImpl({ toolCall, onApprove, onReject }: Props) {// executeVideoGenerateMlx in api/mcp/builtin-tools.ts — no ComfyUI /view// route exists for those).const comfyPreviewUrl = comfyViewUrlFromResult(toolCall.result)- const localPreviewUrl = comfyPreviewUrl ? null : localMediaUrlFromResult(toolCall.result)+ const rawLocalUrl = comfyPreviewUrl ? null : localMediaUrlFromResult(toolCall.result)+ // B3: a `file://` line is read off disk here and released when this block+ // unmounts. Everything else passes through untouched.+ const { url: localPreviewUrl, missing: localMediaMissing } = useDisplayableMediaUrl(rawLocalUrl)const previewUrl = comfyPreviewUrl ?? localPreviewUrl// Model-Picker (v2.5.3): while a generation tool call is RUNNING and the@@ -209,7 +258,10 @@ function ToolCallBlockImpl({ toolCall, onApprove, onReject }: Props) {// A blob:/data: URL carries no `filename=` query param for isInlineVideoUrl// to key off, so fall back to the tool name — accurate since the MLX video// executor never produces an image result and vice versa.- const isVideoResult = !!localPreviewUrl+ // Keyed off the RAW result line, not the resolved one: a file:// URL takes a+ // moment to read off disk, and the kind of element to render must not depend+ // on whether that read has landed yet.+ const isVideoResult = !!rawLocalUrl? toolCall.toolName === 'video_generate': !!effectivePreviewUrl && isInlineVideoUrl(effectivePreviewUrl)@@ -285,6 +337,16 @@ function ToolCallBlockImpl({ toolCall, onApprove, onReject }: Props) {and no picture. A .mp4/.webm output renders in a <video>; everythingelse — including animated .webp — in an <img>. URL is bounded to OURComfyUI by comfyViewUrlFromResult (never auto-loads arbitrary URLs). */}+ {/* B3: the file behind this result is gone, or it was recorded as a+ session-scoped blob: URL before 2.6.3 and died with that window. An+ honest line beats a broken picture frame. */}+ {localMediaMissing && (+ <div className="pl-5 pt-0.5">+ <span className="text-[0.6rem] text-gray-500 dark:text-gray-500">+ This render is no longer on disk.+ </span>+ </div>+ )}{previewUrl && effectivePreviewUrl && (<div className="pl-5 pt-0.5 space-y-1">{isVideoResult ? (diff --git a/src/components/chat/__tests__/tool-media-lifetime.test.ts b/src/components/chat/__tests__/tool-media-lifetime.test.tsnew file mode 100644index 00000000..876a37e4--- /dev/null+++ b/src/components/chat/__tests__/tool-media-lifetime.test.ts@@ -0,0 +1,85 @@+/**+ * B3 (2.6.3): what goes into a persisted tool result, and how long a blob lives.+ *+ * The defect had two halves and one cause. `executeImageGenerateMlx` put a+ * `blob:` URL into the tool-result string; the chat store persists that string;+ * a blob URL only means anything inside the document that made it. So nothing+ * ever revoked the blob (every generated image stayed in memory for the life of+ * the window) AND the stored URL was dead after a restart (the picture silently+ * vanished from the conversation). An LRU cap would have addressed neither.+ *+ * The bytes were on disk the whole time. The Create gallery already relies on+ * that (restoreFromDisk in create/experimental/galleryUrl.ts); the chat path now+ * does too.+ *+ * There is no render harness in this repo, so the component half is guarded at+ * the source, like DownloadBadge-autoclose.test.ts.+ *+ * Run: npx vitest run src/components/chat/__tests__/tool-media-lifetime.test.ts+ */+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'++const SRC = resolve(__dirname, '..', '..', '..')+const read = (...p: string[]) => readFileSync(resolve(SRC, ...p), 'utf8')++const tools = read('api', 'mcp', 'builtin-tools.ts')+const block = read('components', 'chat', 'ToolCallBlock.tsx')++describe('nothing writes a session-scoped URL into a stored result', () => {+ it('the helper that minted them is gone', () => {+ expect(tools).not.toMatch(/pngDataUrlToObjectUrl/)+ })++ it('the tool executors create no object URLs at all', () => {+ // The one place this could regress is a well-meaning "just show it now"+ // fix. There is no legitimate createObjectURL in this file any more.+ expect(tools).not.toMatch(/createObjectURL/)+ })++ it('both MLX lanes put the file path in the result instead', () => {+ expect(tools).toMatch(/Image generated: \$\{filename\}.*\$\{pathToFileUrl\(localPath\)\}/s)+ expect(tools).toMatch(/Video generated: \$\{filename\}.*\$\{pathToFileUrl\(job\.output\)\}/s)+ })++ it('the video lane no longer pulls the whole clip into memory to show it', () => {+ // readVideoAsBlobUrl read the entire file just to build a URL that was+ // then stored. The Create tab still uses it, on its own recovery path.+ expect(tools).not.toMatch(/readVideoAsBlobUrl\(/)+ })+})++describe('the viewer owns the blob, so it can end', () => {+ it('revokes on unmount', () => {+ expect(block).toMatch(/URL\.revokeObjectURL\(made\)/)+ })++ it('revokes a read that landed after the block went away', () => {+ // Without this, unmounting mid-read leaks exactly the blob nobody will see.+ expect(block).toMatch(/if \(!live\) \{ URL\.revokeObjectURL\(blobUrl\); return \}/)+ })++ it('reads the file through the shared helper rather than a second copy', () => {+ expect(block).toMatch(/readLocalFileAsBlobUrl/)+ expect(block).toMatch(/from '\.\.\/\.\.\/lib\/local-media-url'/)+ })++ it('says so when the file is gone instead of showing a broken frame', () => {+ expect(block).toMatch(/setMissing\(true\)/)+ expect(block).toMatch(/no longer on disk/)+ })++ it('treats a blob: URL in a stored result as already dead', () => {+ // Nothing creates one any more, so any that appears was recorded by an+ // older build and its blob died with that window.+ expect(block).toMatch(/const staleBlob = !!url && url\.startsWith\('blob:'\)/)+ expect(block).toMatch(/if \(staleBlob\) return \{ url: null, missing: true \}/)+ })++ it('picks the element kind from the raw result, not the resolved URL', () => {+ // Reading off disk is async; keying the video/image decision on the+ // resolved URL would render the wrong element for the first frame.+ expect(block).toMatch(/const isVideoResult = !!rawLocalUrl/)+ })+})diff --git a/src/lib/__tests__/local-media-url.test.ts b/src/lib/__tests__/local-media-url.test.tsnew file mode 100644index 00000000..1c625d88--- /dev/null+++ b/src/lib/__tests__/local-media-url.test.ts@@ -0,0 +1,99 @@+/**+ * B3 (2.6.3): a blob: URL must never be written into something that is stored.+ *+ * The Mac MLX tool results used to embed one straight into the tool-result+ * string, which the chat store persists. A blob URL is scoped to the document+ * that created it, so that single decision produced two defects at once:+ *+ * 1. nothing ever revoked it, so every image generated in a session stayed+ * in memory for the life of the window+ * 2. after a restart the persisted URL pointed at nothing, so the picture+ * silently disappeared from the conversation+ *+ * The bytes were already on disk the whole time (the Rust side writes the PNG+ * before returning), which is what makes the path form both correct and free.+ *+ * Run: npx vitest run src/lib/__tests__/local-media-url.test.ts+ */+import { describe, it, expect, vi, beforeEach } from 'vitest'++const backendCall = vi.fn()+vi.mock('../../api/backend', () => ({+ backendCall: (...args: any[]) => backendCall(...args),+}))++const { pathToFileUrl, fileUrlToPath, guessMimeFromName, readLocalFileAsBlobUrl } =+ await import('../local-media-url')++beforeEach(() => backendCall.mockReset())++describe('path round-trip', () => {+ it('survives a plain path', () => {+ const p = '/Users/purple/Library/Application Support/lu/mlx/mlx-1.png'+ expect(fileUrlToPath(pathToFileUrl(p))).toBe(p)+ })++ it('survives spaces, which every Mac data directory has', () => {+ // "Application Support" is the reason this cannot be raw string concat.+ const p = '/Users/a b/Application Support/mlx-2.png'+ const url = pathToFileUrl(p)+ expect(url).not.toMatch(/ /)+ expect(fileUrlToPath(url)).toBe(p)+ })++ it('survives a hash and other characters a filename can carry', () => {+ const p = '/tmp/render #3 (final).png'+ expect(fileUrlToPath(pathToFileUrl(p))).toBe(p)+ })++ it('is a real URL, so a result-line regex can find it', () => {+ const url = pathToFileUrl('/tmp/a.png')+ expect(url.startsWith('file://')).toBe(true)+ // The same shape the tool result puts on its own line.+ const line = `Image generated: a.png (prompt: "x")\n${url}`+ const m = line.match(/(file:\/\/[^\s)\]]+)/)+ expect(m?.[1]).toBe(url)+ })++ it('returns null for anything that is not one of ours', () => {+ expect(fileUrlToPath('blob:http://localhost/abc')).toBeNull()+ expect(fileUrlToPath('http://localhost:8188/view?filename=a.png')).toBeNull()+ expect(fileUrlToPath('data:image/png;base64,AAA')).toBeNull()+ })+})++describe('guessMimeFromName', () => {+ it('knows the formats both generation lanes produce', () => {+ expect(guessMimeFromName('a.png')).toBe('image/png')+ expect(guessMimeFromName('a.mp4')).toBe('video/mp4')+ expect(guessMimeFromName('a.webm')).toBe('video/webm')+ expect(guessMimeFromName('A.WEBP')).toBe('image/webp')+ expect(guessMimeFromName('a.jpeg')).toBe('image/jpeg')+ })++ it('falls back to png rather than guessing nothing', () => {+ expect(guessMimeFromName('noextension')).toBe('image/png')+ })+})++describe('readLocalFileAsBlobUrl', () => {+ it('reads through the guarded Rust command and types the blob by extension', async () => {+ backendCall.mockResolvedValue(btoa('fake-bytes'))+ const created: { type: string }[] = []+ const origCreate = URL.createObjectURL+ ;(URL as any).createObjectURL = (b: Blob) => { created.push({ type: b.type }); return 'blob:made' }+ try {+ const url = await readLocalFileAsBlobUrl('/tmp/clip.mp4')+ expect(backendCall).toHaveBeenCalledWith('read_media_file', { path: '/tmp/clip.mp4' })+ expect(url).toBe('blob:made')+ expect(created[0].type).toBe('video/mp4')+ } finally {+ ;(URL as any).createObjectURL = origCreate+ }+ })++ // A read that fails is left to propagate rather than swallowed, so the+ // caller can render the "no longer on disk" state. That the caller actually+ // does is asserted in ToolCallBlock's own guard, where the catch lives; a+ // unit assertion here only ever proved that a mock rejects.+})diff --git a/src/lib/local-media-url.ts b/src/lib/local-media-url.tsnew file mode 100644index 00000000..f8d4a8ce--- /dev/null+++ b/src/lib/local-media-url.ts@@ -0,0 +1,62 @@+/**+ * Turning a file this app wrote into something an <img> or <video> can show.+ *+ * B3 (2.6.3). The Mac MLX tool results used to embed a `blob:` URL straight+ * into the tool-result string. That string is PERSISTED with the conversation,+ * and a blob URL is scoped to the document that created it, so it broke in two+ * ways at once: the blob was never revoked, so every generated image stayed in+ * memory for the life of the window, and after a restart the persisted URL+ * pointed at nothing, so the picture silently vanished from the history.+ *+ * The Create gallery already solved this (see recoverGalleryUrl /+ * restoreFromDisk in components/create/experimental/galleryUrl.ts): keep the+ * PATH, which is stable, and rebuild a blob on demand. The bytes are already on+ * disk in both cases, written by the Rust side before the result is built, so+ * nothing has to be re-generated.+ */++import { backendCall } from '../api/backend'++/** `file://` is what marks a result line as OUR file rather than a ComfyUI URL. */+const FILE_URL_PREFIX = 'file://'++/** Wrap an absolute path so it survives in a result string as a real URL. */+export function pathToFileUrl(path: string): string {+ return FILE_URL_PREFIX + encodeURI(path.replace(/\\/g, '/'))+}++/** The path back out, or null when this is not one of ours. */+export function fileUrlToPath(url: string): string | null {+ if (!url.startsWith(FILE_URL_PREFIX)) return null+ try {+ return decodeURI(url.slice(FILE_URL_PREFIX.length))+ } catch {+ return null+ }+}++export function guessMimeFromName(filename: string): string {+ const ext = filename.toLowerCase().split('.').pop() || ''+ if (ext === 'mp4') return 'video/mp4'+ if (ext === 'webm') return 'video/webm'+ if (ext === 'gif') return 'image/gif'+ if (ext === 'webp') return 'image/webp'+ if (ext === 'jpg' || ext === 'jpeg') return 'image/jpeg'+ return 'image/png'+}++/**+ * Read a file this app wrote and hand back a fresh `blob:` URL for it.+ *+ * The caller owns the URL and MUST revoke it when the element goes away. That+ * is the whole difference from the old code: the blob's lifetime is now tied to+ * something that ends, instead of to a string that is stored forever.+ */+export async function readLocalFileAsBlobUrl(path: string): Promise<string> {+ const b64 = await backendCall<string>('read_media_file', { path })+ const binary = atob(b64)+ const bytes = new Uint8Array(binary.length)+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)+ const name = path.split(/[\\/]/).pop() || ''+ return URL.createObjectURL(new Blob([bytes], { type: guessMimeFromName(name) }))+}