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 remaining file downloads (#7710)

oobaboogaa763affd4d1f
diff --git a/studio/frontend/src/components/assistant-ui/audio-player.tsx b/studio/frontend/src/components/assistant-ui/audio-player.tsx
index 51ea6464986..2052c318081 100644
--- a/studio/frontend/src/components/assistant-ui/audio-player.tsx
+++ b/studio/frontend/src/components/assistant-ui/audio-player.tsx
@@ -4,9 +4,11 @@
"use client";
import { Button } from "@/components/ui/button";
-import { PauseIcon, PlayIcon } from "lucide-react";
+import { downloadUrl, isDownloadCancelled } from "@/lib/native-files";
+import { toast } from "@/lib/toast";
import { Download01Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
+import { PauseIcon, PlayIcon } from "lucide-react";
import { type FC, useRef, useState } from "react";
interface AudioPlayerProps {
@@ -56,10 +58,11 @@ export const AudioPlayer: FC<AudioPlayerProps> = ({ src }) => {
};
const handleDownload = () => {
- const link = document.createElement("a");
- link.href = src;
- link.download = "generated-audio.wav";
- link.click();
+ void downloadUrl(src, "generated-audio.wav").catch((error) => {
+ if (!isDownloadCancelled(error)) {
+ toast.error("Could not save audio.");
+ }
+ });
};
const formatTime = (t: number) => {
diff --git a/studio/frontend/src/components/assistant-ui/image.tsx b/studio/frontend/src/components/assistant-ui/image.tsx
index f10c1bf024b..b24c6dd91c6 100644
--- a/studio/frontend/src/components/assistant-ui/image.tsx
+++ b/studio/frontend/src/components/assistant-ui/image.tsx
@@ -7,11 +7,20 @@
"use client";
+import { Spinner } from "@/components/ui/spinner";
+import {
+ downloadUrl,
+ isDownloadCancelled,
+ urlToBlob,
+} from "@/lib/native-files";
+import { toast } from "@/lib/toast";
import { cn } from "@/lib/utils";
import type {
ImageMessagePart,
ImageMessagePartComponent,
} from "@assistant-ui/react";
+import { Download01Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
import { type VariantProps, cva } from "class-variance-authority";
import {
CopyIcon,
@@ -20,9 +29,6 @@ import {
RefreshCwIcon,
ShieldAlertIcon,
} from "lucide-react";
-import { Spinner } from "@/components/ui/spinner";
-import { Download01Icon } from "@hugeicons/core-free-icons";
-import { HugeiconsIcon } from "@hugeicons/react";
import {
type ComponentProps,
type PropsWithChildren,
@@ -51,24 +57,8 @@ const extensionForMimeType = (mimeType?: string): string => {
}
};
-const DATA_URI_MIME_RE = /data:([^;]+)/;
-const DATA_URI_BASE64_RE = /;base64/i;
const IMAGE_DATA_URI_MIME_RE = /^data:([^;,]+)/;
-export const dataUriToBlob = (dataUri: string): Blob => {
- const [meta, data] = dataUri.split(",");
- const mime = meta?.match(DATA_URI_MIME_RE)?.[1] ?? "application/octet-stream";
- if (!DATA_URI_BASE64_RE.test(meta ?? "")) {
- return new Blob([decodeURIComponent(data ?? "")], { type: mime });
- }
- const bytes = atob(data ?? "");
- const arr = new Uint8Array(bytes.length);
- for (let i = 0; i < bytes.length; i += 1) {
- arr[i] = bytes.charCodeAt(i);
- }
- return new Blob([arr], { type: mime });
-};
-
const mimeFromImage = (image: string): string | undefined =>
image.match(IMAGE_DATA_URI_MIME_RE)?.[1];
@@ -80,21 +70,11 @@ export const downloadImagePart = (
}
const ext = extensionForMimeType(mimeFromImage(part.image));
const filename = part.filename ?? `image.${ext}`;
- const isDataUri = part.image.startsWith("data:");
- const objectUrl = isDataUri
- ? URL.createObjectURL(dataUriToBlob(part.image))
- : null;
- const href = objectUrl ?? part.image;
- const a = document.createElement("a");
- a.href = href;
- a.download = filename;
- a.rel = "noopener";
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- if (objectUrl) {
- URL.revokeObjectURL(objectUrl);
- }
+ void downloadUrl(part.image, filename).catch((error) => {
+ if (!isDownloadCancelled(error)) {
+ toast.error("Could not save image.");
+ }
+ });
};
export const copyImagePart = async (
@@ -107,9 +87,7 @@ export const copyImagePart = async (
) {
throw new Error("Clipboard API is not available in this environment.");
}
- const blob = part.image.startsWith("data:")
- ? dataUriToBlob(part.image)
- : await fetch(part.image).then((r) => r.blob());
+ const blob = await urlToBlob(part.image);
const mime = mimeFromImage(part.image) || blob.type || "image/png";
await navigator.clipboard.write([new ClipboardItem({ [mime]: blob })]);
};
diff --git a/studio/frontend/src/components/assistant-ui/markdown-text.tsx b/studio/frontend/src/components/assistant-ui/markdown-text.tsx
index 81265bd05dc..e7c4b8f27ec 100644
--- a/studio/frontend/src/components/assistant-ui/markdown-text.tsx
+++ b/studio/frontend/src/components/assistant-ui/markdown-text.tsx
@@ -13,9 +13,11 @@ import {
} from "@/features/chat/artifacts/html-fences";
import { copyToClipboard } from "@/lib/copy-to-clipboard";
import { preprocessLaTeX } from "@/lib/latex";
+import { downloadFile, isDownloadCancelled } from "@/lib/native-files";
import { openLink } from "@/lib/open-link";
import { safeMarkdownUrl } from "@/lib/safe-markdown-url";
import { Tick02Icon } from "@/lib/tick-icon";
+import { toast } from "@/lib/toast";
import { INTERNAL, useAuiState, useMessagePartText } from "@assistant-ui/react";
import { Copy01Icon, Download01Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
@@ -66,6 +68,8 @@ function getMermaidSource(blockContent: string): string | null {
function getCodeFilename(language: string | null) {
const extByLanguage: Record<string, string> = {
bash: "sh",
+ "c++": "cpp",
+ csharp: "cs",
javascript: "js",
js: "js",
json: "json",
@@ -74,6 +78,8 @@ function getCodeFilename(language: string | null) {
md: "md",
python: "py",
py: "py",
+ ruby: "rb",
+ rust: "rs",
shell: "sh",
sh: "sh",
sql: "sql",
@@ -116,15 +122,13 @@ function SvgPreview({ source }: { source: string }) {
}
function downloadTextFile(filename: string, text: string): void {
- const blob = new Blob([text], { type: "text/plain;charset=utf-8" });
- const url = URL.createObjectURL(blob);
- const anchor = document.createElement("a");
- anchor.href = url;
- anchor.download = filename;
- document.body.appendChild(anchor);
- anchor.click();
- document.body.removeChild(anchor);
- window.setTimeout(() => URL.revokeObjectURL(url), 0);
+ void downloadFile(text, filename, "text/plain;charset=utf-8").catch(
+ (error) => {
+ if (!isDownloadCancelled(error)) {
+ toast.error("Could not save file.");
+ }
+ },
+ );
}
function useCopiedState() {
diff --git a/studio/frontend/src/features/studio/sections/training-section.tsx b/studio/frontend/src/features/studio/sections/training-section.tsx
index 5650b9c1459..8ed7a2e7821 100644
--- a/studio/frontend/src/features/studio/sections/training-section.tsx
+++ b/studio/frontend/src/features/studio/sections/training-section.tsx
@@ -29,6 +29,7 @@ import { useRef } from "react";
import { toast } from "@/lib/toast";
import { CartesianGrid, Line, LineChart, XAxis, YAxis } from "recharts";
import { useT } from "@/i18n";
+import { downloadFile, isDownloadCancelled } from "@/lib/native-files";
const placeholderData = [
{ step: 0, loss: 2.5 },
@@ -97,19 +98,18 @@ export function TrainingSection() {
includeVisionFields,
includeVisionFields && !isDeepseekOcr,
);
- const blob = new Blob([yamlStr], { type: "text/yaml" });
- const url = URL.createObjectURL(blob);
- const a = document.createElement("a");
- a.href = url;
-
const model = (store.selectedModel ?? "model").split("/").pop();
const method = store.trainingMethod ?? "qlora";
const dataset = (store.dataset ?? "dataset").split("/").pop();
const timestamp = new Date().toISOString().replace(/[:T]/g, "-").slice(0, 19);
- a.download = `${model}_${method}_${dataset}_${timestamp}.yaml`;
-
- a.click();
- URL.revokeObjectURL(url);
+ const filename = `${model}_${method}_${dataset}_${timestamp}.yaml`;
+ void downloadFile(yamlStr, filename, "text/yaml;charset=utf-8").catch(
+ (error) => {
+ if (!isDownloadCancelled(error)) {
+ toast.error("Failed to save training config.");
+ }
+ },
+ );
};
const handleResetConfig = () => {
diff --git a/studio/frontend/src/lib/data-uri.ts b/studio/frontend/src/lib/data-uri.ts
new file mode 100644
index 00000000000..f00d86d4246
--- /dev/null
+++ b/studio/frontend/src/lib/data-uri.ts
@@ -0,0 +1,209 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Only a trailing `;base64` marks the payload as base64. A segment named
+// `base64` anywhere else is an ordinary parameter, so
+// `data:text/plain;base64;charset=utf-8,SGVsbG8=` stays literal text.
+const DATA_URI_BASE64_RE = /;[ \t]*base64[ \t]*$/i;
+const PERCENT_ESCAPE_RE = /%([0-9a-f]{2})/gi;
+const DEFAULT_MIME_TYPE = "text/plain;charset=US-ASCII";
+const PERCENT = 0x25;
+// The URL parser normalises its input before parsing anything: it removes any
+// leading and trailing C0 control or space, then removes every ASCII tab and
+// newline. So ` data:text/plain;base64\n,...` really is base64. Only raw
+// characters go; an escaped %0A or %20 is payload.
+const URL_WHITESPACE_RE = /[\t\n\r]/g;
+const HAS_URL_WHITESPACE_RE = /[\t\n\r]/;
+const DATA_SCHEME = "data:";
+
+function isUrlWhitespace(code: number): boolean {
+ return code === 0x09 || code === 0x0a || code === 0x0d;
+}
+
+function trimUrlControls(url: string): string {
+ let start = 0;
+ let end = url.length;
+ while (start < end && url.charCodeAt(start) <= 0x20) {
+ start += 1;
+ }
+ while (end > start && url.charCodeAt(end - 1) <= 0x20) {
+ end -= 1;
+ }
+ return start === 0 && end === url.length ? url : url.slice(start, end);
+}
+
+function normalizeUrl(url: string): string {
+ const trimmed = trimUrlControls(url);
+ // Testing first keeps the common case from copying a multi-megabyte string.
+ return HAS_URL_WHITESPACE_RE.test(trimmed)
+ ? trimmed.replace(URL_WHITESPACE_RE, "")
+ : trimmed;
+}
+
+export interface DecodedDataUri {
+ bytes: Uint8Array;
+ mimeType: string;
+}
+
+/** URL schemes are case-insensitive, so `DATA:image/png;...` is a data URI. */
+export function isDataUri(url: string): boolean {
+ // Matched in place rather than by normalising a fixed-size prefix: any
+ // number of leading controls is legal, and a window large enough for all of
+ // them would be a guess. Cost is the leading run plus five characters.
+ let index = 0;
+ while (index < url.length && url.charCodeAt(index) <= 0x20) {
+ index += 1;
+ }
+ for (const expected of DATA_SCHEME) {
+ // Tabs and newlines are removed anywhere, the scheme included. A space is
+ // not, so `da ta:` stays invalid, which is what all three engines do.
+ while (index < url.length && isUrlWhitespace(url.charCodeAt(index))) {
+ index += 1;
+ }
+ if (index >= url.length || url[index].toLowerCase() !== expected) {
+ return false;
+ }
+ index += 1;
+ }
+ return true;
+}
+
+/** Hex digit value, or -1. Avoids allocating a substring per character. */
+function hexValue(code: number): number {
+ if (code >= 0x30 && code <= 0x39) {
+ return code - 0x30;
+ }
+ if (code >= 0x61 && code <= 0x66) {
+ return code - 0x57;
+ }
+ if (code >= 0x41 && code <= 0x46) {
+ return code - 0x37;
+ }
+ return -1;
+}
+
+function escapeAt(data: string, index: number): number {
+ if (data.charCodeAt(index) !== PERCENT) {
+ return -1;
+ }
+ const high = hexValue(data.charCodeAt(index + 1));
+ const low = hexValue(data.charCodeAt(index + 2));
+ return high < 0 || low < 0 ? -1 : high * 16 + low;
+}
+
+/**
+ * Percent-decode to raw octets, the way a browser's own data-URL parser does.
+ *
+ * decodeURIComponent() cannot be used here: it insists the escapes form valid
+ * UTF-8, so a legitimate binary payload such as `data:audio/wav,%FF%00%80`
+ * throws URIError instead of yielding [255, 0, 128]. Percent-decoding is
+ * byte-oriented, and an invalid escape is left alone rather than rejected.
+ *
+ * Everything goes into one growable buffer. Payloads here reach tens of
+ * megabytes, and a per-run or per-character allocation turns an encoded SVG
+ * into seconds of blocked UI and hundreds of MiB of garbage.
+ */
+function percentDecodeOctets(data: string): Uint8Array {
+ const encoder = new TextEncoder();
+ if (!data.includes("%")) {
+ return encoder.encode(data);
+ }
+
+ // Escapes shrink three characters to one byte and ASCII literals are 1:1, so
+ // the source length already fits all but non-ASCII payloads.
+ let out = new Uint8Array(data.length);
+ let length = 0;
+
+ const reserve = (extra: number) => {
+ if (length + extra <= out.length) {
+ return;
+ }
+ let capacity = Math.max(out.length, 1);
+ while (capacity < length + extra) {
+ capacity *= 2;
+ }
+ const grown = new Uint8Array(capacity);
+ grown.set(out.subarray(0, length));
+ out = grown;
+ };
+
+ let literalStart = 0;
+ const flushLiteral = (end: number) => {
+ if (end <= literalStart) {
+ return;
+ }
+ const literal = data.slice(literalStart, end);
+ // Worst case is 3 UTF-8 bytes per BMP character; a surrogate pair is 4
+ // bytes for 2 characters, so this bound holds either way.
+ reserve(literal.length * 3);
+ length += encoder.encodeInto(literal, out.subarray(length)).written;
+ };
+
+ let index = 0;
+ while (index < data.length) {
+ if (escapeAt(data, index) < 0) {
+ index += 1;
+ continue;
+ }
+ flushLiteral(index);
+ let octet = escapeAt(data, index);
+ while (octet >= 0) {
+ reserve(1);
+ out[length] = octet;
+ length += 1;
+ index += 3;
+ octet = escapeAt(data, index);
+ }
+ literalStart = index;
+ }
+ flushLiteral(data.length);
+
+ return out.slice(0, length);
+}
+
+function base64ToBytes(payload: string): Uint8Array {
+ const binary = atob(payload);
+ const bytes = new Uint8Array(binary.length);
+ for (let index = 0; index < binary.length; index += 1) {
+ bytes[index] = binary.charCodeAt(index);
+ }
+ return bytes;
+}
+
+export function decodeDataUri(rawDataUri: string): DecodedDataUri {
+ const dataUri = normalizeUrl(rawDataUri);
+ const separator = dataUri.indexOf(",");
+ if (!isDataUri(dataUri) || separator < 0) {
+ throw new Error("Invalid data URI.");
+ }
+ const metadata = dataUri.slice(5, separator);
+ // A fragment belongs to the URL, not to the payload.
+ const fragment = dataUri.indexOf("#", separator + 1);
+ const data = dataUri.slice(
+ separator + 1,
+ fragment < 0 ? undefined : fragment,
+ );
+
+ const isBase64 = DATA_URI_BASE64_RE.test(metadata);
+ const essence = (
+ isBase64 ? metadata.replace(DATA_URI_BASE64_RE, "") : metadata
+ )
+ .split(";", 1)[0]
+ .trim();
+ // Anything without a slash is not a media type, so `data:base64,...` falls
+ // back to the RFC 2397 default rather than reporting `base64`.
+ const mimeType = essence.includes("/") ? essence : DEFAULT_MIME_TYPE;
+
+ if (!isBase64) {
+ return { bytes: percentDecodeOctets(data), mimeType };
+ }
+ // A base64 payload may carry its own escapes, so `data:audio/wav;base64,
+ // SGVsbG8%3D` has to become `SGVsbG8=` before atob() sees it. The base64
+ // alphabet is ASCII, so decoding the escapes in place is enough.
+ const payload = data.includes("%")
+ ? data.replace(PERCENT_ESCAPE_RE, (_match, hex: string) =>
+ String.fromCharCode(Number.parseInt(hex, 16)),
+ )
+ : data;
+ return { bytes: base64ToBytes(payload), mimeType };
+}
diff --git a/studio/frontend/src/lib/native-files.ts b/studio/frontend/src/lib/native-files.ts
index 48a6bd4ab77..56f28def56e 100644
--- a/studio/frontend/src/lib/native-files.ts
+++ b/studio/frontend/src/lib/native-files.ts
@@ -2,6 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { isTauri } from "@/lib/api-base";
+import { decodeDataUri, isDataUri } from "@/lib/data-uri";
const NATIVE_FILE_NAME_HEADER = "x-unsloth-default-name";
export class DownloadCancelledError extends Error {
@@ -40,6 +41,24 @@ function browserDownload(blob: Blob, filename: string): void {
URL.revokeObjectURL(url);
}
+function browserUrlDownload(url: string, filename: string): void {
+ const anchor = document.createElement("a");
+ anchor.href = url;
+ anchor.download = filename;
+ anchor.rel = "noopener";
+ document.body.appendChild(anchor);
+ anchor.click();
+ anchor.remove();
+}
+
+async function fetchDownload(url: string): Promise<Response> {
+ const response = await fetch(url);
+ if (!response.ok) {
+ throw new Error(`Download failed with status ${response.status}.`);
+ }
+ return response;
+}
+
/** Save through a native chooser in Tauri and retain normal downloads on web. */
export async function downloadFile(
content: string | Blob | Uint8Array,
@@ -76,6 +95,37 @@ export async function downloadFile(
return;
}
+export async function urlToBlob(url: string): Promise<Blob> {
+ if (isDataUri(url)) {
+ const { bytes, mimeType } = decodeDataUri(url);
+ return new Blob([Uint8Array.from(bytes).buffer], { type: mimeType });
+ }
+ return (await fetchDownload(url)).blob();
+}
+
+/** Resolve media before crossing the native save boundary. */
+export async function downloadUrl(
+ url: string,
+ filename: string,
+): Promise<void> {
+ if (isDataUri(url)) {
+ const { bytes, mimeType } = decodeDataUri(url);
+ await downloadFile(bytes, filename, mimeType);
+ return;
+ }
+ if (!isTauri) {
+ browserUrlDownload(url, filename);
+ return;
+ }
+ const response = await fetchDownload(url);
+ const bytes = new Uint8Array(await response.arrayBuffer());
+ await downloadFile(
+ bytes,
+ filename,
+ response.headers.get("content-type") || "application/octet-stream",
+ );
+}
+
/** Open the bounded native chat-import picker. Cancellation returns null. */
export async function pickNativeChatImport(): Promise<NativeChatImport | null> {
if (!isTauri) {
diff --git a/studio/frontend/tests/data-uri.test.ts b/studio/frontend/tests/data-uri.test.ts
new file mode 100644
index 00000000000..65d710e7d2f
--- /dev/null
+++ b/studio/frontend/tests/data-uri.test.ts
@@ -0,0 +1,243 @@
+// 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 { decodeDataUri, isDataUri } from "../src/lib/data-uri.ts";
+
+const INVALID_DATA_URI_RE = /Invalid data URI/;
+const DEFAULT_MIME = "text/plain;charset=US-ASCII";
+
+test("decodes base64 data URIs with their media type", () => {
+ const decoded = decodeDataUri("data:audio/wav;base64,AAH6/w==");
+
+ assert.equal(decoded.mimeType, "audio/wav");
+ assert.deepEqual(Array.from(decoded.bytes), [0, 1, 250, 255]);
+});
+
+test("preserves commas in percent-encoded data URI payloads", () => {
+ const decoded = decodeDataUri("data:text/plain,hello,world%20again");
+
+ assert.equal(decoded.mimeType, "text/plain");
+ assert.equal(new TextDecoder().decode(decoded.bytes), "hello,world again");
+});
+
+test("uses the RFC default media type when it is omitted", () => {
+ const decoded = decodeDataUri("data:,plain%20text");
+
+ assert.equal(decoded.mimeType, "text/plain;charset=US-ASCII");
+ assert.equal(new TextDecoder().decode(decoded.bytes), "plain text");
+});
+
+test("rejects data URIs without a payload separator", () => {
+ assert.throws(
+ () => decodeDataUri("data:image/png;base64"),
+ INVALID_DATA_URI_RE,
+ );
+});
+
+// The expectations below were taken from Chromium, Firefox and WebKit, which
+// all agree: percent-decoding a data URI is byte-oriented, not UTF-8 text.
+
+test("decodes percent escapes that are not valid UTF-8", () => {
+ // decodeURIComponent() throws URIError on these; a browser returns the octets.
+ assert.deepEqual(
+ Array.from(decodeDataUri("data:audio/wav,%FF%00%80").bytes),
+ [255, 0, 128],
+ );
+ assert.deepEqual(
+ Array.from(decodeDataUri("data:application/octet-stream,%FF").bytes),
+ [255],
+ );
+});
+
+test("leaves malformed percent escapes as literal characters", () => {
+ assert.deepEqual(
+ Array.from(decodeDataUri("data:text/plain,%G0").bytes),
+ [37, 71, 48],
+ );
+ assert.deepEqual(
+ Array.from(decodeDataUri("data:text/plain,abc%").bytes),
+ [97, 98, 99, 37],
+ );
+});
+
+test("does not treat a base64x parameter as base64", () => {
+ // The old `/;base64/i` matched inside `;base64x`; the anchored form must not.
+ assert.deepEqual(
+ Array.from(decodeDataUri("data:text/plain;base64x,QUJD").bytes),
+ [81, 85, 74, 68],
+ );
+});
+
+test("percent-decodes a base64 payload before decoding it", () => {
+ // atob() would throw InvalidCharacterError on the escapes.
+ assert.deepEqual(
+ Array.from(decodeDataUri("data:audio/wav;base64,SGVsbG8%3D").bytes),
+ [72, 101, 108, 108, 111],
+ );
+ assert.deepEqual(
+ Array.from(decodeDataUri("data:audio/wav;base64,AAH6%2Fw%3D%3D").bytes),
+ [0, 1, 250, 255],
+ );
+ assert.deepEqual(
+ Array.from(decodeDataUri("data:text/plain;base64,QUJ%44").bytes),
+ [65, 66, 67],
+ );
+});
+
+test("treats base64 as the marker only when it ends the metadata", () => {
+ // A mid-metadata `base64` segment is an ordinary parameter.
+ assert.deepEqual(
+ Array.from(
+ decodeDataUri("data:text/plain;base64;charset=utf-8,SGVsbG8=").bytes,
+ ),
+ [83, 71, 86, 115, 98, 71, 56, 61],
+ );
+ assert.deepEqual(
+ Array.from(decodeDataUri("data:base64,SGVsbG8=").bytes),
+ [83, 71, 86, 115, 98, 71, 56, 61],
+ );
+ assert.deepEqual(
+ Array.from(
+ decodeDataUri("data:text/plain;charset=utf-8;base64,SGVsbG8=").bytes,
+ ),
+ [72, 101, 108, 108, 111],
+ );
+});
+
+test("ignores a URL fragment", () => {
+ assert.deepEqual(
+ Array.from(decodeDataUri("data:text/plain,abc#frag").bytes),
+ [97, 98, 99],
+ );
+ assert.deepEqual(
+ Array.from(decodeDataUri("data:text/plain;base64,SGVsbG8=#frag").bytes),
+ [72, 101, 108, 108, 111],
+ );
+ // An escaped hash is payload, not a fragment.
+ assert.deepEqual(
+ Array.from(decodeDataUri("data:text/plain,abc%23hash").bytes),
+ [97, 98, 99, 35, 104, 97, 115, 104],
+ );
+});
+
+test("falls back to the default media type when there is no slash", () => {
+ assert.equal(decodeDataUri("data:base64,SGVsbG8=").mimeType, DEFAULT_MIME);
+ assert.equal(decodeDataUri("data:;base64,AAA=").mimeType, DEFAULT_MIME);
+ assert.equal(
+ decodeDataUri("data:image/png;base64,QUJD").mimeType,
+ "image/png",
+ );
+});
+
+test("decodes a large base64 payload without stalling", () => {
+ // The 20 MiB attachment cap must not take seconds of blocked UI.
+ const payload = btoa("x".repeat(3 * 1024 * 1024));
+ const started = Date.now();
+ const decoded = decodeDataUri(`data:image/png;base64,${payload}`);
+ assert.equal(decoded.bytes.length, 3 * 1024 * 1024);
+ assert.ok(
+ Date.now() - started < 2000,
+ `decoding took ${Date.now() - started}ms`,
+ );
+});
+
+test("treats the data scheme case-insensitively", () => {
+ // URL schemes are case-insensitive and all three engines render DATA:.
+ assert.ok(isDataUri("DATA:image/png;base64,QUJD"));
+ assert.ok(isDataUri("Data:image/png;base64,QUJD"));
+ assert.ok(isDataUri("data:image/png;base64,QUJD"));
+ assert.ok(!isDataUri("https://example.com/a.png"));
+ assert.deepEqual(
+ Array.from(decodeDataUri("DATA:text/plain;base64,QUJD").bytes),
+ [65, 66, 67],
+ );
+});
+
+test("decodes an escape-heavy payload without stalling", () => {
+ // Encoded SVG text alternates literals and escapes, which used to allocate
+ // a separate array per run.
+ const source = "a%20".repeat(400000);
+ const started = Date.now();
+ const decoded = decodeDataUri(`data:image/svg+xml,${source}`);
+ assert.equal(decoded.bytes.length, 800000);
+ assert.equal(decoded.bytes[0], 97);
+ assert.equal(decoded.bytes[1], 32);
+ assert.ok(
+ Date.now() - started < 2000,
+ `decoding took ${Date.now() - started}ms`,
+ );
+});
+
+test("removes URL tabs and newlines the way the URL parser does", () => {
+ // Firefox and WebKit strip these before parsing, per the URL standard.
+ // Chromium keeps them for a data: URL passed to fetch, so this follows the
+ // standard and the majority.
+ assert.deepEqual(
+ Array.from(decodeDataUri("data:text/plain;base64\n,SGVsbG8=").bytes),
+ [72, 101, 108, 108, 111],
+ );
+ assert.deepEqual(
+ Array.from(decodeDataUri("data:text/plain;base64\t,SGVsbG8=").bytes),
+ [72, 101, 108, 108, 111],
+ );
+ assert.deepEqual(
+ Array.from(decodeDataUri("data:text/plain;bas\ne64,SGVsbG8=").bytes),
+ [72, 101, 108, 108, 111],
+ );
+ assert.deepEqual(
+ Array.from(decodeDataUri("data:text/plain,ab\ncd").bytes),
+ [97, 98, 99, 100],
+ );
+ // An escaped newline is payload, not URL whitespace.
+ assert.deepEqual(
+ Array.from(decodeDataUri("data:text/plain,ab%0Acd").bytes),
+ [97, 98, 10, 99, 100],
+ );
+});
+
+test("trims leading and trailing C0 controls and spaces", () => {
+ // All three engines render ` data:image/png;...` and decode these.
+ assert.ok(isDataUri(" data:text/plain,abc"));
+ assert.ok(isDataUri("\u0000data:text/plain,abc"));
+ assert.ok(isDataUri(" DATA:text/plain,abc"));
+ for (const uri of [
+ " data:text/plain,abc",
+ " data:text/plain,abc",
+ "\u0000data:text/plain,abc",
+ "\u001fdata:text/plain,abc",
+ "data:text/plain,abc ",
+ ]) {
+ assert.deepEqual(Array.from(decodeDataUri(uri).bytes), [97, 98, 99], uri);
+ }
+ // A space inside the payload is content, not URL whitespace.
+ assert.deepEqual(
+ Array.from(decodeDataUri("data:text/plain,a bc").bytes),
+ [97, 32, 98, 99],
+ );
+});
+
+test("detects the scheme past any number of leading controls", () => {
+ // All three engines decode these; a fixed-size prefix window could not.
+ const lead = [" ".repeat(30), "\u0000".repeat(40), " \u0000 \t"];
+ for (const prefix of lead) {
+ assert.ok(
+ isDataUri(`${prefix}data:text/plain,abc`),
+ JSON.stringify(prefix),
+ );
+ assert.deepEqual(
+ Array.from(decodeDataUri(`${prefix}data:text/plain,abc`).bytes),
+ [97, 98, 99],
+ );
+ }
+ // Tabs and newlines are removed inside the scheme too.
+ assert.ok(isDataUri("da\nta:text/plain,abc"));
+ assert.ok(isDataUri("da\tta:text/plain,abc"));
+ // A space is not removed, so this is not a data URL in any engine.
+ assert.ok(!isDataUri("da ta:text/plain,abc"));
+ assert.ok(!isDataUri("https://example.com/a.png"));
+ assert.ok(!isDataUri("dat"));
+ assert.ok(!isDataUri(""));
+});
diff --git a/studio/src-tauri/src/native_file_dialogs.rs b/studio/src-tauri/src/native_file_dialogs.rs
index 1544f5806dd..438367521f8 100644
--- a/studio/src-tauri/src/native_file_dialogs.rs
+++ b/studio/src-tauri/src/native_file_dialogs.rs
@@ -1,6 +1,7 @@
use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
use serde::Serialize;
+use std::borrow::Cow;
use std::fs::{self, File};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
@@ -35,45 +36,78 @@ fn decode_default_file_name(encoded_name: &str) -> Result<String, String> {
Ok(default_file_name(&name))
}
-fn save_filter(file_name: &str) -> (&'static str, Vec<&'static str>) {
+fn filter_extensions<const N: usize>(values: [&str; N]) -> Vec<String> {
+ values.into_iter().map(str::to_string).collect()
+}
+
+fn is_safe_filter_extension(extension: &str) -> bool {
+ !extension.is_empty()
+ && extension.len() <= 32
+ && extension
+ .bytes()
+ .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
+}
+
+fn save_filter(file_name: &str) -> (&'static str, Vec<String>) {
match Path::new(file_name)
.extension()
.and_then(|extension| extension.to_str())
.map(str::to_ascii_lowercase)
.as_deref()
{
- Some("json") => ("JSON", vec!["json"]),
- Some("jsonl") | Some("ndjson") => ("JSON Lines", vec!["jsonl", "ndjson"]),
- Some("csv") => ("CSV", vec!["csv"]),
- Some("md") | Some("markdown") => ("Markdown", vec!["md", "markdown"]),
- Some("html") | Some("htm") => ("HTML", vec!["html", "htm"]),
- Some("py") => ("Python", vec!["py"]),
- Some("sh") => ("Shell script", vec!["sh"]),
- Some("zip") => ("ZIP archive", vec!["zip"]),
+ Some("json") => ("JSON", filter_extensions(["json"])),
+ Some("jsonl") | Some("ndjson") => ("JSON Lines", filter_extensions(["jsonl", "ndjson"])),
+ Some("csv") => ("CSV", filter_extensions(["csv"])),
+ Some("md") | Some("markdown") => ("Markdown", filter_extensions(["md", "markdown"])),
+ Some("html") | Some("htm") => ("HTML", filter_extensions(["html", "htm"])),
+ Some("yaml") | Some("yml") => ("YAML", filter_extensions(["yaml", "yml"])),
+ Some("py") => ("Python", filter_extensions(["py"])),
+ Some("sh") => ("Shell script", filter_extensions(["sh"])),
+ Some("js") | Some("jsx") => ("JavaScript", filter_extensions(["js", "jsx"])),
+ Some("ts") | Some("tsx") => ("TypeScript", filter_extensions(["ts", "tsx"])),
+ Some("sql") => ("SQL", filter_extensions(["sql"])),
+ Some("zip") => ("ZIP archive", filter_extensions(["zip"])),
// Saved chat attachments, not just exports: a name outside the active
// filter can be rejected or silently re-extensioned by the OS dialog.
- Some("txt") | Some("log") => ("Text", vec!["txt", "log"]),
- Some("png") => ("PNG image", vec!["png"]),
- Some("jpg") | Some("jpeg") => ("JPEG image", vec!["jpg", "jpeg"]),
- Some("webp") => ("WebP image", vec!["webp"]),
- Some("gif") => ("GIF image", vec!["gif"]),
- Some("wav") => ("WAV audio", vec!["wav"]),
- Some("mp3") => ("MP3 audio", vec!["mp3"]),
- Some("m4a") | Some("mp4") => ("MPEG-4 audio", vec!["m4a", "mp4"]),
- Some("ogg") | Some("oga") => ("Ogg audio", vec!["ogg", "oga"]),
- Some("flac") => ("FLAC audio", vec!["flac"]),
- Some("webm") => ("WebM audio", vec!["webm"]),
+ Some("txt") | Some("log") => ("Text", filter_extensions(["txt", "log"])),
+ Some("png") => ("PNG image", filter_extensions(["png"])),
+ Some("jpg") | Some("jpeg") => ("JPEG image", filter_extensions(["jpg", "jpeg"])),
+ Some("webp") => ("WebP image", filter_extensions(["webp"])),
+ Some("gif") => ("GIF image", filter_extensions(["gif"])),
+ Some("svg") => ("SVG image", filter_extensions(["svg"])),
+ Some("wav") => ("WAV audio", filter_extensions(["wav"])),
+ Some("mp3") => ("MP3 audio", filter_extensions(["mp3"])),
+ Some("m4a") | Some("mp4") => ("MPEG-4 audio", filter_extensions(["m4a", "mp4"])),
+ Some("ogg") | Some("oga") => ("Ogg audio", filter_extensions(["ogg", "oga"])),
+ Some("flac") => ("FLAC audio", filter_extensions(["flac"])),
+ Some("webm") => ("WebM audio", filter_extensions(["webm"])),
+ Some(extension) if is_safe_filter_extension(extension) => {
+ ("Export file", vec![extension.to_string()])
+ }
_ => (
"Export files",
- vec![
- "json", "jsonl", "ndjson", "csv", "md", "markdown", "html", "htm", "py", "sh",
- "zip", "txt", "log", "png", "jpg", "jpeg", "webp", "gif", "wav", "mp3", "m4a",
- "mp4", "ogg", "oga", "flac", "webm",
- ],
+ filter_extensions([
+ "json", "jsonl", "ndjson", "csv", "md", "markdown", "html", "htm", "yaml", "yml",
+ "py", "sh", "js", "jsx", "ts", "tsx", "sql", "zip", "txt", "log", "png", "jpg",
+ "jpeg", "webp", "gif", "svg", "wav", "mp3", "m4a", "mp4", "ogg", "oga", "flac",
+ "webm",
+ ]),
),
}
}
+fn invoke_body_bytes(body: &tauri::ipc::InvokeBody) -> Option<Cow<'_, [u8]>> {
+ match body {
+ tauri::ipc::InvokeBody::Raw(content) => Some(Cow::Borrowed(content)),
+ tauri::ipc::InvokeBody::Json(value) => value
+ .as_array()?
+ .iter()
+ .map(|item| u8::try_from(item.as_u64()?).ok())
+ .collect::<Option<Vec<_>>>()
+ .map(Cow::Owned),
+ }
+}
+
fn local_dialog_path(path: tauri_plugin_dialog::FilePath) -> Result<PathBuf, String> {
path.into_path()
.map_err(|_| "Only local filesystem paths are supported.".to_string())
@@ -183,17 +217,16 @@ pub async fn save_native_file(
.to_str()
.map_err(|_| "Invalid native export filename.".to_string())?;
let file_name = decode_default_file_name(encoded_name)?;
- let content = match request.body() {
- tauri::ipc::InvokeBody::Raw(content) => content,
- _ => return Err("Native export content must be binary.".to_string()),
- };
+ let content = invoke_body_bytes(request.body())
+ .ok_or_else(|| "Native export content must be binary.".to_string())?;
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, &extensions)
+ .add_filter(filter_name, &extension_refs)
.save_file(move |path| {
let _ = tx.send(path);
});
@@ -202,7 +235,7 @@ pub async fn save_native_file(
.map_err(|_| "Save dialog closed unexpectedly.".to_string())?
.map(local_dialog_path)
.transpose()?;
- save_selected_file(selected_path, content)
+ save_selected_file(selected_path, content.as_ref())
}
#[tauri::command]
@@ -243,12 +276,48 @@ mod tests {
))
}
+ fn assert_save_filter(file_name: &str, name: &str, expected: &[&str]) {
+ let (actual_name, actual_extensions) = save_filter(file_name);
+ assert_eq!(actual_name, name);
+ assert_eq!(
+ actual_extensions
+ .iter()
+ .map(String::as_str)
+ .collect::<Vec<_>>(),
+ expected
+ );
+ }
+
#[test]
fn cancellation_is_quiet_for_save_and_import() {
assert!(save_selected_file(None, b"x").unwrap().is_none());
assert!(read_selected_import(None).unwrap().is_none());
}
+ #[test]
+ fn accepts_raw_and_json_byte_bodies() {
+ let raw = tauri::ipc::InvokeBody::Raw(vec![1, 2, 250]);
+ assert_eq!(
+ invoke_body_bytes(&raw).as_deref(),
+ Some([1, 2, 250].as_slice())
+ );
+
+ let json = tauri::ipc::InvokeBody::Json(serde_json::json!([1, 2, 250]));
+ assert_eq!(
+ invoke_body_bytes(&json).as_deref(),
+ Some([1, 2, 250].as_slice())
+ );
+
+ for value in [
+ serde_json::json!({"content": "hi"}),
+ serde_json::json!([1, 256]),
+ serde_json::json!([1, -2]),
+ ] {
+ let body = tauri::ipc::InvokeBody::Json(value);
+ assert!(invoke_body_bytes(&body).is_none());
+ }
+ }
+
#[test]
fn writes_text_and_binary_exactly() {
// Overwriting must stage the new content before replacing the destination.
@@ -266,40 +335,49 @@ mod tests {
#[test]
fn markdown_exports_use_a_markdown_save_filter() {
- assert_eq!(
- save_filter("message.md"),
- ("Markdown", vec!["md", "markdown"])
- );
+ assert_save_filter("message.md", "Markdown", &["md", "markdown"]);
}
#[test]
fn html_canvas_exports_use_an_html_save_filter() {
- assert_eq!(save_filter("canvas.html"), ("HTML", vec!["html", "htm"]));
- assert_eq!(save_filter("canvas.HTM"), ("HTML", vec!["html", "htm"]));
+ assert_save_filter("canvas.html", "HTML", &["html", "htm"]);
+ assert_save_filter("canvas.HTM", "HTML", &["html", "htm"]);
}
#[test]
fn python_scripts_use_a_python_save_filter() {
- assert_eq!(save_filter("script.py"), ("Python", vec!["py"]));
- assert_eq!(save_filter("script.PY"), ("Python", vec!["py"]));
+ assert_save_filter("script.py", "Python", &["py"]);
+ assert_save_filter("script.PY", "Python", &["py"]);
}
#[test]
fn shell_commands_use_a_shell_save_filter() {
// The terminal card downloads command.sh through the same cell.
- assert_eq!(save_filter("command.sh"), ("Shell script", vec!["sh"]));
- assert_eq!(save_filter("command.SH"), ("Shell script", vec!["sh"]));
+ assert_save_filter("command.sh", "Shell script", &["sh"]);
+ assert_save_filter("command.SH", "Shell script", &["sh"]);
+ }
+
+ #[test]
+ fn browser_generated_exports_keep_their_extension() {
+ assert_save_filter("training.yaml", "YAML", &["yaml", "yml"]);
+ assert_save_filter("snippet.TSX", "TypeScript", &["ts", "tsx"]);
+ assert_save_filter("diagram.svg", "SVG image", &["svg"]);
+ assert_save_filter("snippet.rs", "Export file", &["rs"]);
+
+ let (name, extensions) = save_filter("snippet.bad!");
+ assert_eq!(name, "Export files");
+ assert!(!extensions.iter().any(|extension| extension == "bad!"));
}
#[test]
fn saved_chat_attachments_keep_their_own_extension() {
// Settings > Data saves attachments here; a name outside the filter can
// be rejected or re-extensioned by the OS dialog.
- assert_eq!(save_filter("report.txt"), ("Text", vec!["txt", "log"]));
- assert_eq!(save_filter("photo.PNG"), ("PNG image", vec!["png"]));
- assert_eq!(save_filter("shot.jpeg"), ("JPEG image", vec!["jpg", "jpeg"]));
- assert_eq!(save_filter("clip.wav"), ("WAV audio", vec!["wav"]));
- assert_eq!(save_filter("voice.webm"), ("WebM audio", vec!["webm"]));
+ assert_save_filter("report.txt", "Text", &["txt", "log"]);
+ assert_save_filter("photo.PNG", "PNG image", &["png"]);
+ assert_save_filter("shot.jpeg", "JPEG image", &["jpg", "jpeg"]);
+ assert_save_filter("clip.wav", "WAV audio", &["wav"]);
+ assert_save_filter("voice.webm", "WebM audio", &["webm"]);
}
#[test]
@@ -307,9 +385,13 @@ mod tests {
let (name, extensions) = save_filter("no-extension");
assert_eq!(name, "Export files");
for wanted in [
- "py", "sh", "json", "jsonl", "csv", "md", "html", "zip", "txt", "png", "jpg", "wav",
+ "py", "sh", "js", "ts", "sql", "yaml", "json", "jsonl", "csv", "md", "html", "zip",
+ "txt", "png", "jpg", "svg", "wav",
] {
- assert!(extensions.contains(&wanted), "fallback lost {wanted}");
+ assert!(
+ extensions.iter().any(|extension| extension == wanted),
+ "fallback lost {wanted}"
+ );
}
}
diff --git a/studio/src-tauri/tauri.conf.json b/studio/src-tauri/tauri.conf.json
index ac08e849cca..4a17d593f13 100644
--- a/studio/src-tauri/tauri.conf.json
+++ b/studio/src-tauri/tauri.conf.json
@@ -16,7 +16,7 @@
"app": {
"withGlobalTauri": true,
"security": {
- "csp": "default-src 'self'; connect-src 'self' http://localhost:* ws://localhost:* ws://127.0.0.1:* http://127.0.0.1:* https://huggingface.co https://*.huggingface.co https://datasets-server.huggingface.co; img-src 'self' data: blob: https:; media-src 'self' data: blob: https:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; frame-src 'self' http://localhost:* http://127.0.0.1:*"
+ "csp": "default-src 'self'; connect-src 'self' ipc: http://ipc.localhost http://localhost:* ws://localhost:* ws://127.0.0.1:* http://127.0.0.1:* https://huggingface.co https://*.huggingface.co https://datasets-server.huggingface.co; img-src 'self' data: blob: https:; media-src 'self' data: blob: https:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; frame-src 'self' http://localhost:* http://127.0.0.1:*"
},
"windows": [
{
diff --git a/tests/studio/test_desktop_reliability_frontend_contract.py b/tests/studio/test_desktop_reliability_frontend_contract.py
index 6cccd10cf11..d4bf6f155a1 100644
--- a/tests/studio/test_desktop_reliability_frontend_contract.py
+++ b/tests/studio/test_desktop_reliability_frontend_contract.py
@@ -29,6 +29,10 @@ APP_PROVIDER = FRONTEND / "app/provider.tsx"
CLIPBOARD_FILES = FRONTEND / "features/chat/utils/clipboard-files.ts"
TAURI_CAPABILITIES = REPO / "studio/src-tauri/capabilities/default.json"
CHAT_PAGE = FRONTEND / "features/chat/chat-page.tsx"
+TRAINING_SECTION = FRONTEND / "features/studio/sections/training-section.tsx"
+MARKDOWN_TEXT = FRONTEND / "components/assistant-ui/markdown-text.tsx"
+IMAGE = FRONTEND / "components/assistant-ui/image.tsx"
+AUDIO_PLAYER = FRONTEND / "components/assistant-ui/audio-player.tsx"
def test_file_actions_route_through_native_commands_only_in_tauri():
@@ -104,6 +108,32 @@ def test_chat_exports_await_native_saves_and_markdown_uses_shared_helper():
assert "downloadFile(" in thread
+def test_generated_download_buttons_use_the_native_save_boundary():
+ helper = NATIVE_FILES.read_text(encoding = "utf-8")
+ training = TRAINING_SECTION.read_text(encoding = "utf-8")
+ markdown = MARKDOWN_TEXT.read_text(encoding = "utf-8")
+ image = IMAGE.read_text(encoding = "utf-8")
+ audio = AUDIO_PLAYER.read_text(encoding = "utf-8")
+
+ assert "downloadFile(bytes, filename" in helper
+ assert "browserUrlDownload(url, filename)" in helper
+ assert "if (!isTauri)" in helper
+ assert "downloadFile(yamlStr, filename" in training
+ assert "downloadFile(text, filename" in markdown
+ assert "fallbackExt" in markdown
+ assert 'rust: "rs"' in markdown
+ assert "downloadUrl(part.image, filename)" in image
+ assert "urlToBlob(part.image)" in image
+ assert 'downloadUrl(src, "generated-audio.wav")' in audio
+
+ tauri_config = (REPO / "studio/src-tauri/tauri.conf.json").read_text(encoding = "utf-8")
+ assert "connect-src 'self' ipc: http://ipc.localhost" in tauri_config
+
+ for source in (training, markdown, image, audio):
+ assert 'document.createElement("a")' not in source
+ assert "isDownloadCancelled(error)" in source
+
+
def test_clipboard_file_paste_is_bounded_and_wired_to_both_composers():
helper = CLIPBOARD_FILES.read_text(encoding = "utf-8")
thread = THREAD.read_text(encoding = "utf-8")