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.

Studio: save files from download buttons inside browser panel pages (#14285)

Nilay8e95c167f258
diff --git a/studio/backend/routes/browser.py b/studio/backend/routes/browser.py
index e1902965e4b..41b4391928b 100644
--- a/studio/backend/routes/browser.py
+++ b/studio/backend/routes/browser.py
@@ -51,7 +51,8 @@ BROWSER_PRINT_PATH = "/api/browser/print"
KIND_HEADER = "X-Unsloth-Browser-Kind"
URL_HEADER = "X-Unsloth-Browser-Url"
NAME_HEADER = "X-Unsloth-Browser-Filename"
-EXPOSED_HEADERS = (KIND_HEADER, URL_HEADER, NAME_HEADER)
+ATTACHMENT_HEADER = "X-Unsloth-Browser-Attachment"
+EXPOSED_HEADERS = (KIND_HEADER, URL_HEADER, NAME_HEADER, ATTACHMENT_HEADER)
_MAX_BROWSER_FETCH_BYTES = 50 * 1024 * 1024
# HTML goes into srcdoc and the page cache; more would stall the renderer.
@@ -457,6 +458,7 @@ _FRAME_HTML = r"""<!doctype html>
const navigate = (raw, newTab, background) => {
const url = resolve(raw);
if (!url) return;
+ if (/^(?:blob|data):/i.test(url)) { fileAt(url, "").then((file) => file && post({ type: "download", ...file })); return; }
if (!/^https?:/i.test(url)) { post({ type: "external", url }); return; }
if (!newTab && samePage(url) && new URL(url).hash) { followHash(new URL(url).hash); return; }
// Relative links in a local file can't be reached.
@@ -545,9 +547,18 @@ _FRAME_HTML = r"""<!doctype html>
else navigate(event.destination.url, false);
});
}
+ // A blank popup the page then points somewhere (FileSaver.js sends it the file): open or save that.
+ const blankPopup = () => {
+ // Pointed there after the click's activation ran out, a new tab would be refused: open it here instead.
+ const go = (url) => navigate(String(url), navigator.userActivation?.isActive !== false);
+ const location = { set href(url) { go(url); }, assign: go, replace: go };
+ return { closed: false, document: { title: "", body: {} }, get location() { return location; }, set location(url) { go(url); }, close() {}, focus() {} };
+ };
// Popup blocker: only open tabs on user activation.
window.open = (url) => {
- if (url && navigator.userActivation?.isActive !== false) navigate(String(url), true);
+ const target = url == null ? "" : String(url).trim();
+ if (!target || /^about:blank$/i.test(target)) return blankPopup();
+ if (/^(?:blob|data):/i.test(target) || navigator.userActivation?.isActive !== false) navigate(target, true);
return null;
};
@@ -585,6 +596,16 @@ _FRAME_HTML = r"""<!doctype html>
if (!cancelled) action();
});
};
+ const fileAt = (raw, name) =>
+ nativeFetch(raw).then((response) => response.blob()).then((blob) => ({ name: name || "download", blob }), () => null);
+ // Read at the click: a page may revoke a blob: URL as soon as its click returns.
+ const fileFrom = (link, raw) =>
+ link.hasAttribute("download") && /^(?:blob|data):/i.test(raw) ? fileAt(raw, link.getAttribute("download")) : null;
+ const siteFile = (link, raw) => {
+ if (!link.hasAttribute("download") || raw.startsWith("#")) return null;
+ const url = resolve(raw);
+ try { return url && /^https?:/i.test(url) && new URL(url).origin === new URL(pageUrl).origin ? url : null; } catch { return null; }
+ };
const onLinkClick = (event) => {
const link = linkFrom(event);
if (!link) return;
@@ -592,7 +613,24 @@ _FRAME_HTML = r"""<!doctype html>
if (/^javascript:/i.test(raw)) return;
const modified = event.button === 1 || event.metaKey || event.ctrlKey || event.shiftKey;
if (!raw.startsWith("#")) post({ type: "linkClick", url: resolve(raw) });
+ const name = link.getAttribute("download");
+ let file = fileFrom(link, raw);
unlessCancelled(event, () => {
+ // The page's own click handler may have set the file; a rename keeps the bytes already read.
+ const now = (link.getAttribute("href") || "").trim();
+ const final = link.getAttribute("download");
+ if (now !== raw || !file) {
+ if (now !== raw || final !== name) file = fileFrom(link, now);
+ } else if (final !== name) file = final === null ? null : file.then((got) => got && { ...got, name: final || "download" });
+ if (file) {
+ file.then((download) => download && post({ type: "download", ...download }));
+ return;
+ }
+ const url = siteFile(link, now);
+ if (url) {
+ post({ type: "download", url, name: final || "" });
+ return;
+ }
// Keep "#" links on the page; against <base> they would navigate.
if (raw.startsWith("#")) {
if (raw.length > 1) followHash(raw);
@@ -603,6 +641,18 @@ _FRAME_HTML = r"""<!doctype html>
};
document.addEventListener("click", onLinkClick, true);
document.addEventListener("auxclick", (event) => { if (event.button === 1) onLinkClick(event); }, true);
+ // A script's click on a download link outside the document (FileSaver.js) never reaches the listener above.
+ const clickDetached = (anchor, click) => {
+ if (!(anchor instanceof HTMLAnchorElement) || anchor.isConnected || !anchor.hasAttribute("download")) return click();
+ anchor.addEventListener("click", onLinkClick);
+ try { return click(); } finally { anchor.removeEventListener("click", onLinkClick); }
+ };
+ const anchorClick = HTMLAnchorElement.prototype.click;
+ HTMLAnchorElement.prototype.click = function () { clickDetached(this, () => anchorClick.call(this)); };
+ const dispatch = EventTarget.prototype.dispatchEvent;
+ EventTarget.prototype.dispatchEvent = function (event) {
+ return event?.type === "click" ? clickDetached(this, () => dispatch.call(this, event)) : dispatch.call(this, event);
+ };
const submitForm = (form, submitter) => {
const method = ((submitter && submitter.getAttribute("formmethod")) || form.getAttribute("method") || "get").toLowerCase();
@@ -1806,6 +1856,14 @@ def _attachment_name(meta: dict) -> Optional[str]:
return name if name.strip(".") else None
+def _is_attachment(meta: dict) -> bool:
+ disposition = next(
+ (value for key, value in meta.get("headers") or () if key.lower() == "content-disposition"),
+ "",
+ )
+ return disposition.split(";", 1)[0].strip().lower() == "attachment"
+
+
def _build_response(
url: str,
error: Optional[str],
@@ -1831,7 +1889,7 @@ def _build_response(
raise HTTPException(status_code = 502, detail = error)
final_url = meta.get("url") or url
- if is_html:
+ if is_html and (error is not None or not _is_attachment(meta)):
if len(body) > _MAX_BROWSER_HTML_BYTES:
raise HTTPException(
status_code = 502,
@@ -1873,6 +1931,7 @@ def _build_response(
# never rendered on Studio's origin
"Content-Security-Policy": "sandbox",
**({NAME_HEADER: quote(name, safe = "")} if (name := _attachment_name(meta)) else {}),
+ **({ATTACHMENT_HEADER: "1"} if _is_attachment(meta) else {}),
},
)
diff --git a/studio/backend/tests/test_browser_routes.py b/studio/backend/tests/test_browser_routes.py
index 74d0a3db46d..8419db3a508 100644
--- a/studio/backend/tests/test_browser_routes.py
+++ b/studio/backend/tests/test_browser_routes.py
@@ -467,6 +467,39 @@ def test_a_download_keeps_the_servers_file_name(monkeypatch):
assert browser_mod.NAME_HEADER in browser_mod.EXPOSED_HEADERS
+ "disposition, attachment",
+ [
+ ("attachment; filename=x.csv", True),
+ ('Attachment ; filename="x.csv"', True),
+ ("inline; filename=x.csv", False),
+ (None, False),
+ ],
+)
+def test_an_attachment_is_marked_so_the_panel_saves_it(monkeypatch, disposition, attachment):
+ headers = [("Content-Type", "text/csv")] + (
+ [("Content-Disposition", disposition)] if disposition else []
+ )
+ meta = {"url": "https://example.com/export", "headers": headers}
+ _fetch(monkeypatch, (None, b"a,b\n1,2\n", "text/csv"), meta)
+ response = _call()
+ assert response.headers["x-unsloth-browser-kind"] == "raw"
+ assert (response.headers.get("x-unsloth-browser-attachment") == "1") is attachment
+ assert browser_mod.ATTACHMENT_HEADER in browser_mod.EXPOSED_HEADERS
+
+
+def test_an_html_attachment_is_saved_not_shown(monkeypatch):
+ page = b"<!doctype html><html><head><base href=/x/></head><body>report</body></html>"
+ headers = [("Content-Disposition", 'attachment; filename="report.html"')]
+ meta = {"url": "https://example.com/export", "headers": headers, "filename": "report.html"}
+ _fetch(monkeypatch, (None, page, "text/html"), meta)
+ response = _call()
+ assert response.headers["x-unsloth-browser-kind"] == "raw"
+ assert response.headers["x-unsloth-browser-attachment"] == "1"
+ assert response.headers["x-unsloth-browser-filename"] == "report.html"
+ assert response.body == page
+
+
def test_fetch_arguments(monkeypatch):
calls = _fetch(monkeypatch, (None, b"<html></html>", "text/html"))
_call(method = "POST", body = "q=a+b", max_bytes = 4096)
diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.ts
index a5f3367f92f..dc0e5608d05 100644
--- a/studio/frontend/scripts/check-bundle-budget.ts
+++ b/studio/frontend/scripts/check-bundle-budget.ts
@@ -322,8 +322,11 @@ export const BUDGET = {
// Raised to that build plus the same 160 B raw / 189 B transfer margin.
// Slider tracks round to whole screen pixels at any zoom: theme-boot.js publishes --device-px before first
// paint, 1,501 -> 1,847 B (served uncompressed, so 346 B raw and transfer). Raised by that, same margin.
- transferBytes: 2_067_227,
- rawBytes: 6_864_038,
+ // Main at dcf5c4009 measures 6,870,312 B raw / 2,068,954 B transfer, already over the line above. Browser panel
+ // page downloads add 1,468 B raw / 354 B transfer on top (6,871,780 B raw, 2,069,308 B transfer, one machine and
+ // build, Node 24, 97 chunks). Raised to that build plus the same 160 B raw / 189 B transfer margin.
+ transferBytes: 2_069_497,
+ rawBytes: 6_871_940,
};
// 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/api.ts b/studio/frontend/src/features/browser/api.ts
index d1e4be4237c..f138c34e918 100644
--- a/studio/frontend/src/features/browser/api.ts
+++ b/studio/frontend/src/features/browser/api.ts
@@ -17,7 +17,14 @@ export type BrowserPage =
html: string;
refresh: { delay: number; url: string } | null;
}
- | { kind: "raw"; url: string; blob: Blob; contentType: string; /** the server's download name. */ fileName?: string };
+ | {
+ kind: "raw";
+ url: string;
+ blob: Blob;
+ contentType: string;
+ fileName?: string;
+ attachment?: boolean;
+ };
export type BrowserRequest = {
url: string;
@@ -94,6 +101,7 @@ export async function fetchBrowserPage(request: BrowserRequest, signal: AbortSig
blob,
contentType: response.headers.get("Content-Type") ?? blob.type,
fileName,
+ ...(response.headers.get("X-Unsloth-Browser-Attachment") === "1" && { attachment: true }),
};
}
diff --git a/studio/frontend/src/features/browser/download-safety.ts b/studio/frontend/src/features/browser/download-safety.ts
index 9d53932ff1c..0675a70298f 100644
--- a/studio/frontend/src/features/browser/download-safety.ts
+++ b/studio/frontend/src/features/browser/download-safety.ts
@@ -91,6 +91,36 @@ const COMMON_TYPES: Record<string, string> = {
"video/quicktime": "mov",
"application/zip": "zip",
"application/gzip": "gz",
+ "image/svg+xml": "svg",
+ "image/bmp": "bmp",
+ "image/tiff": "tiff",
+ "image/x-icon": "ico",
+ "image/vnd.microsoft.icon": "ico",
+ "image/heic": "heic",
+ "application/epub+zip": "epub",
+ "application/xml": "xml",
+ "text/xml": "xml",
+ "application/rtf": "rtf",
+ "text/rtf": "rtf",
+ "text/calendar": "ics",
+ "application/msword": "doc",
+ "application/vnd.ms-excel": "xls",
+ "application/vnd.ms-powerpoint": "ppt",
+ "application/vnd.oasis.opendocument.text": "odt",
+ "application/vnd.oasis.opendocument.spreadsheet": "ods",
+ "application/vnd.oasis.opendocument.presentation": "odp",
+ "application/x-7z-compressed": "7z",
+ "application/x-tar": "tar",
+ "application/vnd.rar": "rar",
+ "application/x-rar-compressed": "rar",
+ "application/x-bzip2": "bz2",
+ "application/x-xz": "xz",
+ "application/zstd": "zst",
+ "audio/webm": "webm",
+ "font/woff": "woff",
+ "font/woff2": "woff2",
+ "font/ttf": "ttf",
+ "font/otf": "otf",
};
export function withTypeExtension(name: string, contentType: string, includeCommonTypes = false): string {
diff --git a/studio/frontend/src/features/browser/downloads.ts b/studio/frontend/src/features/browser/downloads.ts
index 3a886eba9e3..123670d9218 100644
--- a/studio/frontend/src/features/browser/downloads.ts
+++ b/studio/frontend/src/features/browser/downloads.ts
@@ -74,6 +74,37 @@ function downloadName(name: string, contentType: string): string {
return isTauri ? typed : typed.replace(/^\.+/, "").replace(/[. ]+$/, "") || "download";
}
+const SAVE_PROMPTS = 3;
+let savePrompts = 0;
+
+function offerSave(name: string, save: () => Promise<void>, id?: string): void {
+ const locale = getLocale();
+ toast(translate("browser.downloadPrompt.ready", { name: safeDownloadName(name) }, locale), {
+ id,
+ action: { label: translate("browser.downloadPrompt.save", {}, locale), onClick: () => void save() },
+ });
+}
+
+const nextPrompt = () => `page-download-${savePrompts++ % SAVE_PROMPTS}`;
+
+export function saveBrowserDownloadOnClick(download: BrowserDownload): void {
+ const temporary = download.temporary ?? useChatRuntimeStore.getState().incognito;
+ offerSave(downloadName(download.name, download.contentType), () => saveBrowserDownload({ ...download, temporary }), nextPrompt());
+}
+
+type LinkedFile = Pick<BrowserDownload, "site" | "temporary"> & { agentRule: (fileUrl: string) => DownloadsRule | null };
+
+export function saveLinkedFile(url: string, name: string, file: LinkedFile, askFirst = false): void {
+ const temporary = file.temporary ?? useChatRuntimeStore.getState().incognito;
+ const save = () =>
+ fetchBrowserPage({ url }, new AbortController().signal).then(
+ (page) => saveBrowserDownload({ ...linkDownload(page, url, name), site: file.site, temporary, agentRule: file.agentRule(page.url) }),
+ (error: unknown) => void toast.error(error instanceof Error ? error.message : String(error)),
+ );
+ if (askFirst) offerSave(name || fileNameFromUrl(url), save, nextPrompt());
+ else void save();
+}
+
/** 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(given: BrowserDownload, target?: SaveHandle | null): Promise<void> {
const download = { ...given, name: downloadName(given.name, given.contentType) };
@@ -83,13 +114,7 @@ export async function saveBrowserDownload(given: BrowserDownload, target?: SaveH
if (!(await approved(download.url, download.name, download.site, download.agentRule))) return;
// A save dialog needs a fresh click; a late approval waits for a click on Save instead.
if (saveNeedsClick()) {
- const locale = getLocale();
- toast(translate("browser.downloadPrompt.ready", { name: safeDownloadName(download.name) }, locale), {
- action: {
- label: translate("browser.downloadPrompt.save", {}, locale),
- onClick: () => void writeDownload(download, undefined, temporary),
- },
- });
+ offerSave(download.name, () => writeDownload(download, undefined, temporary));
return;
}
}
@@ -150,13 +175,12 @@ async function writeDownload(
// Well inside the ~5 s a click lets a page open the save dialog.
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 {
+function linkDownload(page: BrowserPage, url: string, linkName = ""): BrowserDownload {
if (page.kind === "raw") {
- const name = downloadName(page.fileName ?? fileNameFromUrl(page.url), page.contentType);
+ const name = downloadName(page.fileName ?? (linkName || fileNameFromUrl(page.url)), page.contentType);
return { blob: page.blob, name, contentType: page.contentType, url };
}
- const name = fileNameFromUrl(page.url);
+ const name = linkName || fileNameFromUrl(page.url);
return {
blob: new Blob([withBaseUrl(page.html, page.base)], { type: "text/html" }),
name: /\.html?$/i.test(name) ? name : `${name}.html`,
diff --git a/studio/frontend/src/features/browser/file-kind.ts b/studio/frontend/src/features/browser/file-kind.ts
index 176ae426978..6b7a2344c3f 100644
--- a/studio/frontend/src/features/browser/file-kind.ts
+++ b/studio/frontend/src/features/browser/file-kind.ts
@@ -52,3 +52,7 @@ export function canShowFile(name: string, contentType: string): boolean {
if (documentKind(name, contentType) || mediaKind(name, contentType)) return true;
return TEXT_TYPE.test(contentType) || TEXT_NAME.test(name) || HTML_NAME.test(name) || !contentType;
}
+
+export function savesFile(name: string, contentType: string, attachment = false): boolean {
+ return attachment || !canShowFile(name, contentType);
+}
diff --git a/studio/frontend/src/features/browser/file-view.tsx b/studio/frontend/src/features/browser/file-view.tsx
index f79d8539a3c..893d2fa4342 100644
--- a/studio/frontend/src/features/browser/file-view.tsx
+++ b/studio/frontend/src/features/browser/file-view.tsx
@@ -186,6 +186,7 @@ export function FileView({
scale = 1,
tabId,
reloadNonce = 0,
+ saved = false,
}: {
blob: Blob;
name: string;
@@ -194,10 +195,11 @@ export function FileView({
scale?: number;
tabId?: string;
reloadNonce?: number;
+ saved?: boolean;
}) {
const t = useT();
- const media = plainText ? null : mediaKind(name, contentType);
- const docKind = plainText ? null : documentKind(name, contentType);
+ const media = plainText || saved ? null : mediaKind(name, contentType);
+ const docKind = plainText || saved ? null : documentKind(name, contentType);
const svg = media === "image" && (/^image\/svg\+xml\b/i.test(contentType) || /\.svg$/i.test(name));
const src = useObjectUrl(blob, media !== null, svg);
const [failed, setFailed] = useState(false);
@@ -249,7 +251,7 @@ export function FileView({
</div>
);
}
- if (plainText || canShowFile(name, contentType)) {
+ if (!saved && (plainText || canShowFile(name, contentType))) {
return (
<TextFile
blob={blob}
diff --git a/studio/frontend/src/features/browser/frame-message.ts b/studio/frontend/src/features/browser/frame-message.ts
index 216957ed13e..a87eb3228ad 100644
--- a/studio/frontend/src/features/browser/frame-message.ts
+++ b/studio/frontend/src/features/browser/frame-message.ts
@@ -14,6 +14,8 @@ export type FrameMessage =
body?: string;
}
| { type: "external"; url: string }
+ | { type: "download"; name: string; blob: Blob; askFirst?: true }
+ | { type: "download"; name: string; url: string; askFirst?: true }
| { type: "loaded"; title: string; favicon: string | null }
| { type: "title"; title: string }
| { type: "url"; url: string }
@@ -179,6 +181,12 @@ function pageRequest(message: Record<string, unknown>): PageRequest | null {
return { url, method, headers, body, redirect: redirect as RedirectMode, integrity };
}
+function fileName(value: unknown): string | null {
+ if (typeof value !== "string" || value.length <= MAX_TITLE_CHARS) return text(value, MAX_TITLE_CHARS);
+ const extension = /\.[^./\\]{1,32}$/.exec(value.slice(-33))?.[0] ?? "";
+ return value.slice(0, MAX_TITLE_CHARS - extension.length).replace(/[\uD800-\uDBFF]$/, "") + extension;
+}
+
/** A message from a page, checked field by field: pages can post anything. */
export function parseFrameMessage(data: unknown): FrameMessage | null {
if (!data || typeof data !== "object") return null;
@@ -202,6 +210,14 @@ export function parseFrameMessage(data: unknown): FrameMessage | null {
const url = text(message.url, MAX_URL_CHARS);
return url ? { type: message.type, url } : null;
}
+ case "download": {
+ const name = fileName(message.name);
+ if (message.blob === undefined) {
+ const url = text(message.url, MAX_URL_CHARS);
+ return url && name !== null ? { type: "download", name, url } : null;
+ }
+ return name && message.blob instanceof Blob ? { type: "download", name, blob: message.blob } : null;
+ }
case "loaded":
return { type: "loaded", title: title(message.title), favicon: text(message.favicon, MAX_URL_CHARS) };
case "title":
@@ -271,3 +287,24 @@ export const frameNotice = (type: "upload" | "scriptNavigation" | "needsBrowser"
id: `browser-${type}-${tabId}`,
...(type === "needsBrowser" && { duration: Number.POSITIVE_INFINITY }),
});
+
+const isUserAction = (message: FrameMessage) =>
+ (message.type === "navigate" && message.newTab === true) ||
+ message.type === "external" ||
+ message.type === "download" ||
+ message.type === "shortcut";
+
+// Activation outlives the click that loaded the page, so user actions are also rate limited, per page.
+const USER_ACTION_INTERVAL_MS = 1000;
+
+export function userActionGate(): (message: FrameMessage, active: boolean, now: number) => FrameMessage | null {
+ let lastUserAction = Number.NEGATIVE_INFINITY;
+ return (message, active, now) => {
+ if (!isUserAction(message)) return message;
+ if (active && now - lastUserAction >= USER_ACTION_INTERVAL_MS) {
+ lastUserAction = now;
+ return message;
+ }
+ return message.type === "download" ? { ...message, askFirst: true } : null;
+ };
+}
diff --git a/studio/frontend/src/features/browser/page-frame.tsx b/studio/frontend/src/features/browser/page-frame.tsx
index 37b7d012ec9..e8e3510d2b7 100644
--- a/studio/frontend/src/features/browser/page-frame.tsx
+++ b/studio/frontend/src/features/browser/page-frame.tsx
@@ -3,7 +3,7 @@
import { useEffect, useRef, useState } from "react";
import { browserFrameUrl, type PageResponse, requestForPage } from "./api";
-import { type AnnotateEvent, type FrameMessage, parseFrameMessage } from "./frame-message";
+import { type AnnotateEvent, type FrameMessage, parseFrameMessage, userActionGate } from "./frame-message";
import { pageRequests } from "./page-requests";
import {
onPageStorageClear,
@@ -106,15 +106,6 @@ export function sendFrameCommand(tabId: string, command: FrameCommand): boolean
return true;
}
-// Messages that open tabs or apps, or run shortcuts. Pages can post anything, so check them here.
-const isUserAction = (message: FrameMessage) =>
- (message.type === "navigate" && message.newTab === true) ||
- message.type === "external" ||
- message.type === "shortcut";
-
-// Activation outlives the click that loaded the page, so user actions are also rate limited, per page.
-const USER_ACTION_INTERVAL_MS = 1000;
-
/** Recent user activation in the focused frame; without the API, focus opens a tab but never the system browser. */
function userActive(frame: HTMLIFrameElement, message: FrameMessage): boolean {
if (document.activeElement !== frame) return false;
@@ -166,7 +157,7 @@ export function PageFrame({
// A page loads and leaves once; repeats are spam.
let loaded = false;
let left = false;
- let lastUserAction = Number.NEGATIVE_INFINITY;
+ const userAction = userActionGate();
// The page's requests to its own site, answered through the shell, which relays to the page.
const requests = pageRequests(
requestForPage,
@@ -215,13 +206,8 @@ export function PageFrame({
return;
}
if (message.type === "typed" && left) return;
- if (isUserAction(message)) {
- if (!userActive(frame, message)) return;
- // Shortcuts too: a script can queue many before the first one moves focus off the page.
- const now = performance.now();
- if (now - lastUserAction < USER_ACTION_INTERVAL_MS) return;
- lastUserAction = now;
- }
+ message = userAction(message, userActive(frame, message), performance.now());
+ if (!message) return;
if (message.type === "loaded") {
if (loaded) message = { type: "title", title: message.title };
loaded = true;
diff --git a/studio/frontend/src/features/browser/tab-view.tsx b/studio/frontend/src/features/browser/tab-view.tsx
index e574d3dccad..171ae269c86 100644
--- a/studio/frontend/src/features/browser/tab-view.tsx
+++ b/studio/frontend/src/features/browser/tab-view.tsx
@@ -15,8 +15,8 @@ import { fileNameFromUrl, hostOf } from "./address";
import { agentDownloadRule, stricterDownloadRule } from "./agent/agent-store";
import { BrowserFetchError, type BrowserPage, fetchBrowserPage } from "./api";
import { proxiedFavicon } from "./favicon";
-import { saveBrowserDownload } from "./downloads";
-import { canShowFile } from "./file-kind";
+import { saveBrowserDownload, saveBrowserDownloadOnClick, saveLinkedFile } from "./downloads";
+import { savesFile } from "./file-kind";
import { FileView } from "./file-view";
import { BROWSER_FIND_TARGET, pageLoadedForFind, receiveFindResult } from "./find";
import { useBrowserHistoryStore } from "./history-store";
@@ -104,6 +104,33 @@ function useFrameMessages(tabId: string, origin: string | null) {
case "external":
openExternalLink(message.url);
break;
+ case "download": {
+ const tab = store.tabs.find((candidate) => candidate.id === tabId);
+ const entry = tab ? currentEntry(tab) : null;
+ const site = pageAddress(tab);
+ if (!site || !entry) break;
+ const temporary = loadTemporary(tabId, entry) || undefined;
+ if ("url" in message) {
+ // Pages can post any address: only one on the page's own site saves, as in a browser.
+ if (!origin || !sameOrigin(message.url, origin)) break;
+ const atClick = agentDownloadRule(tabId, site, message.url);
+ const agentRule = (fileUrl: string) => stricterDownloadRule(atClick, agentDownloadRule(tabId, site, fileUrl));
+ saveLinkedFile(message.url, message.name, { site, temporary, agentRule }, message.askFirst);
+ break;
+ }
+ const download = {
+ blob: message.blob,
+ name: message.name,
+ contentType: message.blob.type,
+ url: site,
+ site,
+ temporary,
+ agentRule: agentDownloadRule(tabId, site, site),
+ };
+ if (message.askFirst) saveBrowserDownloadOnClick(download);
+ else void saveBrowserDownload(download);
+ break;
+ }
case "loaded": {
store.updateTab(tabId, { title: message.title, favicon: null, loading: false });
pageLoadedForFind(tabId);
@@ -332,7 +359,7 @@ function WebPage({
// unsupported files download only on fresh loads, so revisiting the tab does not prompt again.
if (page.kind === "raw") {
const name = page.fileName ?? fileNameFromUrl(page.url);
- if (!canShowFile(name, page.contentType)) {
+ if (savesFile(name, page.contentType, page.attachment)) {
// use the sender or requested address, not the redirect target, so another site's permission cannot apply.
void saveBrowserDownload({ blob: page.blob, name, contentType: page.contentType, url: page.url, site: entry.from ?? url, temporary: loadTemporary(tab.id, entry) || undefined, agentRule: stricterDownloadRule(agentRuleAtStart, agentDownloadRule(tab.id, entry.from ?? url, page.url)) });
if (entry.kind === "web" && entry.from) useBrowserStore.getState().leaveDownload(tab.id, entry);
@@ -372,7 +399,13 @@ function WebPage({
const { page } = state;
if (page.kind === "raw") {
return (
- <FileView blob={page.blob} name={page.fileName ?? fileNameFromUrl(page.url)} contentType={page.contentType} scale={tab.zoom} />
+ <FileView
+ blob={page.blob}
+ name={page.fileName ?? fileNameFromUrl(page.url)}
+ contentType={page.contentType}
+ scale={tab.zoom}
+ saved={page.attachment}
+ />
);
}
return (
diff --git a/studio/frontend/tests/browser-frame-message.test.ts b/studio/frontend/tests/browser-frame-message.test.ts
index c3f680245a9..bcab4887139 100644
--- a/studio/frontend/tests/browser-frame-message.test.ts
+++ b/studio/frontend/tests/browser-frame-message.test.ts
@@ -3,7 +3,7 @@
import assert from "node:assert/strict";
import { test } from "node:test";
-import { frameNotice, parseFrameMessage } from "../src/features/browser/frame-message.ts";
+import { type FrameMessage, frameNotice, parseFrameMessage, userActionGate } from "../src/features/browser/frame-message.ts";
const from = (message: Record<string, unknown>) => parseFrameMessage({ source: "unsloth-browser", ...message });
@@ -121,3 +121,41 @@ test("a page's request is checked field by field, and one the panel won't make s
assert.deepEqual(from({ type: "requestAbort", id: "q1" }), { type: "requestAbort", id: "q1" });
assert.equal(from({ type: "requestAbort", id: 3 }), null);
});
+
+test("a file a page saves reaches the panel with its bytes and name only", () => {
+ const blob = new Blob(["a,b"], { type: "text/csv" });
+ const message = from({ type: "download", name: "data.csv", blob, url: "https://evil.example/" });
+ assert.deepEqual(message && Object.keys(message), ["type", "name", "blob"]);
+ assert.equal(message && "blob" in message && message.blob, blob);
+ assert.equal(message?.type === "download" && message.name, "data.csv");
+ assert.equal(from({ type: "download", name: "data.csv", blob: "a,b" }), null);
+ assert.equal(from({ type: "download", name: "", blob }), null);
+ const long = from({ type: "download", name: `${"x".repeat(5000)}.csv`, blob });
+ assert.ok(long?.type === "download" && long.name.length <= 1024 && /^x+\.csv$/.test(long.name));
+ const unnamed = from({ type: "download", name: "\u{1F600}".repeat(3000), blob });
+ assert.ok(unnamed?.type === "download" && unnamed.name.length <= 1024 && !/[\uD800-\uDBFF]$/.test(unnamed.name));
+});
+
+test("a file sent without a fresh click, or within a second of the last action, waits for Save instead of being dropped", () => {
+ const gate = userActionGate();
+ const file: FrameMessage = { type: "download", name: "data.csv", blob: new Blob(["a,b"]) };
+ const asks = (message: FrameMessage | null) => (message?.type === "download" ? message.askFirst === true : message);
+ assert.equal(asks(gate(file, false, 0)), true);
+ assert.equal(asks(gate(file, true, 10)), false);
+ assert.equal(asks(gate(file, true, 500)), true);
+ assert.equal(gate({ type: "shortcut", key: "t", shift: false }, true, 600), null);
+ assert.equal(asks(gate(file, true, 1200)), false);
+ assert.equal(gate({ type: "external", url: "https://a.example/" }, false, 5000), null);
+ assert.deepEqual(gate({ type: "title", title: "x" }, false, 5000), { type: "title", title: "x" });
+});
+
+test("a download link reaches the panel as its address and the link's name, which may be empty", () => {
+ const url = "https://a.example/data.txt";
+ assert.deepEqual(from({ type: "download", url, name: "" }), { type: "download", name: "", url });
+ assert.deepEqual(from({ type: "download", url, name: "data.txt", extra: 1 }), { type: "download", name: "data.txt", url });
+ assert.equal(from({ type: "download", name: "data.txt" }), null);
+ assert.equal(from({ type: "download", url, name: 3 }), null);
+ const gate = userActionGate();
+ const link: FrameMessage = { type: "download", name: "", url };
+ assert.deepEqual(gate(link, false, 0), { ...link, askFirst: true });
+});
diff --git a/studio/frontend/tests/browser-page-downloads.test.ts b/studio/frontend/tests/browser-page-downloads.test.ts
new file mode 100644
index 00000000000..e4562c54ff0
--- /dev/null
+++ b/studio/frontend/tests/browser-page-downloads.test.ts
@@ -0,0 +1,246 @@
+// 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 { readFileSync } from "node:fs";
+import { test } from "node:test";
+import { runInNewContext } from "node:vm";
+
+const shell = readFileSync(new URL("../../backend/routes/browser.py", import.meta.url), "utf8");
+const source = shell.slice(shell.indexOf("const linkFrom = "), shell.indexOf("const submitForm = "));
+
+const nativeDispatch = EventTarget.prototype.dispatchEvent;
+
+function setup() {
+ class PageEventTarget extends EventTarget {}
+ const capturing = new PageEventTarget();
+ const bubbling = new PageEventTarget();
+ class Document extends PageEventTarget {
+ addEventListener(type: string, listener: EventListener, capture?: boolean) {
+ (capture ? capturing : bubbling).addEventListener(type, listener);
+ }
+ }
+ const document = new Document();
+ class Element extends PageEventTarget {
+ isConnected = false;
+ attributes: Map<string, string>;
+ constructor(attributes: Record<string, string>) {
+ super();
+ this.attributes = new Map(Object.entries(attributes));
+ }
+ getAttribute(name: string) {
+ return this.attributes.get(name) ?? null;
+ }
+ hasAttribute(name: string) {
+ return this.attributes.has(name);
+ }
+ matches(selector: string) {
+ return selector === "a[href], area[href]" && this.hasAttribute("href");
+ }
+ }
+ const fire = (target: Element, event: Event) => {
+ if (!target.isConnected) return nativeDispatch.call(target, event);
+ Object.defineProperty(event, "composedPath", { value: () => [target, document] });
+ for (const node of [capturing, target, bubbling]) nativeDispatch.call(node, event);
+ return !event.defaultPrevented;
+ };
+ class HTMLAnchorElement extends Element {
+ click() {
+ fire(this, new Event("click", { cancelable: true }));
+ }
+ }
+ const posted: Array<Record<string, unknown>> = [];
+ const navigated: string[] = [];
+ runInNewContext(source, {
+ document,
+ Element,
+ HTMLAnchorElement,
+ EventTarget: PageEventTarget,
+ Event,
+ setTimeout,
+ nativeFetch: fetch,
+ URL,
+ pageUrl: "https://a.example/docs/page",
+ resolve: (href: string) => new URL(href, "https://a.example/docs/page").href,
+ post: (message: Record<string, unknown>) => message.type !== "linkClick" && posted.push(message),
+ navigate: (url: string) => navigated.push(url),
+ followHash: () => {},
+ });
+ const link = (attributes: Record<string, string>, connected = true) => {
+ const anchor = new HTMLAnchorElement(attributes);
+ anchor.isConnected = connected;
+ return anchor;
+ };
+ const userClick = (anchor: Element) => fire(anchor, new Event("click", { cancelable: true }));
+ return { document, link, userClick, posted, navigated };
+}
+
+async function settled(done: () => boolean) {
+ for (let i = 0; i < 100 && !done(); i++) await new Promise((resolve) => setTimeout(resolve, 10));
+}
+
+async function savedFile(posted: Array<Record<string, unknown>>) {
+ await settled(() => posted.length > 0);
+ assert.equal(posted.length, 1);
+ const [{ type, name, blob }] = posted;
+ assert.equal(type, "download");
+ assert.ok(blob instanceof Blob);
+ return { name, type: blob.type, text: await blob.text() };
+}
+
+test("a download link to a data: URL hands its file to the panel", async () => {
+ const page = setup();
+ page.userClick(page.link({ href: "data:text/csv,name%2Cage", download: "people.csv" }));
+ assert.deepEqual(await savedFile(page.posted), { name: "people.csv", type: "text/csv", text: "name,age" });
+ assert.deepEqual(page.navigated, []);
+});
+
+test("a blob saved through a link outside the page is handed over, though the page revokes it at once", async () => {
+ for (const click of ["dispatchEvent", "click"] as const) {
+ const page = setup();
+ const href = URL.createObjectURL(new Blob(['{"a":1}'], { type: "application/json" }));
+ const anchor = page.link({ href, download: "convertcsv.json" }, false);
+ if (click === "dispatchEvent") anchor.dispatchEvent(new Event("click"));
+ else anchor.click();
+ URL.revokeObjectURL(href);
+ assert.deepEqual(await savedFile(page.posted), {
+ name: "convertcsv.json",
+ type: "application/json",
+ text: '{"a":1}',
+ });
+ }
+});
+
+test("a blob saved through a link in the page is handed over", async () => {
+ const page = setup();
+ const href = URL.createObjectURL(new Blob(["hello blob"], { type: "text/plain" }));
+ page.link({ href, download: "" }).click();
+ URL.revokeObjectURL(href);
+ assert.deepEqual(await savedFile(page.posted), { name: "download", type: "text/plain", text: "hello blob" });
+});
+
+test("a download link the page fills in its own click handler saves the new file", async () => {
+ const saved: unknown[] = [];
+ const links: Array<Record<string, string>> = [{ href: "#" }, { href: URL.createObjectURL(new Blob(["old"])), download: "old.txt" }];
+ for (const before of links) {
+ const page = setup();
+ const anchor = page.link(before);
+ anchor.addEventListener("click", () => {
+ anchor.attributes.set("href", URL.createObjectURL(new Blob(["new"], { type: "text/csv" })));
+ anchor.attributes.set("download", "export.csv");
+ URL.revokeObjectURL(before.href);
+ });
+ page.userClick(anchor);
+ await settled(() => page.posted.length + page.navigated.length > 0);
+ const [file] = page.posted;
+ saved.push(file?.blob instanceof Blob ? [file.name, await file.blob.text()] : page.navigated);
+ }
+ assert.deepEqual(saved, [["export.csv", "new"], ["export.csv", "new"]]);
+});
+
+test("a link renamed in its own click handler keeps the bytes, though the caller revokes them at once", async () => {
+ const page = setup();
+ const href = URL.createObjectURL(new Blob(["report"], { type: "text/plain" }));
+ const anchor = page.link({ href, download: "draft.txt" });
+ anchor.addEventListener("click", () => anchor.attributes.set("download", "final.txt"));
+ anchor.click();
+ URL.revokeObjectURL(href);
+ assert.deepEqual(await savedFile(page.posted), { name: "final.txt", type: "text/plain", text: "report" });
+});
+
+test("ordinary links still navigate, and a download the page cancels saves nothing", async () => {
+ const page = setup();
+ page.userClick(page.link({ href: "https://example.com/next" }));
+ await settled(() => page.navigated.length > 0);
+ assert.deepEqual(page.navigated, ["https://example.com/next"]);
+ const routed = setup();
+ routed.document.addEventListener("click", (event) => event.preventDefault());
+ routed.userClick(routed.link({ href: "data:text/plain,x", download: "x.txt" }));
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ assert.deepEqual([routed.posted, routed.navigated], [[], []]);
+ assert.deepEqual(page.posted, []);
+});
+
+test("a download link to the page's own site is saved through the panel under the link's name, and the page stays", async () => {
+ const saves: unknown[] = [];
+ for (const download of ["data.txt", ""]) {
+ const page = setup();
+ page.userClick(page.link({ href: "/downloads/documents/txt/data.txt", download }));
+ await settled(() => page.posted.length + page.navigated.length > 0);
+ saves.push([page.posted.map((message) => ({ ...message })), page.navigated]);
+ }
+ const url = "https://a.example/downloads/documents/txt/data.txt";
+ assert.deepEqual(saves, [
+ [[{ type: "download", url, name: "data.txt" }], []],
+ [[{ type: "download", url, name: "" }], []],
+ ]);
+});
+
+test("a download link to another site opens it, as in a browser", async () => {
+ const page = setup();
+ page.userClick(page.link({ href: "https://b.example/data.txt", download: "data.txt" }));
+ await settled(() => page.posted.length + page.navigated.length > 0);
+ assert.deepEqual([page.posted, page.navigated], [[], ["https://b.example/data.txt"]]);
+});
+
+function shellNavigation(active = false) {
+ const part = (from: string, to: string) => {
+ const at = shell.indexOf(from);
+ return shell.slice(at, shell.indexOf(to, at));
+ };
+ const code = [
+ part("const navigate = ", "/* PAGE_STORAGE_JS */"),
+ part("// A blank popup", "const linkFrom = "),
+ part("const fileAt = ", "// Read at the click"),
+ "({ navigate });",
+ ].join("\n");
+ const posted: Array<Record<string, unknown>> = [];
+ const window: { open?: (url?: string, target?: string) => unknown } = {};
+ const base = "https://a.example/page";
+ const { navigate } = runInNewContext(code, {
+ window,
+ navigator: { userActivation: { isActive: active } },
+ cfg: { url: base },
+ shellOrigin: null,
+ URL,
+ nativeFetch: fetch,
+ resolve: (href: string) => new URL(href, base).href,
+ samePage: () => false,
+ followHash: () => {},
+ post: (message: Record<string, unknown>) => posted.push({ ...message }),
+ }) as { navigate: (url: string, newTab?: boolean) => void };
+ return { open: window.open!, navigate, posted };
+}
+
+test("a file the page sends a window to, or opens, is saved; it would otherwise be dropped as an outside link", async () => {
+ const opened = shellNavigation();
+ assert.equal(opened.open("data:text/plain,hi"), null);
+ assert.deepEqual(await savedFile(opened.posted), { name: "download", type: "text/plain", text: "hi" });
+ const sent = shellNavigation();
+ const href = URL.createObjectURL(new Blob(["a,b"], { type: "text/csv" }));
+ sent.navigate(href);
+ assert.deepEqual(await savedFile(sent.posted), { name: "download", type: "text/csv", text: "a,b" });
+ URL.revokeObjectURL(href);
+ const blocked = shellNavigation();
+ blocked.open("https://b.example/");
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ assert.deepEqual(blocked.posted, []);
+});
+
+test("FileSaver.js's blank popup, pointed at the file, saves it", async () => {
+ for (const send of ["href", "location"] as const) {
+ const page = shellNavigation();
+ const popup = page.open("", "_blank") as { document: { title: string; body: { innerText?: string } }; location: unknown };
+ popup.document.title = popup.document.body.innerText = "downloading...";
+ const url = "data:attachment/file;base64,aGk=";
+ if (send === "href") (popup.location as { href: string }).href = url;
+ else popup.location = url;
+ assert.deepEqual(await savedFile(page.posted), { name: "download", type: "attachment/file", text: "hi" });
+ }
+ const page = shellNavigation(true);
+ (page.open() as { location: string }).location = "https://b.example/next";
+ assert.deepEqual(page.posted, [{ type: "navigate", url: "https://b.example/next", newTab: true, background: false }]);
+ const late = shellNavigation(false);
+ (late.open() as { location: string }).location = "https://b.example/next";
+ assert.deepEqual(late.posted, [{ type: "navigate", url: "https://b.example/next", newTab: false, background: false }]);
+});
diff --git a/studio/frontend/tests/browser-settings.test.ts b/studio/frontend/tests/browser-settings.test.ts
index 4248fc0ab4f..d9f3203dd09 100644
--- a/studio/frontend/tests/browser-settings.test.ts
+++ b/studio/frontend/tests/browser-settings.test.ts
@@ -22,6 +22,7 @@ Object.assign(globalThis, {
});
register("./helpers/browser-store-resolver.mjs", import.meta.url);
+register("./helpers/file-kind-resolver.mjs", import.meta.url);
const { useBrowserHistoryStore } = await import("../src/features/browser/history-store.ts");
const { useBrowserPrefsStore } = await import("../src/features/browser/prefs-store.ts");
const { useBrowserBookmarksStore } = await import("../src/features/browser/bookmarks-store.ts");
@@ -680,6 +681,101 @@ test("a file a page sends the tab to is asked about for that page, not the file'
store.closeTab(tabId);
});
+test("a file a page sent without a click waits for Save, then asks for its page and follows the agent's rule", async () => {
+ const { saveBrowserDownloadOnClick } = await import("../src/features/browser/downloads.ts");
+ const { answerDownload, useApprovalStore } = await import("../src/features/browser/download-approval-queue.ts");
+ const g = globalThis as { __toasts?: { message: string; options?: { id?: string; action?: { onClick: () => void } } }[] };
+ g.__toasts = [];
+ const download = { blob: new Blob(["a,b"]), name: "export.csv", contentType: "text/csv", url: "https://a.example/page", site: "https://a.example/page" };
+ saveBrowserDownloadOnClick(download);
+ saveBrowserDownloadOnClick({ ...download, agentRule: "block" });
+ assert.deepEqual(g.__toasts.map((toast) => toast.message), ["browser.downloadPrompt.ready", "browser.downloadPrompt.ready"]);
+ assert.equal(useApprovalStore.getState().queue.length, 0);
+ g.__toasts[0].options!.action!.onClick();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ const queue = useApprovalStore.getState().queue;
+ assert.equal(queue.length, 1);
+ assert.equal(queue[0].origin, "https://a.example");
+ answerDownload(queue[0], false, false);
+ g.__toasts[1].options!.action!.onClick();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ assert.equal(g.__toasts.at(-1)!.message, "browser.downloadPrompt.blocked");
+ assert.equal(useApprovalStore.getState().queue.length, 0);
+ for (let i = 0; i < 4; i++) saveBrowserDownloadOnClick(download);
+ const ids = g.__toasts.slice(-4).map((toast) => toast.options?.id);
+ assert.equal(new Set(ids).size, 3);
+ assert.equal(ids[3], ids[0]);
+ saveBrowserDownloadOnClick({ ...download, blob: new Blob(["MZ"]), name: "update", contentType: "application/x-msdownload" });
+ g.__toasts.at(-1)!.options!.action!.onClick();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ const program = useApprovalStore.getState().queue[0];
+ assert.deepEqual([program?.name, program?.dangerous], ["update.exe", true]);
+ answerDownload(program, false, false);
+});
+
+test("a download link's file is fetched through the panel, named by the server, else the link, else its address", async () => {
+ const { saveLinkedFile } = await import("../src/features/browser/downloads.ts");
+ const { answerDownload, useApprovalStore } = await import("../src/features/browser/download-approval-queue.ts");
+ const g = globalThis as { __authFetch?: unknown; __toasts?: { message: string; options?: { action?: { onClick: () => void } } }[] };
+ const fetched: string[] = [];
+ let served: Record<string, string> = {};
+ g.__authFetch = async (_path: string, init: { body: string }) => {
+ fetched.push(JSON.parse(init.body).url);
+ return new Response("a,b", { headers: { "X-Unsloth-Browser-Kind": "raw", "Content-Type": "text/plain", ...served } });
+ };
+ const asked = async () => {
+ for (let i = 0; i < 50 && useApprovalStore.getState().queue.length === 0; i++) await new Promise((resolve) => setTimeout(resolve, 10));
+ const [item] = useApprovalStore.getState().queue;
+ answerDownload(item, false, false);
+ return [item.name, item.origin];
+ };
+ const rules: string[] = [];
+ const file = { site: "https://a.example/page", agentRule: (fileUrl: string) => (rules.push(fileUrl), null) };
+ try {
+ saveLinkedFile("https://a.example/downloads/data.txt", "data.txt", file);
+ assert.deepEqual(await asked(), ["data.txt", "https://a.example"]);
+ saveLinkedFile("https://a.example/downloads/data.txt", "", file);
+ assert.deepEqual(await asked(), ["data.txt", "https://a.example"]);
+ served = { "X-Unsloth-Browser-Filename": "report.txt" };
+ saveLinkedFile("https://a.example/downloads/data.txt", "data.txt", file);
+ assert.deepEqual(await asked(), ["report.txt", "https://a.example"]);
+ assert.deepEqual(rules, Array(3).fill("https://a.example/downloads/data.txt"));
+ g.__toasts = [];
+ saveLinkedFile("https://a.example/downloads/data.txt", "", file, true);
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ assert.equal(fetched.length, 3);
+ assert.deepEqual(g.__toasts.map((toast) => toast.message), ["browser.downloadPrompt.ready"]);
+ g.__toasts[0].options!.action!.onClick();
+ assert.deepEqual(await asked(), ["report.txt", "https://a.example"]);
+ assert.equal(fetched.length, 4);
+ } finally {
+ delete g.__authFetch;
+ useApprovalStore.setState({ queue: [] });
+ }
+});
+
+test("a file its site sends as an attachment is saved, not shown; inline or undeclared text still shows", async () => {
+ const { fetchBrowserPage } = await import("../src/features/browser/api.ts");
+ const { savesFile } = await import("../src/features/browser/file-kind.ts");
+ const g = globalThis as { __authFetch?: unknown };
+ const load = async (headers: Record<string, string>) => {
+ g.__authFetch = async () => new Response("a,b", { headers: { "X-Unsloth-Browser-Kind": "raw", ...headers } });
+ const page = await fetchBrowserPage({ url: "https://a.example/export" }, new AbortController().signal);
+ assert.ok(page.kind === "raw");
+ return savesFile(page.fileName ?? "export", page.contentType, page.attachment);
+ };
+ try {
+ const csv = { "Content-Type": "text/csv", "X-Unsloth-Browser-Filename": "export.csv" };
+ assert.equal(await load({ ...csv, "X-Unsloth-Browser-Attachment": "1" }), true);
+ assert.equal(await load({ "Content-Type": "application/pdf", "X-Unsloth-Browser-Attachment": "1" }), true);
+ assert.equal(await load(csv), false);
+ assert.equal(await load({ "Content-Type": "text/plain" }), false);
+ assert.equal(await load({ "Content-Type": "application/zip" }), true);
+ } finally {
+ delete g.__authFetch;
+ }
+});
+
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");
@@ -743,6 +839,26 @@ test("ordinary MIME suffixes are browser-only while native program suffixes stil
assert.equal(withTypeExtension("update", "application/x-msdownload"), "update.exe");
});
+test("an ordinary file sent without an extension gets its type's on the web, whatever the type's parameters", async () => {
+ const { withTypeExtension } = await import("../src/features/browser/download-safety.ts");
+ const { saveBrowserDownload } = await import("../src/features/browser/downloads.ts");
+ const { answerDownload, useApprovalStore } = await import("../src/features/browser/download-approval-queue.ts");
+ assert.equal(withTypeExtension("test-passing-green", "image/svg+xml;charset=utf-8", true), "test-passing-green.svg");
+ assert.equal(withTypeExtension("book", "application/epub+zip", true), "book.epub");
+ assert.equal(withTypeExtension("book", "application/epub+zip"), "book");
+ for (const [name, contentType, saved] of [
+ ["test-passing-green", "image/svg+xml; charset=utf-8", "test-passing-green.svg"],
+ ["book", "application/epub+zip", "book.epub"],
+ ]) {
+ const saving = saveBrowserDownload({ blob: new Blob(["x"]), name, contentType, url: `https://a.example/${name}` });
+ for (let i = 0; i < 50 && useApprovalStore.getState().queue.length === 0; i++) await new Promise((resolve) => setTimeout(resolve, 10));
+ const [asked] = useApprovalStore.getState().queue;
+ assert.deepEqual([asked?.name, asked?.dangerous], [saved, false]);
+ answerDownload(asked, false, false);
+ await saving;
+ }
+});
+
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");
diff --git a/studio/frontend/tests/browser-typed-tab-stays-live.test.ts b/studio/frontend/tests/browser-typed-tab-stays-live.test.ts
index 688477571d2..da443c4e6fd 100644
--- a/studio/frontend/tests/browser-typed-tab-stays-live.test.ts
+++ b/studio/frontend/tests/browser-typed-tab-stays-live.test.ts
@@ -6,6 +6,7 @@ import { readFileSync } from "node:fs";
import { register } from "node:module";
import { test } from "node:test";
import ts from "@typescript/typescript6";
+import { userActionGate } from "../src/features/browser/frame-message.ts";
import { readSrc } from "./helpers/kit.ts";
register("./helpers/browser-store-resolver.mjs", import.meta.url);
@@ -182,7 +183,7 @@ test("discarding a frame clears only its own draft mark", () => {
for (const id of [ids[1], ids[0]]) {
const noop = () => {};
const globals = {
- pageRequests: () => ({ stop: noop }), requestForPage: noop, urlRef: { current: null }, frameRef: { current: null },
+ pageRequests: () => ({ stop: noop }), requestForPage: noop, userActionGate, urlRef: { current: null }, frameRef: { current: null },
window: { addEventListener: noop, removeEventListener: noop }, onPageStorageClear: () => noop,
onPageStorageWrite: () => noop, origin: "https://a.example", tabIdRef: { current: id },
onMessageRef: { current: useFrameMessages(id, "https://a.example") },