Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Desktop: fix image and video gallery downloads (#8388)

oobabooga1f5e4ab3c728
diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.ts
index 7864618ea58..8d2c91e893a 100644
--- a/studio/frontend/src/features/images/api.ts
+++ b/studio/frontend/src/features/images/api.ts
@@ -432,14 +432,19 @@ export async function clearGallery(): Promise<void> {
if (!res.ok) throw new Error(await readFastApiError(res));
}
+/** Fetch an auth-protected gallery image as its original blob. */
+export async function fetchGalleryBlob(url: string): Promise<Blob> {
+ const res = await authFetch(url);
+ if (!res.ok) throw new Error(await readFastApiError(res));
+ return res.blob();
+}
+
/** Fetch a gallery PNG (auth-protected, so it cannot be a plain <img src>) and wrap it in an object URL. Callers must revoke it. */
export async function fetchGalleryObjectUrl(
url: string,
): Promise<{ url: string; bytes: number }> {
- const res = await authFetch(url);
- if (!res.ok) throw new Error(await readFastApiError(res));
// The blob size travels with the URL: the gallery cache is budgeted in bytes, which the caller cannot work out from the URL.
- const blob = await res.blob();
+ const blob = await fetchGalleryBlob(url);
return { url: URL.createObjectURL(blob), bytes: blob.size };
}
diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsx
index 0b5ef37dad0..ae838fc5767 100644
--- a/studio/frontend/src/features/images/images-page.tsx
+++ b/studio/frontend/src/features/images/images-page.tsx
@@ -95,6 +95,11 @@ import { NegativePromptField } from "@/components/negative-prompt-field";
import { cn } from "@/lib/utils";
import { isTauri } from "@/lib/api-base";
import { BlobUrlCache } from "@/lib/blob-url-cache";
+import {
+ downloadFile,
+ downloadUrl,
+ isDownloadCancelled,
+} from "@/lib/native-files";
import { resolveDiffusionGgufFilename } from "@/lib/diffusion-gguf-filename";
import { createPickGuard, runGgufRepoPick } from "@/lib/diffusion-gguf-pick";
import { diffusionRoutePick } from "@/lib/diffusion-route-pick";
@@ -132,6 +137,7 @@ import {
GenerateResponseLostError,
cancelDiffusionGeneration,
deleteGalleryImage,
+ fetchGalleryBlob,
fetchGalleryObjectUrl,
generateDiffusionImage,
getDiffusionLoadProgress,
@@ -344,52 +350,81 @@ function exportFilename(image: GalleryImage, format: ImageExportFormat = "png"):
return `Unsloth_${stamp}_${image.seed}${suffix}.${ext}`;
}
-function saveBlobUrl(href: string, filename: string) {
- const link = document.createElement("a");
- link.href = href;
- link.download = filename;
- link.click();
+// PNG saves the stored bytes verbatim (keeping the embedded recipe); JPEG / WebP re-encode client-side, JPEG flattened onto white.
+async function reencodeImage(
+ src: string,
+ format: Exclude<ImageExportFormat, "png">,
+): Promise<Blob> {
+ const el = new Image();
+ el.decoding = "async";
+ el.src = src;
+ await el.decode();
+ const canvas = document.createElement("canvas");
+ canvas.width = el.naturalWidth;
+ canvas.height = el.naturalHeight;
+ const ctx = canvas.getContext("2d");
+ if (!ctx) {
+ throw new Error("canvas 2d context unavailable");
+ }
+ if (format === "jpeg") {
+ ctx.fillStyle = "#ffffff";
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
+ }
+ ctx.drawImage(el, 0, 0);
+ const blob = await new Promise<Blob | null>((resolve) =>
+ canvas.toBlob(resolve, `image/${format}`, 0.95),
+ );
+ if (!blob) {
+ throw new Error(`could not encode ${format}`);
+ }
+ if (blob.type !== `image/${format}`) {
+ // WebKit can silently return PNG bytes when an encoder is unavailable.
+ // Treat that as a failed conversion so the caller uses a matching .png name.
+ throw new Error(`${format} encoding is unavailable`);
+ }
+ return blob;
}
-// PNG saves the stored bytes verbatim (keeping the embedded recipe); JPEG / WebP re-encode client-side, JPEG flattened onto white.
async function downloadImage(
src: string,
image: GalleryImage,
format: ImageExportFormat = "png",
) {
- if (format === "png") {
- saveBlobUrl(src, exportFilename(image, format));
- return;
+ let outputFormat = format;
+ let outputBlob: Blob | null = null;
+
+ if (format !== "png") {
+ try {
+ outputBlob = await reencodeImage(src, format);
+ } catch {
+ // Conversion failed, so preserve the original PNG instead.
+ outputFormat = "png";
+ outputBlob = null;
+ }
}
+
+ const filename = exportFilename(image, outputFormat);
try {
- const el = new Image();
- el.decoding = "async";
- el.src = src;
- await el.decode();
- const canvas = document.createElement("canvas");
- canvas.width = el.naturalWidth;
- canvas.height = el.naturalHeight;
- const ctx = canvas.getContext("2d");
- if (!ctx) throw new Error("canvas 2d context unavailable");
- if (format === "jpeg") {
- ctx.fillStyle = "#ffffff";
- ctx.fillRect(0, 0, canvas.width, canvas.height);
+ if (outputBlob) {
+ await downloadFile(outputBlob, filename, outputBlob.type);
+ } else if (isTauri) {
+ // WebKit can display the cached object URL but fail to fetch it again with
+ // "Load failed". Re-fetch the authenticated original for the native save.
+ const originalBlob = await fetchGalleryBlob(image.url);
+ await downloadFile(originalBlob, filename, originalBlob.type);
+ } else {
+ await downloadUrl(src, filename);
}
- ctx.drawImage(el, 0, 0);
- const blob = await new Promise<Blob | null>((resolve) =>
- canvas.toBlob(resolve, `image/${format}`, 0.95),
- );
- if (!blob) throw new Error(`could not encode ${format}`);
- const url = URL.createObjectURL(blob);
- try {
- saveBlobUrl(url, exportFilename(image, format));
- } finally {
- // Give the click a tick to start before revoking.
- setTimeout(() => URL.revokeObjectURL(url), 10_000);
+ if (isTauri) {
+ toast.success("Image saved", { description: filename });
}
- } catch {
- // Conversion failed (decode/encode); fall back to the original PNG bytes.
- saveBlobUrl(src, exportFilename(image, "png"));
+ } catch (error) {
+ if (isDownloadCancelled(error)) {
+ return;
+ }
+ toast.error("Could not save image", {
+ description: error instanceof Error ? error.message : undefined,
+ });
}
}
diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsx
index cf34e900b21..f6c04427b60 100644
--- a/studio/frontend/src/features/video/video-page.tsx
+++ b/studio/frontend/src/features/video/video-page.tsx
@@ -86,6 +86,7 @@ import { getHfToken, hfApiToken } from "@/features/hub/stores/hf-token-store";
import { formatBytes, formatEta } from "@/features/hub/lib/format";
import { useNavigate, useSearch } from "@tanstack/react-router";
import { useStagedDownload } from "@/features/hub/download-manager";
+import { isTauri } from "@/lib/api-base";
import { cn } from "@/lib/utils";
import { resolveDiffusionGgufFilename } from "@/lib/diffusion-gguf-filename";
import { createPickGuard, runGgufRepoPick } from "@/lib/diffusion-gguf-pick";
@@ -104,7 +105,11 @@ import {
routedGgufFilename,
routedGgufLabel,
} from "@/lib/diffusion-route-search";
-import { downloadUrlStreaming, isDownloadCancelled } from "@/lib/native-files";
+import {
+ downloadFile,
+ downloadUrlStreaming,
+ isDownloadCancelled,
+} from "@/lib/native-files";
import { toast } from "@/lib/toast";
import { subscribeModelEjected } from "@/lib/model-lifecycle-events";
@@ -227,13 +232,6 @@ function exportFilename(video: GalleryVideo, format: VideoExportFormat = "mp4"):
return `Unsloth_video_${stamp}_${video.seed}.${format}`;
}
-function saveLink(href: string, filename: string) {
- const link = document.createElement("a");
- link.href = href;
- link.download = filename;
- link.click();
-}
-
// MP4 streams from its signed link to the chosen path: that link is cross-origin under Tauri,
// where an anchor no longer saves, and a clip is too big to hold in memory on the way past.
// WebM / GIF are transcoded by the backend on demand (501 when the codec is absent).
@@ -247,12 +245,7 @@ async function downloadVideo(
return;
}
const blob = await fetchGalleryVideoExport(video.id, format);
- const url = URL.createObjectURL(blob);
- try {
- saveLink(url, exportFilename(video, format));
- } finally {
- setTimeout(() => URL.revokeObjectURL(url), 10_000);
- }
+ await downloadFile(blob, exportFilename(video, format), blob.type);
}
function formatTimestamp(iso: string): string {
@@ -1309,22 +1302,20 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
// WebM/GIF go through a server-side transcode that can take seconds (and 501s when the codec is missing), so wrap the helper with toasts.
const handleDownload = useCallback(
async (src: string, video: GalleryVideo, format: "mp4" | "webm" | "gif") => {
- if (format === "mp4") {
- void downloadVideo(src, video, format).catch((err) => {
- if (!isDownloadCancelled(err)) toast.error("Could not save video.");
- });
- return;
- }
- const toastId = toast.loading(`Converting to ${format.toUpperCase()}…`);
+ const toastId =
+ format === "mp4" ? null : toast.loading(`Converting to ${format.toUpperCase()}…`);
try {
await downloadVideo(src, video, format);
- toast.dismiss(toastId);
+ if (toastId !== null) toast.dismiss(toastId);
+ if (isTauri) {
+ toast.success("Video saved", { description: exportFilename(video, format) });
+ }
} catch (err) {
- toast.dismiss(toastId);
+ if (toastId !== null) toast.dismiss(toastId);
if (isDownloadCancelled(err)) return;
- toast.error(
- err instanceof Error ? err.message : `Failed to export ${format}`,
- );
+ toast.error("Could not save video", {
+ description: err instanceof Error ? err.message : undefined,
+ });
}
},
[],
diff --git a/tests/studio/test_desktop_reliability_frontend_contract.py b/tests/studio/test_desktop_reliability_frontend_contract.py
index ed89f132b97..24fc810521c 100644
--- a/tests/studio/test_desktop_reliability_frontend_contract.py
+++ b/tests/studio/test_desktop_reliability_frontend_contract.py
@@ -210,6 +210,35 @@ def test_file_actions_route_through_native_commands_only_in_tauri():
assert "fs::write(&path, content)" not in native_dialogs
+def test_media_galleries_save_natively_with_feedback():
+ images_page = IMAGES_PAGE.read_text(encoding = "utf-8")
+ video_page = VIDEO_PAGE.read_text(encoding = "utf-8")
+ reencode = images_page.split("async function reencodeImage(", 1)[1].split(
+ "\n}\n\nasync function downloadImage", 1
+ )[0]
+ download = images_page.split("async function downloadImage(", 1)[1].split(
+ "\n}\n\nfunction formatTimestamp", 1
+ )[0]
+ video_download = video_page.split("const handleDownload = useCallback(", 1)[1].split(
+ "\n\n const handleDelete", 1
+ )[0]
+
+ assert "await downloadUrl(src, filename);" in download
+ assert "await downloadFile(outputBlob, filename, outputBlob.type);" in download
+ assert "const originalBlob = await fetchGalleryBlob(image.url);" in download
+ assert "await downloadFile(originalBlob, filename, originalBlob.type);" in download
+ assert "blob.type !== `image/${format}`" in reencode
+ assert "isDownloadCancelled(error)" in download
+ assert "if (isTauri)" in download
+ assert 'toast.success("Image saved", { description: filename });' in download
+ assert 'document.createElement("a")' not in download
+
+ assert "await downloadFile(blob, exportFilename(video, format), blob.type);" in video_page
+ assert "if (isTauri)" in video_download
+ assert 'toast.success("Video saved"' in video_download
+ assert "function saveLink(" not in video_page
+
+
def test_chat_exports_await_native_saves_and_markdown_uses_shared_helper():
app_sidebar = APP_SIDEBAR.read_text(encoding = "utf-8")
prompt_storage = PROMPT_STORAGE.read_text(encoding = "utf-8")
@@ -290,8 +319,9 @@ def test_gallery_video_links_are_absolute_and_saved_natively():
assert "downloadUrlStreaming(src, exportFilename(video, format))" in video_page
assert '"save_native_file_from_url"' in helper
assert "isDownloadCancelled(err)" in video_page
- # WebM / GIF keep the blob-and-anchor route they already had; nothing forced a change.
- assert "URL.createObjectURL(blob)" in video_page
+ # Converted exports cross the same native boundary after the backend returns their blob.
+ assert "await downloadFile(blob, exportFilename(video, format), blob.type);" in video_page
+ assert "URL.createObjectURL(blob)" not in video_page
# media-src, not just connect-src: the signed link is played by an element.
tauri_config = (REPO / "studio/src-tauri/tauri.conf.json").read_text(encoding = "utf-8")