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.

fix(studio): keep download approval and saved filenames aligned (#14278)

Nilayca02529687ac
diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.ts
index 0e2f06a1a54..338763af0a1 100644
--- a/studio/frontend/scripts/check-bundle-budget.ts
+++ b/studio/frontend/scripts/check-bundle-budget.ts
@@ -298,8 +298,9 @@ export const BUDGET = {
// The Desktop chat-only install choice (#14245) adds 679 B raw / 205 B transfer (6,842,169 -> 6,842,848 B raw,
// 2,060,319 -> 2,060,524 B transfer against 26e246d407, one machine and build, Node 24, 96 chunks): the
// first-run checkbox lives in the eager startup screen and the Train hint in the eager sidebar. Raised by that.
- transferBytes: 2_061_610,
- rawBytes: 6_846_068,
+ // Explicit browser download names retain the prior startup margin.
+ transferBytes: 2_062_292,
+ rawBytes: 6_847_855,
};
// The chunk count is reported but not budgeted. Splitting a page out of the entry raises it while lowering the
diff --git a/studio/frontend/src/features/browser/download-safety.ts b/studio/frontend/src/features/browser/download-safety.ts
index 8d4798bf736..9d53932ff1c 100644
--- a/studio/frontend/src/features/browser/download-safety.ts
+++ b/studio/frontend/src/features/browser/download-safety.ts
@@ -42,6 +42,64 @@ function runsCode(name: string): boolean {
return DANGEROUS.has(extension.toLowerCase()) || DANGEROUS.has(extension.toUpperCase().toLowerCase());
}
+const PROGRAM_TYPES: Record<string, string> = {
+ "application/x-msdownload": "exe",
+ "application/x-msdos-program": "exe",
+ "application/x-ms-dos-executable": "exe",
+ "application/vnd.microsoft.portable-executable": "exe",
+ "application/x-dosexec": "exe",
+ "application/x-msi": "msi",
+ "application/x-ms-installer": "msi",
+ "application/x-apple-diskimage": "dmg",
+ "application/x-sh": "sh",
+ "application/x-shellscript": "sh",
+ "text/x-sh": "sh",
+ "application/java-archive": "jar",
+ "application/x-java-archive": "jar",
+ "application/vnd.debian.binary-package": "deb",
+ "application/x-debian-package": "deb",
+ "application/x-rpm": "rpm",
+ "application/x-redhat-package-manager": "rpm",
+ "application/hta": "hta",
+ "text/javascript": "js",
+ "application/javascript": "js",
+ "application/x-javascript": "js",
+};
+
+const COMMON_TYPES: Record<string, string> = {
+ "application/pdf": "pdf",
+ "text/plain": "txt",
+ "text/csv": "csv",
+ "text/tab-separated-values": "tsv",
+ "application/json": "json",
+ "text/markdown": "md",
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation": "pptx",
+ "image/png": "png",
+ "image/jpeg": "jpg",
+ "image/gif": "gif",
+ "image/webp": "webp",
+ "image/avif": "avif",
+ "audio/mpeg": "mp3",
+ "audio/wav": "wav",
+ "audio/ogg": "ogg",
+ "audio/flac": "flac",
+ "audio/mp4": "m4a",
+ "video/mp4": "mp4",
+ "video/webm": "webm",
+ "video/quicktime": "mov",
+ "application/zip": "zip",
+ "application/gzip": "gz",
+};
+
+export function withTypeExtension(name: string, contentType: string, includeCommonTypes = false): string {
+ const type = contentType.split(";")[0].trim().toLowerCase();
+ const extension = PROGRAM_TYPES[type] ?? (includeCommonTypes ? COMMON_TYPES[type] : undefined);
+ const stem = name.replace(/^\.+/, "").replace(/[. ]+$/, "");
+ return extension && !/\.[^./\\]+$/.test(stem) ? `${stem || "download"}.${extension}` : name;
+}
+
/** As the desktop app cleans a name before the cut: controls, bidi controls and reserved characters become
* one-byte "_", trailing dots and spaces go. */
function cleaned(name: string): string {
diff --git a/studio/frontend/src/features/browser/downloads.ts b/studio/frontend/src/features/browser/downloads.ts
index cd8d6da64af..3a886eba9e3 100644
--- a/studio/frontend/src/features/browser/downloads.ts
+++ b/studio/frontend/src/features/browser/downloads.ts
@@ -11,7 +11,7 @@ import { type BrowserPage, fetchBrowserPage } from "./api";
import { abandonDownload, beginDownload, finishDownload } from "./download-activity";
import type { DownloadsRule } from "./agent/permissions";
import { approveDownload } from "./download-approval-queue";
-import { isDangerousDownload } from "./download-safety";
+import { isDangerousDownload, withTypeExtension } from "./download-safety";
import { useBrowserHistoryStore } from "./history-store";
import { type SavedNativeDownload, saveNativeDownload } from "./native-downloads";
import { useBrowserPrefsStore } from "./prefs-store";
@@ -69,8 +69,14 @@ function approved(url: string | null, name: string, site?: string, agentRule?: D
return url && isWebUrl(url) ? approveDownload(url, name, site ?? url, agentRule) : Promise.resolve(true);
}
+function downloadName(name: string, contentType: string): string {
+ const typed = withTypeExtension(safeDownloadName(name), contentType, !isTauri);
+ return isTauri ? typed : typed.replace(/^\.+/, "").replace(/[. ]+$/, "") || "download";
+}
+
/** Website files wait for approval first. `target`: a location already picked, null for none; omitted, the dialog opens when Settings asks. */
-export async function saveBrowserDownload(download: BrowserDownload, target?: SaveHandle | null): Promise<void> {
+export async function saveBrowserDownload(given: BrowserDownload, target?: SaveHandle | null): Promise<void> {
+ const download = { ...given, name: downloadName(given.name, given.contentType) };
// Taken now: the fetch, approval and the save dialog can outlast the temporary chat.
const temporary = download.temporary ?? useChatRuntimeStore.getState().incognito;
if (target === undefined) {
@@ -116,7 +122,8 @@ async function writeDownload(
await writable.write(blob);
await writable.close();
} else {
- await downloadFile(blob, name, contentType || undefined);
+ // The browser must not infer an unapproved extension from its MIME registry.
+ await downloadFile(blob.slice(0, blob.size, "application/octet-stream"), name);
}
}
} catch (error) {
@@ -146,7 +153,8 @@ const RESOLVE_BEFORE_ASK_MS = 1000;
/** A fetched link as a file: the server's name, or the page as .html. */
function linkDownload(page: BrowserPage, url: string): BrowserDownload {
if (page.kind === "raw") {
- return { blob: page.blob, name: page.fileName ?? fileNameFromUrl(page.url), contentType: page.contentType, url };
+ const name = downloadName(page.fileName ?? fileNameFromUrl(page.url), page.contentType);
+ return { blob: page.blob, name, contentType: page.contentType, url };
}
const name = fileNameFromUrl(page.url);
return {
diff --git a/studio/frontend/tests/browser-settings.test.ts b/studio/frontend/tests/browser-settings.test.ts
index e7295a0522b..4248fc0ab4f 100644
--- a/studio/frontend/tests/browser-settings.test.ts
+++ b/studio/frontend/tests/browser-settings.test.ts
@@ -680,6 +680,154 @@ test("a file a page sends the tab to is asked about for that page, not the file'
store.closeTab(tabId);
});
+test("a program sent with no extension asks under the name it saves as, whatever the site's answer", async () => {
+ const { saveBrowserDownload, saveLinkAs } = await import("../src/features/browser/downloads.ts");
+ const { answerDownload, useApprovalStore } = await import("../src/features/browser/download-approval-queue.ts");
+ const { useDownloadSitesStore } = await import("../src/features/browser/download-sites-store.ts");
+ const nextAsked = async () => {
+ for (let i = 0; i < 50 && useApprovalStore.getState().queue.length === 0; i++) {
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ }
+ return useApprovalStore.getState().queue[0];
+ };
+ const save = async (name: string, contentType: string) => {
+ const saving = saveBrowserDownload({ blob: new Blob(["MZ"], { type: contentType }), name, contentType, url: `https://a.example/${name}` });
+ const asked = await nextAsked();
+ if (asked) answerDownload(asked, false, false);
+ await saving;
+ return asked && [asked.name, asked.dangerous];
+ };
+ const prefs = useBrowserPrefsStore.getState();
+ const g = globalThis as { showSaveFilePicker?: unknown; __authFetch?: unknown };
+ try {
+ assert.deepEqual(await save("report", "application/pdf"), ["report.pdf", false]);
+ assert.deepEqual(await save("notes.txt", "application/x-msdownload"), ["notes.txt", false]);
+
+ useDownloadSitesStore.getState().setSite("https://a.example", "allow");
+ assert.deepEqual(await save("update", "application/x-msdownload"), ["update.exe", true]);
+ assert.deepEqual(await save("Installer", "application/x-apple-diskimage"), ["Installer.dmg", true]);
+ assert.deepEqual(await save("install", "text/x-sh"), ["install.sh", true]);
+ assert.deepEqual(await save("loader", "text/javascript; charset=utf-8"), ["loader.js", true]);
+ assert.deepEqual(await save(".install", "text/x-sh"), ["install.sh", true]);
+ assert.deepEqual(await save("update. ", "application/x-msdownload"), ["update.exe", true]);
+ assert.deepEqual(await save("...", "text/x-sh"), ["download.sh", true]);
+
+ prefs.setAskWhereToSave(true);
+ g.showSaveFilePicker = async () => {
+ throw new DOMException("no picker here", "NotAllowedError");
+ };
+ g.__authFetch = async () =>
+ new Response(new Blob(["MZ"]), {
+ headers: { "Content-Type": "application/x-msdownload; charset=binary", "X-Unsloth-Browser-Filename": "setup" },
+ });
+ const linked = saveLinkAs("https://a.example/download");
+ const asked = await nextAsked();
+ assert.deepEqual(asked && [asked.name, asked.dangerous], ["setup.exe", true]);
+ answerDownload(asked, false, false);
+ await linked;
+ } finally {
+ delete g.showSaveFilePicker;
+ delete g.__authFetch;
+ prefs.setAskWhereToSave(false);
+ useApprovalStore.setState({ queue: [] });
+ useDownloadSitesStore.getState().setSite("https://a.example", null);
+ }
+});
+
+test("ordinary MIME suffixes are browser-only while native program suffixes still apply", async () => {
+ const { withTypeExtension } = await import("../src/features/browser/download-safety.ts");
+ for (const name of [".gitignore", ".env", "report"]) {
+ assert.equal(withTypeExtension(name, "text/plain"), name);
+ }
+ assert.equal(withTypeExtension("report", "application/pdf"), "report");
+ assert.equal(withTypeExtension("update", "application/x-msdownload"), "update.exe");
+});
+
+test("browser saves keep the approved name without MIME inference, including agent downloads", async () => {
+ const { saveBrowserDownload } = await import("../src/features/browser/downloads.ts");
+ const { answerDownload, useApprovalStore } = await import("../src/features/browser/download-approval-queue.ts");
+ const { useDownloadSitesStore } = await import("../src/features/browser/download-sites-store.ts");
+ const prefs = useBrowserPrefsStore.getState();
+ const previous = { ...prefs };
+ const oldDocument = Object.getOwnPropertyDescriptor(globalThis, "document");
+ const oldTimer = window.setTimeout;
+ const create = URL.createObjectURL;
+ const revoke = URL.revokeObjectURL;
+ let transport: Blob | undefined;
+ const saved: { name: string; blob: Blob }[] = [];
+ Object.assign(globalThis, {
+ document: {
+ body: { appendChild() {} },
+ createElement: () => {
+ const anchor = { href: "", download: "", click: () => saved.push({ name: anchor.download, blob: transport! }), remove() {} };
+ return anchor;
+ },
+ },
+ });
+ Object.assign(window, { setTimeout: () => 0 });
+ URL.createObjectURL = (blob) => { transport = blob as Blob; return "blob:test"; };
+ URL.revokeObjectURL = () => {};
+ const cases: [string, string, string, boolean][] = [
+ ["update", "application/x-msdownload", "update.exe", true],
+ ["Installer", "application/x-apple-diskimage", "Installer.dmg", true],
+ ["install", "text/x-sh", "install.sh", true],
+ ["loader", "Application/X-MSDownload; charset=binary", "loader.exe", true],
+ [".install.sh", "text/x-sh", "install.sh", true],
+ ["update. ", "application/x-msdownload", "update.exe", true],
+ ["update.exe. ", "application/octet-stream", "update.exe", true],
+ ["report.pdf", "application/x-msdownload", "report.pdf", false],
+ ["setup.exe.txt", "application/x-msdownload", "setup.exe.txt", false],
+ ["x\u202efdp.exe", "application/octet-stream", "x_fdp.exe", true],
+ ["update", "application/octet-stream", "update", false],
+ ["update", "", "update", false],
+ ["profile", "application/x-apple-aspen-config", "profile", false],
+ ["report", "application/pdf", "report.pdf", false],
+ ["picture", "image/png", "picture.png", false],
+ ["data", "Application/JSON; charset=utf-8", "data.json", false],
+ ["report.txt", "application/pdf", "report.txt", false],
+ ["notes.txt", "text/x-sh", "notes.txt", false],
+ ];
+ try {
+ prefs.setAskWhereToSave(false);
+ prefs.setSaveDownloadHistory(true);
+ for (const mode of ["site", "setting", "agent"]) {
+ useDownloadSitesStore.getState().setSite("https://a.example", mode === "site" ? "allow" : null);
+ prefs.setAskBeforeDownloading(mode !== "setting");
+ for (const [name, contentType, expected, dangerous] of cases) {
+ const blob = new Blob(["MZ harmless bytes"], { type: contentType || "application/x-msdownload" });
+ const count = saved.length;
+ const saving = saveBrowserDownload({ blob, name, contentType, url: "https://a.example/download", temporary: false, agentRule: mode === "agent" ? "allow" : null });
+ const asked = useApprovalStore.getState().queue[0];
+ assert.equal(Boolean(asked), dangerous, `${mode}: ${name} (${contentType})`);
+ if (asked) {
+ assert.deepEqual([asked.name, asked.dangerous], [expected, true]);
+ assert.equal(saved.length, count);
+ answerDownload(asked, true, false);
+ }
+ await saving;
+ assert.equal(saved.length, count + 1);
+ assert.equal(saved.at(-1)?.name, expected);
+ assert.equal(saved.at(-1)?.blob.type, "application/octet-stream");
+ assert.equal(await saved.at(-1)!.blob.text(), await blob.text());
+ assert.equal(blob.type, (contentType || "application/x-msdownload").toLowerCase());
+ const recorded = useBrowserHistoryStore.getState().downloads[0];
+ assert.deepEqual([recorded.name, recorded.contentType], [expected, contentType]);
+ }
+ }
+ } finally {
+ if (oldDocument) Object.defineProperty(globalThis, "document", oldDocument);
+ else Reflect.deleteProperty(globalThis, "document");
+ window.setTimeout = oldTimer;
+ URL.createObjectURL = create;
+ URL.revokeObjectURL = revoke;
+ prefs.setAskWhereToSave(previous.askWhereToSave);
+ prefs.setAskBeforeDownloading(previous.askBeforeDownloading);
+ prefs.setSaveDownloadHistory(previous.saveDownloadHistory);
+ useDownloadSitesStore.getState().setSite("https://a.example", null);
+ for (const request of useApprovalStore.getState().queue) answerDownload(request, false, false);
+ }
+});
+
test("Save link as asks again when the file it named by the address turns out to run code", async () => {
const { saveLinkAs } = await import("../src/features/browser/downloads.ts");
const { answerDownload, useApprovalStore } = await import("../src/features/browser/download-approval-queue.ts");