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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: save audio clips and stems through the desktop save dialog (#12808)
Etherl5058d843b245
diff --git a/studio/frontend/src/features/audio/components/stem-zip.ts b/studio/frontend/src/features/audio/components/stem-zip.tsindex 8618fd00d29..407d2386611 100644--- a/studio/frontend/src/features/audio/components/stem-zip.ts+++ b/studio/frontend/src/features/audio/components/stem-zip.ts@@ -1,12 +1,15 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-// Stored (uncompressed) zip: WAV barely compresses. Free of app imports for the node test runner.+// stored zip avoids wasted compression because WAV barely compresses.import { Zip, ZipPassThrough } from "fflate";+import { AUDIO_WORKFLOWS, clipWorkflow } from "../workflows";const INVALID_CHARS = new Set('<>:"/\\|?*');const MAX_TITLE_CHARS = 120;+// prompts can span paragraphs; 60 characters keeps CJK and emoji names under 255 bytes.+const MAX_CLIP_TITLE_CHARS = 60;const FALLBACK_TITLE = "Separated track";export function sanitizeFileNamePart(part: string, fallback: string): string {@@ -22,15 +25,32 @@ export function sanitizeFileNamePart(part: string, fallback: string): string {return cleaned || fallback;}-/** The title is kept short so the stem label always survives. */-export function stemFileName(title: string, label: string): string {+function shortTitle(title: string, max: number, fallback: string): string {const bare = title.replace(/\.(wav|mp3|flac|ogg|m4a|aac|opus|webm)$/i, "");- const safeTitle = [...sanitizeFileNamePart(bare, FALLBACK_TITLE)]- .slice(0, MAX_TITLE_CHARS)+ const safe = [...sanitizeFileNamePart(bare, fallback)]+ .slice(0, max).join("").trim();+ return safe || fallback;+}++/** the title is capped so the stem label always survives. */+export function stemFileName(title: string, label: string): string {const safeLabel = sanitizeFileNamePart(label, "Stem");- return `${safeTitle || FALLBACK_TITLE} - ${safeLabel}.wav`;+ return `${shortTitle(title, MAX_TITLE_CHARS, FALLBACK_TITLE)} - ${safeLabel}.wav`;+}++/** gallery clips are always WAV. */+export function clipFileName(clip: {+ prompt?: string | null;+ workflow?: string | null;+ audio_type?: string | null;+}): string {+ const workflow = clipWorkflow(clip);+ const label =+ AUDIO_WORKFLOWS.find((item) => item.id === workflow)?.label ?? "Audio";+ const prompt = (clip.prompt ?? "").replace(/\s+/g, " ");+ return `${shortTitle(prompt, MAX_CLIP_TITLE_CHARS, "Audio")} - ${label}.wav`;}export function stemZipName(title: string): string {diff --git a/studio/frontend/src/features/audio/hooks/use-audio-gallery.tsx b/studio/frontend/src/features/audio/hooks/use-audio-gallery.tsxindex 47cc917c34c..19bee2d7a86 100644--- a/studio/frontend/src/features/audio/hooks/use-audio-gallery.tsx+++ b/studio/frontend/src/features/audio/hooks/use-audio-gallery.tsx@@ -24,6 +24,7 @@ import {type AudioGalleryCursor,clearAudioGallery,deleteAudioClip,+ fetchClipBlob,fetchClipObjectUrl,listAudioGallery,moveAudioClip,@@ -35,11 +36,13 @@ import {MAX_PAGE_SIZE,PAGE_SIZE,} from "../audio-workspace-constants";+import { clipFileName } from "../components/stem-zip";import { decodePeaks } from "../components/waveform-decode";+import { saveAudio } from "../save-audio";import { clipWorkflow } from "../workflows";import type { AudioHostState } from "./audio-host-state";-// Module scope so a tab switch re-renders the gallery instantly.+// module scope preserves instant gallery rendering across tab switches.export const galleryCache: {clips: AudioGalleryClip[];hasMore: boolean;@@ -61,6 +64,8 @@ export function useAudioGallery({}: Pick<AudioHostState, "active">) {const [fallbackClip, setFallbackClip] = useState<{url: string;+ /** bytes for desktop saves when `url` is a blob URL. */+ blob?: Blob;prompt: string;model: string;saved: boolean;@@ -70,7 +75,7 @@ export function useAudioGallery({fallbackClipRef.current = fallbackClip;const loadingMoreRef = useRef(false);const galleryRefreshGeneration = useRef(0);- // Pins and moves in flight. A refresh that overlaps one read the old order, so it is dropped and rerun after.+ // overlapping refreshes read stale order, so defer and rerun them after order writes finish.const orderWrites = useRef({ inFlight: 0, epoch: 0, deferred: false });const [clips, setClips] = useState<AudioGalleryClip[]>(galleryCache.clips);const [hasMore, setHasMore] = useState(galleryCache.hasMore);@@ -466,44 +471,30 @@ export function useAudioGallery({(clip: AudioGalleryClip) => {const src = srcById[clip.id];if (!src) return;- const anchor = document.createElement("a");- anchor.href = src;- anchor.download = `${clip.id}.wav`;- anchor.click();+ void saveAudio(clipFileName(clip), src, () => fetchClipBlob(clip.url));},[srcById],);const handleDownloadFallbackClip = useCallback(() => {if (!fallbackClip) return;- const anchor = document.createElement("a");- anchor.href = fallbackClip.url;- anchor.download = "generated-audio.wav";- anchor.click();+ const { blob } = fallbackClip;+ void saveAudio(+ clipFileName(fallbackClip),+ fallbackClip.url,+ blob ? () => Promise.resolve(blob) : null,+ );}, [fallbackClip]);- const handleDownloadClipById = useCallback(async (clip: AudioGalleryClip) => {- let temporaryUrl: string | null = null;- try {- let src = galleryCache.srcById.get(clip.id);- if (!src) {- const fetched = await fetchClipObjectUrl(clip.url);- src = fetched.url;- temporaryUrl = fetched.url;- }- const anchor = document.createElement("a");- anchor.href = src;- anchor.download = `${clip.id}.wav`;- anchor.click();- } catch {- toast.error("Could not download the clip.");- } finally {- if (temporaryUrl) {- const url = temporaryUrl;- window.setTimeout(() => URL.revokeObjectURL(url), 0);- }- }- }, []);+ const handleDownloadClipById = useCallback(+ (clip: AudioGalleryClip) =>+ saveAudio(+ clipFileName(clip),+ galleryCache.srcById.get(clip.id) ?? null,+ () => fetchClipBlob(clip.url),+ ),+ [],+ );const handleCopyPrompt = useCallback(async (text: string) => {if (await copyToClipboard(text)) {diff --git a/studio/frontend/src/features/audio/hooks/use-clone-generation.ts b/studio/frontend/src/features/audio/hooks/use-clone-generation.tsindex bd291c80cf0..2a0736c22ab 100644--- a/studio/frontend/src/features/audio/hooks/use-clone-generation.ts+++ b/studio/frontend/src/features/audio/hooks/use-clone-generation.ts@@ -78,6 +78,7 @@ export async function showRunResult({const blob = await fetchAudioBlob(clip.url);setFallbackClip({url: URL.createObjectURL(blob),+ blob,prompt: text,model: response.model,saved: true,diff --git a/studio/frontend/src/features/audio/pages/separate-page.tsx b/studio/frontend/src/features/audio/pages/separate-page.tsxindex 6453f36adfa..bbd138873ff 100644--- a/studio/frontend/src/features/audio/pages/separate-page.tsx+++ b/studio/frontend/src/features/audio/pages/separate-page.tsx@@ -35,6 +35,7 @@ import {type SeparateGeneration,} from "../hooks/use-separate-generation";import { useStemSources } from "../hooks/use-stem-sources";+import { saveAudio } from "../save-audio";import {SEPARATE_MAX_SECONDS,separatePresentation,@@ -271,26 +272,13 @@ export function SeparateFooter({);}-function saveBlob(blob: Blob, name: string) {- const url = URL.createObjectURL(blob);- const anchor = document.createElement("a");- anchor.href = url;- anchor.download = name;- anchor.click();- window.setTimeout(() => URL.revokeObjectURL(url), 0);-}--async function downloadGroup(group: SeparationGroup) {- try {- // Each stem is fetched when the zip reaches it, so a long song never holds every stem at once.- const files = group.stems.map((clip) => ({- name: stemFileName(group.title, stemLabel(clip.role ?? "")),- blob: () => fetchAudioBlob(clip.url),- }));- saveBlob(await zipStems(files), stemZipName(group.title));- } catch {- toast.error("Could not download the stems.");- }+function downloadGroup(group: SeparationGroup) {+ // Each stem is fetched when the zip reaches it, so a long song never holds every stem at once.+ const files = group.stems.map((clip) => ({+ name: stemFileName(group.title, stemLabel(clip.role ?? "")),+ blob: () => fetchAudioBlob(clip.url),+ }));+ return saveAudio(stemZipName(group.title), null, () => zipStems(files));}const SEND_TARGETS: readonly SendTarget[] = [@@ -348,13 +336,11 @@ function SelectedSeparation({const clip = group.stems.find((item) => item.id === clipId);const src = sources.srcById[clipId];if (!clip || !src) return;- const anchor = document.createElement("a");- anchor.href = src;- anchor.download = stemFileName(- group.title,- stemLabel(clip.role ?? ""),+ void saveAudio(+ stemFileName(group.title, stemLabel(clip.role ?? "")),+ src,+ () => fetchAudioBlob(clip.url),);- anchor.click();}}onDownloadAll={() => void downloadGroup(group)}onSend={(target, clipId) => {diff --git a/studio/frontend/src/features/audio/save-audio.ts b/studio/frontend/src/features/audio/save-audio.tsnew file mode 100644index 00000000000..e650c2d2116--- /dev/null+++ b/studio/frontend/src/features/audio/save-audio.ts@@ -0,0 +1,37 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { isTauri } from "@/lib/api-base";+import {+ downloadBlobStreaming,+ downloadFile,+ downloadUrl,+ isDownloadCancelled,+} from "@/lib/native-files";+import { toast } from "@/lib/toast";++/** desktop reloads blob: URLs because the page CSP blocks fetch() and the native save dialog needs bytes. */+export async function saveAudio(+ filename: string,+ url: string | null,+ load: (() => Promise<Blob>) | null,+): Promise<void> {+ try {+ if (load && (!url || (isTauri && url.startsWith("blob:")))) {+ const blob = await load();+ if (isTauri) {+ await downloadBlobStreaming(blob, filename);+ } else {+ await downloadFile(blob, filename, blob.type || "audio/wav");+ }+ } else if (url) {+ await downloadUrl(url, filename);+ }+ if (isTauri) toast.success("Audio saved", { description: filename });+ } catch (error) {+ if (isDownloadCancelled(error)) return;+ toast.error("Could not save audio", {+ description: error instanceof Error ? error.message : undefined,+ });+ }+}diff --git a/studio/frontend/src/lib/native-files.ts b/studio/frontend/src/lib/native-files.tsindex 6518f21acb4..2132594b65c 100644--- a/studio/frontend/src/lib/native-files.ts+++ b/studio/frontend/src/lib/native-files.ts@@ -5,6 +5,8 @@ import { isTauri } from "@/lib/api-base";import { decodeDataUri, isDataUri } from "@/lib/data-uri";const NATIVE_FILE_NAME_HEADER = "x-unsloth-default-name";+const NATIVE_FILE_SAVE_TOKEN_HEADER = "x-unsloth-save-token";+const NATIVE_FILE_CHUNK_BYTES = 8 * 1024 * 1024;export class DownloadCancelledError extends Error {constructor() {super("Save cancelled.");@@ -117,6 +119,46 @@ export async function downloadFile(return;}+/** Save a Blob through bounded IPC chunks in Tauri and retain normal downloads on web. */+export async function downloadBlobStreaming(+ content: Blob,+ filename: string,+): Promise<void> {+ if (!isTauri) {+ browserDownload(content, filename);+ return;+ }+ const { invoke } = await import("@tauri-apps/api/core");+ const token = await invoke<string | null>("begin_native_file_save", {+ fileName: filename,+ });+ if (token === null) {+ throw new DownloadCancelledError();+ }+ try {+ for (+ let offset = 0;+ offset < content.size;+ offset += NATIVE_FILE_CHUNK_BYTES+ ) {+ const bytes = new Uint8Array(+ await content+ .slice(offset, offset + NATIVE_FILE_CHUNK_BYTES)+ .arrayBuffer(),+ );+ await invoke<void>("append_native_file_save_chunk", bytes, {+ headers: { [NATIVE_FILE_SAVE_TOKEN_HEADER]: token },+ });+ }+ await invoke<string>("finish_native_file_save", { token });+ } catch (error) {+ await invoke<void>("cancel_native_file_save", { token }).catch(+ () => undefined,+ );+ throw error;+ }+}+export async function urlToBlob(url: string): Promise<Blob> {if (isDataUri(url)) {const { bytes, mimeType } = decodeDataUri(url);diff --git a/studio/frontend/tests/audio-model-eject.test.ts b/studio/frontend/tests/audio-model-eject.test.tsindex 725cf7457eb..8a36284628b 100644--- a/studio/frontend/tests/audio-model-eject.test.ts+++ b/studio/frontend/tests/audio-model-eject.test.ts@@ -176,7 +176,6 @@ test("leaving Transcribe releases the sidecar it loaded", () => {test("selected and fallback clip actions remain named and downloadable", () => {assert.match(source, /aria-label="Download audio clip"/);- // Delete sits in the clip card's menu, the same one each history row uses.assert.match(source,/onDelete=\{\(\) => void handleDeleteClip\(clip\.id\)\}/,@@ -184,22 +183,15 @@ test("selected and fallback clip actions remain named and downloadable", () => {assert.match(source, /menu=\{clipMenu\(selectedClip, "row"\)\}/);assert.match(source,- /const handleDownloadFallbackClip[\s\S]*anchor\.download = "generated-audio\.wav"/,+ /const handleDownloadFallbackClip[\s\S]*saveAudio\(\s*clipFileName\(fallbackClip\),\s*fallbackClip\.url,/,);assert.match(source, /onDownload=\{handleDownloadFallbackClip\}/);});test("a dictation model this page did not load survives a mode switch", () => {- // The activation resync adopts whatever a sidecar holds, including chat dictation's model.- // The identity, not a boolean. Another surface can swap the sidecar's model while Audio- // is inactive; the activation resync then adopts it, and a bare flag claimed it too, so- // Eject unloaded a model this page never loaded. Model only, not model plus engine: a- // "gguf" pick without whisper-server is served by the Transformers fallback and reports- // residency under that engine, so requiring the requested engine leaked the sidecar.+ // match model identity because gguf can report the Transformers fallback engineassert.match(source, /claim !== null &&\s*claim === sttLoadedModel;/);- // Ownership is claimed after a successful load, not before it: claiming up front left the- // flag set when a download was cancelled while the backend kept the previous resident- // model, so leaving Transcribe unloaded another surface's model.+ // claim only after load succeeds because cancellation can leave the previous model residentassert.doesNotMatch(source,/setBusy\("loading"\);\s*sttLoadedByThisPage\.current = sidecarKey;/,diff --git a/studio/frontend/tests/audio-page-policy.test.ts b/studio/frontend/tests/audio-page-policy.test.tsindex 27e08751444..63a29082bd1 100644--- a/studio/frontend/tests/audio-page-policy.test.ts+++ b/studio/frontend/tests/audio-page-policy.test.ts@@ -428,10 +428,10 @@ test("leaving Audio cancels an owned TTS load without touching a pre-request pro);});-test("history-only downloads revoke their temporary blob URL", () => {+test("history-only downloads save the fetched blob without caching a URL", () => {assert.match(audioPageSource,- /handleDownloadClipById[\s\S]*temporaryUrl = fetched\.url;[\s\S]*anchor\.click\(\);[\s\S]*URL\.revokeObjectURL\(url\)/,+ /handleDownloadClipById[\s\S]*galleryCache\.srcById\.get\(clip\.id\) \?\? null,\s*\(\) => fetchClipBlob\(clip\.url\),/,);assert.doesNotMatch(audioPageSource,diff --git a/studio/frontend/tests/audio-stem-mixer-state.test.ts b/studio/frontend/tests/audio-stem-mixer-state.test.tsindex 164edb570a1..937b7801c1a 100644--- a/studio/frontend/tests/audio-stem-mixer-state.test.ts+++ b/studio/frontend/tests/audio-stem-mixer-state.test.ts@@ -3,6 +3,9 @@import assert from "node:assert/strict";import test from "node:test";+import { registerBundlerResolver } from "./helpers/kit.ts";++registerBundlerResolver();const {INITIAL_STEM_MIXER_STATE,@@ -12,6 +15,7 @@ const {stemMixerReducer,} = await import("../src/features/audio/components/stem-mixer-state.ts");const {+ clipFileName,sanitizeFileNamePart,stemFileName,stemZipName,@@ -111,6 +115,48 @@ test("stem file names read '<title> - <Label>.wav' and are safe on disk", () =>assert.equal(sanitizeFileNamePart("", "fallback"), "fallback");});+test("clip file names read '<prompt> - <Workflow>.wav' instead of the clip id", () => {+ const cases: [Parameters<typeof clipFileName>[0], string][] = [+ [{ prompt: "Hello there.", workflow: "speak" }, "Hello there - Speak.wav"],+ [{ prompt: "lofi beat", workflow: "music" }, "lofi beat - Music.wav"],+ [+ { prompt: "song.wav → Alice", workflow: "convert" },+ "song.wav → Alice - Convert.wav",+ ],+ // older clips lack workflow metadata, so audio_type determines the history label.+ [{ prompt: "Hi", audio_type: "orpheus" }, "Hi - Speak.wav"],+ [+ { prompt: "Line one\n\n line two", workflow: "clone" },+ "Line one line two - Clone.wav",+ ],+ [{ prompt: 'a/b:c*?"<>|', workflow: "edit" }, "a_b_c______ - Edit.wav"],+ [{ prompt: " ", workflow: "speak" }, "Audio - Speak.wav"],+ [{ prompt: null, workflow: "separate" }, "Audio - Separate.wav"],+ ];+ for (const [clip, want] of cases) {+ assert.equal(clipFileName(clip), want);+ }+ const long = clipFileName({ prompt: "語".repeat(500), workflow: "speak" });+ assert.equal(long, `${"語".repeat(60)} - Speak.wav`);+ assert.ok(new TextEncoder().encode(long).byteLength <= 255);+});++test("audio downloads go through the native save boundary, never a raw anchor", async () => {+ const { readdir, readFile } = await import("node:fs/promises");+ const root = new URL("../src/features/audio/", import.meta.url);+ const files = (await readdir(root, { recursive: true })).filter((name) =>+ /\.tsx?$/.test(name),+ );+ for (const name of files) {+ const source = await readFile(new URL(name, root), "utf8");+ assert.doesNotMatch(+ source,+ /createElement\(["']a["']\)|\.download\s*=/,+ name,+ );+ }+});+test("repeated names get a counter instead of overwriting", () => {assert.deepEqual(uniqueStemNames(["a - X.wav", "a - X.wav", "A - x.wav", "b.wav"]),diff --git a/studio/frontend/tests/native-file-chunked-save.test.ts b/studio/frontend/tests/native-file-chunked-save.test.tsnew file mode 100644index 00000000000..209838ba3d1--- /dev/null+++ b/studio/frontend/tests/native-file-chunked-save.test.ts@@ -0,0 +1,120 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++import { loadWithStubs } from "./helpers/module-stubs.ts";++type Invoke = (+ command: string,+ args?: unknown,+ options?: { headers?: Record<string, string> },+) => Promise<unknown>;++const DISK_FULL = /disk full/;++type NativeFiles = {+ downloadBlobStreaming: (content: Blob, filename: string) => Promise<void>;+ isDownloadCancelled: (error: unknown) => boolean;+};++function loadNativeFiles(invoke: Invoke): NativeFiles {+ return loadWithStubs<NativeFiles>(+ new URL("../src/lib/native-files.ts", import.meta.url),+ {+ "@/lib/api-base": { isTauri: true },+ "@/lib/data-uri": {+ decodeDataUri: () => {+ throw new Error("unexpected data URI decode");+ },+ isDataUri: () => false,+ },+ "@tauri-apps/api/core": { invoke },+ },+ );+}++test("a native Blob save crosses IPC in bounded chunks", async () => {+ const chunkSizes: number[] = [];+ const headers: Array<Record<string, string> | undefined> = [];+ const commands: string[] = [];+ const nativeFiles = loadNativeFiles((command, args, options) => {+ commands.push(command);+ if (command === "begin_native_file_save") {+ assert.deepEqual(args, { fileName: "stems.zip" });+ return Promise.resolve("opaque-save-token");+ }+ if (command === "append_native_file_save_chunk") {+ assert.ok(args instanceof Uint8Array);+ chunkSizes.push(args.byteLength);+ headers.push(options?.headers);+ return Promise.resolve(undefined);+ }+ if (command === "finish_native_file_save") {+ assert.deepEqual(args, { token: "opaque-save-token" });+ return Promise.resolve("stems.zip");+ }+ throw new Error(`unexpected command ${command}`);+ });++ await nativeFiles.downloadBlobStreaming(+ new Blob([new Uint8Array(8 * 1024 * 1024 + 17)]),+ "stems.zip",+ );++ assert.deepEqual(commands, [+ "begin_native_file_save",+ "append_native_file_save_chunk",+ "append_native_file_save_chunk",+ "finish_native_file_save",+ ]);+ assert.deepEqual(chunkSizes, [8 * 1024 * 1024, 17]);+ assert.deepEqual(headers, [+ { "x-unsloth-save-token": "opaque-save-token" },+ { "x-unsloth-save-token": "opaque-save-token" },+ ]);+});++test("a cancelled native Blob save has the normal cancellation error", async () => {+ const nativeFiles = loadNativeFiles((command) => {+ assert.equal(command, "begin_native_file_save");+ return Promise.resolve(null);+ });++ const error = await nativeFiles+ .downloadBlobStreaming(new Blob(), "stems.zip")+ .then(+ () => null,+ (rejection: unknown) => rejection,+ );+ assert.equal(nativeFiles.isDownloadCancelled(error), true);+});++test("a failed native Blob save drops its staged file", async () => {+ const commands: string[] = [];+ const nativeFiles = loadNativeFiles((command, args) => {+ commands.push(command);+ if (command === "begin_native_file_save") {+ return Promise.resolve("opaque-save-token");+ }+ if (command === "append_native_file_save_chunk") {+ return Promise.reject(new Error("disk full"));+ }+ if (command === "cancel_native_file_save") {+ assert.deepEqual(args, { token: "opaque-save-token" });+ return Promise.resolve(undefined);+ }+ throw new Error(`unexpected command ${command}`);+ });++ await assert.rejects(+ nativeFiles.downloadBlobStreaming(new Blob(["audio"]), "stems.zip"),+ DISK_FULL,+ );+ assert.deepEqual(commands, [+ "begin_native_file_save",+ "append_native_file_save_chunk",+ "cancel_native_file_save",+ ]);+});diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rsindex 26d4e05213e..4805ad4d1f3 100644--- a/studio/src-tauri/src/main.rs+++ b/studio/src-tauri/src/main.rs@@ -2238,6 +2238,7 @@ fn main() {.manage(desktop_updater::new_desktop_update_state()).manage(new_close_to_tray_state()).manage(native_file_dialogs::ChatImportRegistry::default())+ .manage(native_file_dialogs::NativeSaveRegistry::default()).manage(browser_webview::new_browser_views()).invoke_handler(tauri::generate_handler![app_menu::set_app_menu_actions,@@ -2289,6 +2290,10 @@ fn main() {native_clipboard::read_native_clipboard_files,native_clipboard::read_native_clipboard_png,native_file_dialogs::save_native_file,+ native_file_dialogs::begin_native_file_save,+ native_file_dialogs::append_native_file_save_chunk,+ native_file_dialogs::finish_native_file_save,+ native_file_dialogs::cancel_native_file_save,native_file_dialogs::save_native_file_from_url,native_file_dialogs::download_logs_to_downloads,native_file_dialogs::pick_native_chat_import,diff --git a/studio/src-tauri/src/native_file_dialogs.rs b/studio/src-tauri/src/native_file_dialogs.rsindex 9d393964ed0..5f750b798e0 100644--- a/studio/src-tauri/src/native_file_dialogs.rs+++ b/studio/src-tauri/src/native_file_dialogs.rs@@ -15,6 +15,8 @@ const MAX_TRAINING_CONFIG_BYTES: u64 = 1024 * 1024;/// pieces, and a piece has to fit in one IPC response.const MAX_CHAT_IMPORT_CHUNK_BYTES: usize = 8 * 1024 * 1024;const NATIVE_FILE_NAME_HEADER: &str = "x-unsloth-default-name";+const NATIVE_FILE_SAVE_TOKEN_HEADER: &str = "x-unsloth-save-token";+const MAX_NATIVE_FILE_SAVE_CHUNK_BYTES: usize = 8 * 1024 * 1024;const CHAT_IMPORT_EXTENSIONS: &[&str] = &["json", "jsonl", "ndjson", "csv", "md", "markdown"];const CHAT_IMPORT_TYPE_ERROR: &str ="Chat import must be a .json, .jsonl, .ndjson, .csv, or .md file.";@@ -70,6 +72,50 @@ impl ChatImportRegistry {}}+struct NativeSave {+ destination: PathBuf,+ temporary: tempfile::NamedTempFile,+}++const NATIVE_SAVE_HANDLE_LIMIT: usize = 8;++#[derive(Default)]+pub struct NativeSaveRegistry {+ files: Mutex<Vec<(String, Arc<Mutex<NativeSave>>)>>,+}++impl NativeSaveRegistry {+ fn register(&self, save: NativeSave) -> String {+ let token: String = (0..4)+ .map(|_| format!("{:016x}", rand::random::<u64>()))+ .collect();+ let mut files = self.files.lock().expect("native save registry poisoned");+ files.push((token.clone(), Arc::new(Mutex::new(save))));+ while files.len() > NATIVE_SAVE_HANDLE_LIMIT {+ files.remove(0);+ }+ token+ }++ fn resolve(&self, token: &str) -> Option<Arc<Mutex<NativeSave>>> {+ let files = self.files.lock().expect("native save registry poisoned");+ files+ .iter()+ .find(|(candidate, _)| candidate == token)+ .map(|(_, save)| Arc::clone(save))+ }++ fn take(&self, token: &str) -> Option<Arc<Mutex<NativeSave>>> {+ let mut files = self.files.lock().expect("native save registry poisoned");+ let index = files.iter().position(|(candidate, _)| candidate == token)?;+ Some(files.remove(index).1)+ }++ fn cancel(&self, token: &str) {+ let _ = self.take(token);+ }+}+fn default_file_name(suggested_name: &str) -> String {Path::new(suggested_name).file_name()@@ -211,6 +257,45 @@ fn save_selected_file(Ok(Some(saved_file_name(&path)))}+fn native_save_chunk(body: &tauri::ipc::InvokeBody) -> Result<Cow<'_, [u8]>, String> {+ let content = invoke_body_bytes(body)+ .ok_or_else(|| "Native export content must be binary.".to_string())?;+ if content.len() > MAX_NATIVE_FILE_SAVE_CHUNK_BYTES {+ return Err("Native export chunk is too large.".to_string());+ }+ Ok(content)+}++fn append_native_save(save: &Arc<Mutex<NativeSave>>, content: &[u8]) -> Result<(), String> {+ let mut save = save+ .lock()+ .map_err(|_| "Native export handle is unavailable.".to_string())?;+ let destination = save.destination.clone();+ save.temporary+ .write_all(content)+ .map_err(|error| format!("Failed to save {}: {error}", destination.display()))+}++fn finish_native_save(save: Arc<Mutex<NativeSave>>) -> Result<String, String> {+ let save = Arc::try_unwrap(save)+ .map_err(|_| "Native export is still being written.".to_string())?+ .into_inner()+ .map_err(|_| "Native export handle is unavailable.".to_string())?;+ let NativeSave {+ destination,+ mut temporary,+ } = save;+ temporary+ .flush()+ .and_then(|()| temporary.as_file().sync_all())+ .map_err(|error| format!("Failed to save {}: {error}", destination.display()))?;+ let name = saved_file_name(&destination);+ temporary+ .persist(&destination)+ .map_err(|error| format!("Failed to save {}: {}", destination.display(), error.error))?;+ Ok(name)+}+/// Only the local backend, or the webview could write any host's reply to disk. Parsed/// rather than sliced: in `http://127.0.0.1:[email protected]/clip` the loopback-looking part/// is userinfo and the client would connect to `evil.test`.@@ -385,6 +470,89 @@ pub async fn save_native_file(save_selected_file(selected_path, content.as_ref())}+#[tauri::command]+pub async fn begin_native_file_save(+ webview: tauri::Webview,+ app: AppHandle,+ registry: State<'_, NativeSaveRegistry>,+ file_name: String,+) -> Result<Option<String>, String> {+ crate::native_intents::ensure_main_window(&webview)?;+ let file_name = default_file_name(&file_name);+ let (filter_name, extensions) = save_filter(&file_name);+ let extension_refs = extensions.iter().map(String::as_str).collect::<Vec<_>>();+ let (tx, rx) = tokio::sync::oneshot::channel();+ app.dialog()+ .file()+ .set_title("Save Unsloth export")+ .set_file_name(file_name)+ .add_filter(filter_name, &extension_refs)+ .save_file(move |path| {+ let _ = tx.send(path);+ });+ let selected_path = rx+ .await+ .map_err(|_| "Save dialog closed unexpectedly.".to_string())?+ .map(local_dialog_path)+ .transpose()?;+ let Some(destination) = selected_path else {+ return Ok(None);+ };+ let temporary = staged_temp_file(&destination)?;+ Ok(Some(registry.register(NativeSave {+ destination,+ temporary,+ })))+}++#[tauri::command]+pub async fn append_native_file_save_chunk(+ webview: tauri::Webview,+ registry: State<'_, NativeSaveRegistry>,+ request: tauri::ipc::Request<'_>,+) -> Result<(), String> {+ crate::native_intents::ensure_main_window(&webview)?;+ let token = request+ .headers()+ .get(NATIVE_FILE_SAVE_TOKEN_HEADER)+ .ok_or_else(|| "Native export token is missing.".to_string())?+ .to_str()+ .map_err(|_| "Invalid native export token.".to_string())?;+ let save = registry+ .resolve(token)+ .ok_or_else(|| "That native export is no longer available.".to_string())?;+ let content = native_save_chunk(request.body())?.into_owned();+ tokio::task::spawn_blocking(move || append_native_save(&save, &content))+ .await+ .map_err(|error| format!("Failed to write the native export: {error}"))?+}++#[tauri::command]+pub async fn finish_native_file_save(+ webview: tauri::Webview,+ registry: State<'_, NativeSaveRegistry>,+ token: String,+) -> Result<String, String> {+ crate::native_intents::ensure_main_window(&webview)?;+ let save = registry+ .take(&token)+ .ok_or_else(|| "That native export is no longer available.".to_string())?;+ tokio::task::spawn_blocking(move || finish_native_save(save))+ .await+ .map_err(|error| format!("Failed to finish the native export: {error}"))?+}++#[tauri::command]+pub fn cancel_native_file_save(+ webview: tauri::Webview,+ registry: State<'_, NativeSaveRegistry>,+ token: String,+) -> Result<(), String> {+ crate::native_intents::ensure_main_window(&webview)?;+ registry.cancel(&token);+ Ok(())+}+/// Save a backend URL by streaming it to the chosen path.////// `save_native_file` carries the bytes through IPC, so the caller buffers the whole body@@ -927,6 +1095,64 @@ mod tests {let _ = fs::remove_file(binary_path);}+ #[test]+ fn chunked_save_keeps_the_destination_atomic() {+ let destination = temp_path("chunked").with_extension("zip");+ fs::write(&destination, b"previous export").unwrap();+ let registry = NativeSaveRegistry::default();+ let token = registry.register(NativeSave {+ temporary: staged_temp_file(&destination).unwrap(),+ destination: destination.clone(),+ });+ let save = registry.resolve(&token).unwrap();++ append_native_save(&save, b"first ").unwrap();+ append_native_save(&save, b"second").unwrap();+ assert_eq!(fs::read(&destination).unwrap(), b"previous export");+ drop(save);++ let completed = registry.take(&token).unwrap();+ assert_eq!(+ finish_native_save(completed).unwrap(),+ saved_file_name(&destination)+ );+ assert_eq!(fs::read(&destination).unwrap(), b"first second");+ assert!(registry.resolve(&token).is_none());+ let _ = fs::remove_file(destination);+ }++ #[test]+ fn cancelled_chunked_save_preserves_the_destination() {+ let destination = temp_path("chunked-cancel").with_extension("zip");+ fs::write(&destination, b"keep this").unwrap();+ let registry = NativeSaveRegistry::default();+ let token = registry.register(NativeSave {+ temporary: staged_temp_file(&destination).unwrap(),+ destination: destination.clone(),+ });+ append_native_save(®istry.resolve(&token).unwrap(), b"discard this").unwrap();++ registry.cancel(&token);+ assert_eq!(fs::read(&destination).unwrap(), b"keep this");+ assert!(registry.resolve(&token).is_none());+ let _ = fs::remove_file(destination);+ }++ #[test]+ fn native_save_chunks_are_bounded() {+ let accepted = tauri::ipc::InvokeBody::Raw(vec![0; MAX_NATIVE_FILE_SAVE_CHUNK_BYTES]);+ assert_eq!(+ native_save_chunk(&accepted).unwrap().len(),+ MAX_NATIVE_FILE_SAVE_CHUNK_BYTES+ );++ let refused = tauri::ipc::InvokeBody::Raw(vec![0; MAX_NATIVE_FILE_SAVE_CHUNK_BYTES + 1]);+ assert_eq!(+ native_save_chunk(&refused).unwrap_err(),+ "Native export chunk is too large."+ );+ }+#[test]fn markdown_exports_use_a_markdown_save_filter() {assert_save_filter("message.md", "Markdown", &["md", "markdown"]);diff --git a/tests/studio/test_desktop_reliability_frontend_contract.py b/tests/studio/test_desktop_reliability_frontend_contract.pyindex a4953fe9875..f52d964c368 100644--- a/tests/studio/test_desktop_reliability_frontend_contract.py+++ b/tests/studio/test_desktop_reliability_frontend_contract.py@@ -312,6 +312,38 @@ def test_media_galleries_save_natively_with_feedback():assert "function saveLink(" not in video_page+def test_audio_clips_and_stems_save_natively():+ save_audio = _ui_source(FRONTEND / "features/audio/save-audio.ts")+ helper = _ui_source(NATIVE_FILES)+ dialogs = _ui_source(NATIVE_DIALOGS)+ main_rs = (REPO / "studio/src-tauri/src/main.rs").read_text(encoding = "utf-8")++ # desktop re-reads blob URLs because the page CSP blocks fetch()+ assert 'isTauri && url.startsWith("blob:")' in save_audio+ assert "await downloadBlobStreaming(blob, filename);" in save_audio+ assert "await downloadUrl(url, filename);" in save_audio+ assert "if (isDownloadCancelled(error)) return;" in save_audio+ # tests/audio-stem-mixer-state.test.ts forbids raw anchors in features/audio+ for page in ("hooks/use-audio-gallery.tsx", "pages/separate-page.tsx"):+ assert "saveAudio(" in _ui_source(FRONTEND / "features/audio" / page)++ streaming = helper[helper.index("export async function downloadBlobStreaming") :]+ assert ".slice(offset, offset + NATIVE_FILE_CHUNK_BYTES)" in streaming+ assert "NATIVE_FILE_CHUNK_BYTES" in streaming+ assert "await content.arrayBuffer()" not in streaming+ for command in (+ "begin_native_file_save",+ "append_native_file_save_chunk",+ "finish_native_file_save",+ "cancel_native_file_save",+ ):+ assert f'"{command}"' in streaming+ assert f"native_file_dialogs::{command}," in main_rs+ assert "MAX_NATIVE_FILE_SAVE_CHUNK_BYTES" in dialogs+ assert "staged_temp_file(&destination)" in dialogs+ assert "spawn_blocking(move || append_native_save" in dialogs++def test_chat_exports_await_native_saves_and_markdown_uses_shared_helper():prompt_storage = _ui_source(PROMPT_STORAGE)thread = _ui_source(THREAD)@@ -326,7 +358,7 @@ def test_chat_exports_await_native_saves_and_markdown_uses_shared_helper():assert "catch (error)" not in download_blobassert "isDownloadCancelled(error)" in prompt_storage- # #12122 moved chat export out of the sidebar into the Library and the project menu.+ # #12122 moved chat export into the Library and project menuchats_library = _ui_source(FRONTEND / "features/library/chats/chats-library.tsx")project_menu = _ui_source(FRONTEND / "features/chat/components/project-menu-items.tsx")for source in (thread, thread_sidebar, shared_composer, data_tab, projects):