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(mac): local renders survive a restart instead of turning into dead tiles
purple5e1087551d8f
diff --git a/src-tauri/src/commands/media_cmds.rs b/src-tauri/src/commands/media_cmds.rsindex 20ba938c..32d15e49 100644--- a/src-tauri/src/commands/media_cmds.rs+++ b/src-tauri/src/commands/media_cmds.rs@@ -142,7 +142,14 @@ pub fn video_cancel(state: State<'_, AppState>, args: Value) -> Result<Value, St/// output today (MLX images are never written to disk — see above); add/// more roots here if a future in-process media backend gains one.fn allowed_media_roots() -> Vec<PathBuf> {- vec![crate::commands::video::outputs_root()]+ vec![+ crate::commands::video::outputs_root(),+ // Stills from the MLX image lane. They land on disk so the gallery+ // survives a restart — the in-memory data URL does not (createStore's+ // partialize strips it), and without a file there was nothing left to+ // re-read.+ crate::commands::mlx::images_root(),+ ]}/// Read a file from one of the app's own media output directories anddiff --git a/src-tauri/src/commands/mlx.rs b/src-tauri/src/commands/mlx.rsindex 9580a5c9..87948f2b 100644--- a/src-tauri/src/commands/mlx.rs+++ b/src-tauri/src/commands/mlx.rs@@ -666,13 +666,63 @@ pub async fn mlx_generate(_state: &AppState, args: &Value) -> CmdResult {let text = res.text().await.unwrap_or_default();return Err(crate::commands::internal(format!("HTTP {s}: {text}")));}- let payload: Value = res+ let mut payload: Value = res.json().await.map_err(|e| crate::commands::internal(e.to_string()))?;++ // Also put the PNG on disk and hand back its path.+ //+ // The base64 alone is not enough to build a gallery: createStore's+ // partialize strips `dataUrl` (megabytes of base64 would blow the+ // localStorage quota), so after a restart a Mac-generated image had+ // nothing left to display and the gallery fell through to a ComfyUI+ // /view URL that can never resolve here. A file under the app's own+ // media root can be re-read through read_media_file, exactly like the+ // MLX video lane already does with its mp4.+ //+ // Best effort on purpose: a full disk must not fail a render the user+ // is looking at. They lose durability, not the image.+ if let Some(b64) = payload.get("image_base64").and_then(|v| v.as_str()) {+ match write_generated_png(b64) {+ Ok(path) => {+ if let Some(obj) = payload.as_object_mut() {+ obj.insert("output".into(), json!(path.to_string_lossy()));+ }+ }+ Err(e) => println!("[MLX] could not persist the render ({e}) — gallery entry stays session-only"),+ }+ }Ok(payload)}+/// Where generated stills live. Sibling of the video lane's outputs root and+/// covered by the same read_media_file allow-list.+pub(crate) fn images_root() -> PathBuf {+ dirs::config_dir()+ .unwrap_or_else(|| PathBuf::from("."))+ .join("lu-labs")+ .join("images")+}++fn write_generated_png(b64: &str) -> Result<PathBuf, String> {+ use base64::Engine as _;+ let bytes = base64::engine::general_purpose::STANDARD+ .decode(b64)+ .map_err(|e| format!("decode: {e}"))?;+ let dir = images_root();+ std::fs::create_dir_all(&dir).map_err(|e| format!("mkdir {}: {e}", dir.display()))?;+ // Millisecond stamp + the process id: two renders inside the same+ // millisecond (batching, a retry) must not overwrite each other.+ let stamp = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_millis())+ .unwrap_or(0);+ let path = dir.join(format!("mlx-{stamp}-{}.png", std::process::id()));+ std::fs::write(&path, bytes).map_err(|e| format!("write {}: {e}", path.display()))?;+ Ok(path)+}+pub fn mlx_start(_state: &AppState, _args: &Value) -> CmdResult {if !venv_python().exists() {return Err(crate::commands::bad_request(diff --git a/src/api/mlx-image.ts b/src/api/mlx-image.tsindex ba905b45..f60b50a8 100644--- a/src/api/mlx-image.ts+++ b/src/api/mlx-image.ts@@ -70,6 +70,10 @@ export interface MlxGenerateResult {image_base64: stringwidth: numberheight: number+ /** Absolute path of the PNG Rust also wrote to disk. Absent only when that+ * write failed (best-effort — a full disk must not fail a render), which+ * costs the gallery entry its life beyond this session, nothing more. */+ output?: string}export async function mlxStatus(): Promise<MlxStatus> {@@ -154,7 +158,7 @@ async function waitForMlxRunning(timeoutMs = 30_000): Promise<void> {*/export async function generateMlxImageDataUrl(args: MlxGenerateArgs,-): Promise<{ dataUrl: string; width: number; height: number }> {+): Promise<{ dataUrl: string; width: number; height: number; localPath?: string }> {const status = await mlxStatus()if (!status.installed) {throw new Error(@@ -181,6 +185,7 @@ export async function generateMlxImageDataUrl(dataUrl: `data:image/png;base64,${result.image_base64}`,width: result.width,height: result.height,+ localPath: result.output,}}diff --git a/src/components/create/experimental/__tests__/galleryUrl.test.ts b/src/components/create/experimental/__tests__/galleryUrl.test.tsindex b9da3696..04116d5f 100644--- a/src/components/create/experimental/__tests__/galleryUrl.test.ts+++ b/src/components/create/experimental/__tests__/galleryUrl.test.ts@@ -25,9 +25,16 @@ vi.mock('../../../../api/cloud/jobs', () => ({refreshResultUrl: vi.fn(),resolveResultUrl: vi.fn(),}))+// Only backendCall is faked — fetchLocalhostBytes/isTauri keep their real+// behaviour, which the ComfyUI-path tests below depend on.+vi.mock('../../../../api/backend', async (importOriginal) => ({+ ...(await importOriginal<typeof import('../../../../api/backend')>()),+ backendCall: vi.fn(),+}))import { fetchGalleryItemBlob, recoverGalleryUrl } from '../galleryUrl'import { refreshResultUrl, resolveResultUrl } from '../../../../api/cloud/jobs'+import { backendCall } from '../../../../api/backend'import { useCreateStore, type GalleryItem } from '../../../../stores/createStore'const baseItem: GalleryItem = {@@ -121,3 +128,65 @@ describe('recoverGalleryUrl — expired cloud renders', () => {expect(useCreateStore.getState().gallery[0].unavailable).toBeUndefined()})})++/**+ * Local MLX renders (Mac). partialize strips `dataUrl` on persist, so after a+ * restart the tile has only a filename — and galleryItemUrl turns that into a+ * ComfyUI /view URL, which on a Mac can never answer. Every locally generated+ * image therefore died on the next launch. The file on disk is the way back.+ */+describe('recoverGalleryUrl — local MLX renders on disk', () => {+ beforeEach(() => {+ vi.mocked(backendCall).mockReset()+ useCreateStore.setState({ gallery: [] })+ ;(URL as unknown as { createObjectURL: (b: unknown) => string }).createObjectURL = () => 'blob:restored'+ })++ const flush = () => new Promise((r) => setTimeout(r, 0))++ it('re-reads the file and hands the tile a fresh blob URL', async () => {+ const item = { ...baseItem, id: 'disk-ok', localPath: '/tmp/mlx-1.png' }+ useCreateStore.setState({ gallery: [item] })+ // base64 of "PNG" — content is irrelevant, the decode path is what matters.+ vi.mocked(backendCall).mockResolvedValueOnce('UE5H' as never)++ recoverGalleryUrl(item)+ await flush()+ expect(vi.mocked(backendCall)).toHaveBeenCalledWith('read_media_file', { path: '/tmp/mlx-1.png' })+ expect(useCreateStore.getState().gallery[0].dataUrl).toBe('blob:restored')+ expect(useCreateStore.getState().gallery[0].unavailable).toBeUndefined()+ })++ it('marks the tile unavailable when the file is gone', async () => {+ const item = { ...baseItem, id: 'disk-gone', localPath: '/tmp/deleted.png' }+ useCreateStore.setState({ gallery: [item] })+ vi.mocked(backendCall).mockRejectedValueOnce(new Error('no such file'))++ recoverGalleryUrl(item)+ await flush()+ expect(useCreateStore.getState().gallery[0].unavailable).toBe(true)+ })++ it('reads the file once, not on every remount', async () => {+ // Tiles call this from onError, which can fire repeatedly.+ const item = { ...baseItem, id: 'disk-once', localPath: '/tmp/mlx-2.png' }+ useCreateStore.setState({ gallery: [item] })+ vi.mocked(backendCall).mockResolvedValue('UE5H' as never)++ recoverGalleryUrl(item)+ await flush()+ recoverGalleryUrl(item)+ await flush()+ expect(vi.mocked(backendCall).mock.calls.length).toBe(1)+ })++ it('still marks a ComfyUI item unavailable — no localPath, nothing to re-read', async () => {+ const item = { ...baseItem, id: 'comfy-dead' }+ useCreateStore.setState({ gallery: [item] })++ recoverGalleryUrl(item)+ await flush()+ expect(vi.mocked(backendCall)).not.toHaveBeenCalled()+ expect(useCreateStore.getState().gallery[0].unavailable).toBe(true)+ })+})diff --git a/src/components/create/experimental/galleryUrl.ts b/src/components/create/experimental/galleryUrl.tsindex e51fc488..7289a280 100644--- a/src/components/create/experimental/galleryUrl.ts+++ b/src/components/create/experimental/galleryUrl.ts@@ -1,6 +1,6 @@import { getImageUrl } from '../../../api/comfyui'import { refreshResultUrl, resolveResultUrl } from '../../../api/cloud/jobs'-import { fetchLocalhostBytes, isTauri } from '../../../api/backend'+import { backendCall, fetchLocalhostBytes, isTauri } from '../../../api/backend'import { useCreateStore, type GalleryItem } from '../../../stores/createStore'/** Resolve a gallery item's display URL. Priority mirrors MediaViewer/Gallery:@@ -25,6 +25,16 @@ const recovered = new Map<string, number>()export function recoverGalleryUrl(item: GalleryItem): void {if (!item.jobId) {+ // A local MLX render keeps its bytes on disk (Mac image + video lanes).+ // partialize strips `dataUrl` on persist, so after a restart the only+ // thing left was a filename — and galleryItemUrl turned that into a+ // ComfyUI /view URL, which on a Mac can never resolve. Every locally+ // generated image therefore died on the next launch. Re-read the file+ // instead of declaring the tile dead.+ if (item.localPath) {+ void restoreFromDisk(item)+ return+ }// Local ComfyUI item whose /view fetch failed (engine not running /// output pruned) — nothing to re-sign. Flag it so the tiles can render// an honest "engine offline" state instead of a silently dead <img>.@@ -53,6 +63,32 @@ export function recoverGalleryUrl(item: GalleryItem): void {})}+/**+ * Re-read a local render from disk and hand the tile a fresh blob: URL.+ *+ * Shares the `recovered` guard with the cloud re-sign path so a file that is+ * genuinely gone (user emptied the folder) is tried once per item and then+ * marked unavailable, instead of re-reading on every remount.+ */+async function restoreFromDisk(item: GalleryItem): Promise<void> {+ if (recovered.has(item.id)) return+ recovered.set(item.id, 0)+ try {+ const b64 = await backendCall<string>('read_media_file', { path: item.localPath })+ const binary = atob(b64)+ const bytes = new Uint8Array(binary.length)+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)+ const url = URL.createObjectURL(new Blob([bytes], { type: guessMime(item.filename) }))+ recovered.set(item.id, Date.now())+ useCreateStore.getState().updateGalleryItem(item.id, { dataUrl: url, unavailable: undefined })+ } catch {+ // The file is gone (or unreadable). Same honest dead-tile state the+ // ComfyUI path uses; do NOT release the guard, there is nothing to retry.+ recovered.set(item.id, Date.now())+ useCreateStore.getState().updateGalleryItem(item.id, { unavailable: true })+ }+}+/** Clear a tile's offline flag once its media actually loads (onLoad). */export function markGalleryItemAvailable(item: GalleryItem): void {if (item.unavailable) useCreateStore.getState().updateGalleryItem(item.id, { unavailable: undefined })diff --git a/src/hooks/useCreate.ts b/src/hooks/useCreate.tsindex f1508a71..ff000ca5 100644--- a/src/hooks/useCreate.ts+++ b/src/hooks/useCreate.ts@@ -523,7 +523,7 @@ export function useCreate() {try {state.setProgressPhase('sampling')setProgress(40, 'Generating with MLX...')- const { dataUrl, width: outW, height: outH } = await generateMlxImageDataUrl({+ const { dataUrl, width: outW, height: outH, localPath } = await generateMlxImageDataUrl({prompt, steps, seed, width, height,model: mlxModelIdFor(effImageModel),negativePrompt: negativePrompt || undefined,@@ -534,7 +534,9 @@ export function useCreate() {state.setLastGenTime(`${elapsed}s`)addToGallery({id: uuid(), type: 'image', filename: `mlx-${Date.now()}.png`, subfolder: '',- dataUrl, prompt, negativePrompt, model: imageModel, modelType: 'unknown',+ // localPath is what survives the restart: partialize strips dataUrl,+ // and there is no ComfyUI /view to fall back to on a Mac.+ dataUrl, localPath, prompt, negativePrompt, model: imageModel, modelType: 'unknown',seed: seed === -1 ? 0 : seed, steps, cfgScale, sampler, scheduler,width: outW || width, height: outH || height, batchSize: 1,createdAt: Date.now(), builderUsed: 'dynamic', intent,