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: confirm browser downloads, choose the download folder (#12832)

Michael Hanbc8173cc38c9
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index 10766442e64..770a54d9b77 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -15805,8 +15805,9 @@ def _fetch_url_raw(
redirect to another site does not carry them.
``post_data`` sends a urlencoded POST (kept on 307/308, dropped on other redirects).
- ``meta_out`` receives the final ``url``, ``charset`` and ``filename`` (Content-Disposition) of a
- successful binary-mode fetch, and
+ ``meta_out`` receives the final ``url``, ``charset``, ``filename`` (Content-Disposition),
+ ``allow_origin`` (Access-Control-Allow-Origin), ``cache_control`` and ``age`` of a successful
+ binary-mode fetch, and
``bot_check`` on HTTP errors.
``raw_bytes_max`` switches to binary mode: the body is returned as ``bytes`` untouched (no PDF
@@ -15963,6 +15964,9 @@ def _fetch_url_raw(
meta_out["url"] = current_url
meta_out["charset"] = resp.headers.get_content_charset()
meta_out["filename"] = resp.headers.get_filename()
+ meta_out["allow_origin"] = resp.headers.get("Access-Control-Allow-Origin")
+ meta_out["cache_control"] = resp.headers.get("Cache-Control")
+ meta_out["age"] = resp.headers.get("Age")
return None, raw_bytes, content_type
if not declared_pdf and len(raw_bytes) == max_bytes and _has_pdf_magic(raw_bytes):
tail_error, tail = _read_capped_body(
diff --git a/studio/backend/routes/browser.py b/studio/backend/routes/browser.py
index 2dea769850f..fa3c828d66a 100644
--- a/studio/backend/routes/browser.py
+++ b/studio/backend/routes/browser.py
@@ -9,13 +9,16 @@ from __future__ import annotations
import asyncio
import base64
+import bisect
import codecs
import hashlib
+import hmac
import html as _html
import json
import re
import threading
import time
+from collections import OrderedDict
from concurrent.futures import ThreadPoolExecutor
from typing import Literal, Optional
from urllib.parse import quote, urljoin, urlsplit
@@ -67,6 +70,60 @@ _REFRESH_RE = re.compile(
)
_META_CHARSET_RE = re.compile(rb"""<meta[^<>]+charset\s*=\s*["']?([\w:.-]+)""", re.IGNORECASE)
+# The sandbox's opaque origin fails CORS module loads: self-contained modules are inlined, ones with imports keep src.
+_MODULE_SCRIPT_RE = re.compile(r"<script\b" + _TAG_BODY + r"\s*</script\s*>", re.IGNORECASE)
+# One start-tag attribute; quoted values are skipped whole so a name inside a value isn't matched.
+_TAG_ATTR_RE = re.compile(r"""([^\s/>][^\s/>=]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]*)))?|/""")
+_FETCH_ATTRS = frozenset({"src", "integrity", "crossorigin"})
+# Imports resolve against the module URL. "/" after import may start a comment; after from it may be division (keeping the tag is the safe side).
+_MODULE_IMPORT_RE = re.compile(r"""(?<![\w$.])(?:import\b\s*[{*("'`\w$./]|from\s*["'`/])""")
+_MAX_AGE_RE = re.compile(r"(?:^|[\s,])(s-maxage|max-age)\s*=\s*\"?(\d+)", re.IGNORECASE)
+_SCRIPT_OPEN_RE = re.compile(r"<script", re.IGNORECASE)
+# Text, not markup: comments, raw-text/RCDATA/noscript/template content, and other tags' attribute values.
+_INERT_START_RE = re.compile(
+ r"<!--|<(script|style|textarea|title|xmp|iframe|noembed|noframes|noscript|plaintext|template)\b"
+ + _TAG_BODY
+ + r"|<[a-z][^\s/>]*"
+ + _TAG_BODY,
+ re.IGNORECASE,
+)
+_TEMPLATE_TAG_RE = re.compile(r"<(/)?template(?=[\s/>])", re.IGNORECASE)
+_CLOSING_TAG_RES = {
+ name: re.compile(rf"</{name}(?=[\s/>])", re.IGNORECASE)
+ for name in (
+ "script",
+ "style",
+ "textarea",
+ "title",
+ "xmp",
+ "iframe",
+ "noembed",
+ "noframes",
+ "noscript",
+ )
+}
+# The JavaScript MIME types a module script may be served as (WHATWG MIME Sniffing).
+_JS_TYPES = frozenset(
+ "application/ecmascript application/javascript application/x-ecmascript "
+ "application/x-javascript text/ecmascript text/javascript text/javascript1.0 "
+ "text/javascript1.1 text/javascript1.2 text/javascript1.3 text/javascript1.4 "
+ "text/javascript1.5 text/jscript text/livescript text/x-ecmascript text/x-javascript".split()
+)
+# Strongest last, for Subresource Integrity's "strongest algorithm wins".
+_SRI_ALGORITHMS = ("sha256", "sha384", "sha512")
+_MAX_INLINED_MODULES = 6
+_MAX_MODULE_BYTES = 2 * 1024 * 1024
+_MODULE_TIMEOUT_S = 8
+# Separate from _FETCH_POOL, whose workers wait on these.
+_MODULE_POOL = ThreadPoolExecutor(max_workers = 4, thread_name_prefix = "browser-module")
+# (url, integrity, credentials) -> (expiry, code or None); kept only while the response says fresh, failures never.
+_MODULE_CACHE: "OrderedDict[tuple[str, str, bool], tuple[float, Optional[str]]]" = OrderedDict()
+_MODULE_CACHE_LOCK = threading.Lock()
+_MODULE_CACHE_TTL_S = 600
+_MODULE_CACHE_ENTRIES = 128
+_MODULE_CACHE_CHARS = 16 * 1024 * 1024
+_module_cache_chars = 0
+
# https only (http could hit local services; WebKit lacks local network protection). The sandbox
# (no allow-same-origin) isolates pages; the injected script submits forms.
_FRAME_CSP = (
@@ -1144,6 +1201,217 @@ def _studio_headers(host: str) -> dict:
return _STUDIO_HEADERS if host == "unsloth.ai" or host.endswith(".unsloth.ai") else {}
+def _integrity_ok(body: bytes, integrity: str) -> bool:
+ """Whether ``body`` matches the tag's SRI ``integrity``; inlining drops the attribute, so check here."""
+ hashes: dict[str, list[str]] = {}
+ for token in integrity.split():
+ algorithm, _, value = token.partition("-")
+ algorithm = algorithm.lower()
+ if algorithm in _SRI_ALGORITHMS and value:
+ hashes.setdefault(algorithm, []).append(value.split("?", 1)[0])
+ if not hashes:
+ # No metadata the browser understands: it loads the script unchecked.
+ return True
+ algorithm = max(hashes, key = _SRI_ALGORITHMS.index)
+ digest = base64.b64encode(hashlib.new(algorithm, body).digest()).decode("ascii")
+ return any(hmac.compare_digest(digest, value) for value in hashes[algorithm])
+
+
+def _fresh_for(cache_control: Optional[str], age: Optional[str]) -> float:
+ """Seconds a response may be reused by this shared cache; ``private``/``no-cache`` rule it out."""
+ directives = (cache_control or "").lower()
+ if any(word in directives for word in ("no-store", "no-cache", "private")):
+ return 0
+ lifetimes = dict((name.lower(), int(value)) for name, value in _MAX_AGE_RE.findall(directives))
+ lifetime = lifetimes.get("s-maxage", lifetimes.get("max-age", 0))
+ try:
+ lifetime -= max(int(age or 0), 0)
+ except ValueError:
+ pass
+ return float(min(max(lifetime, 0), _MODULE_CACHE_TTL_S))
+
+
+def _module_cached(key: tuple[str, str, bool]) -> tuple[bool, Optional[str]]:
+ with _MODULE_CACHE_LOCK:
+ hit = _MODULE_CACHE.get(key)
+ if hit is None or time.monotonic() >= hit[0]:
+ return False, None
+ _MODULE_CACHE.move_to_end(key)
+ return True, hit[1]
+
+
+def _cache_module(key: tuple[str, str, bool], code: Optional[str], fresh_for: float) -> None:
+ global _module_cache_chars
+ size = len(code or "")
+ if fresh_for <= 0 or size > _MODULE_CACHE_CHARS // 4:
+ return
+ with _MODULE_CACHE_LOCK:
+ old = _MODULE_CACHE.pop(key, None)
+ if old is not None:
+ _module_cache_chars -= len(old[1] or "")
+ _MODULE_CACHE[key] = (time.monotonic() + fresh_for, code)
+ _module_cache_chars += size
+ while (
+ len(_MODULE_CACHE) > _MODULE_CACHE_ENTRIES or _module_cache_chars > _MODULE_CACHE_CHARS
+ ):
+ _, (_, dropped) = _MODULE_CACHE.popitem(last = False)
+ _module_cache_chars -= len(dropped or "")
+
+
+def _fetch_module(
+ url: str,
+ integrity: str,
+ credentials: bool,
+ deadline: float,
+ cancel_event: Optional[threading.Event],
+) -> Optional[str]:
+ """A self-contained module's code, safe to inline; None to leave its tag alone."""
+ key = (url, integrity, credentials)
+ found, code = _module_cached(key)
+ if found:
+ return code
+ meta: dict = {}
+ try:
+ error, body, content_type = _fetch_url_raw(
+ url,
+ timeout = _MODULE_TIMEOUT_S,
+ extra_headers = {"User-Agent": _BROWSER_UA, "Accept": "*/*"},
+ deadline = deadline,
+ raw_bytes_max = _MAX_MODULE_BYTES,
+ meta_out = meta,
+ cancel_event = cancel_event,
+ host_headers = _studio_headers,
+ )
+ except Exception as exc:
+ logger.warning("browser_module_fetch_failed", error = type(exc).__name__)
+ return None
+ if error is not None or not isinstance(body, bytes):
+ return None
+ # Redirected to http: tamperable, and the frame's upgrade-insecure-requests wouldn't run it either.
+ if not str(meta.get("url") or url).lower().startswith("https://"):
+ return None
+ code = None
+ allow_origin = (meta.get("allow_origin") or "").strip()
+ # ACAO * or null already loads from the sandbox (where SRI is enforced too).
+ loads_itself = allow_origin in ("*", "null") and not credentials
+ if content_type in _JS_TYPES and not loads_itself and _integrity_ok(body, integrity):
+ # Browsers decode module scripts as UTF-8 whatever the header says.
+ text = body.decode("utf-8", errors = "replace")
+ # Imports would resolve against the page; "<!--" then "<script" keeps an inline tag open.
+ if not _MODULE_IMPORT_RE.search(text) and not (
+ "<!--" in text and _SCRIPT_OPEN_RE.search(text)
+ ):
+ code = re.sub(r"</(script)", r"<\\/\1", text, flags = re.IGNORECASE)
+ # Only the final hop's headers are known, so a redirected answer isn't cached.
+ redirected = str(meta.get("url") or url) != url
+ fresh_for = 0 if redirected else _fresh_for(meta.get("cache_control"), meta.get("age"))
+ _cache_module(key, code, fresh_for)
+ return code
+
+
+def _inert_spans(page: str) -> list[tuple[int, int]]:
+ """Spans of ``page`` that are text, not markup, in order, read front to back as the parser does."""
+ spans: list[tuple[int, int]] = []
+ at = 0
+ while match := _INERT_START_RE.search(page, at):
+ if match.group(0).startswith("<!--"):
+ close = page.find("-->", match.end())
+ end = len(page) if close < 0 else close + 3
+ spans.append((match.start(), end))
+ elif match.group(1) is None:
+ end = match.end()
+ spans.append((match.start(), end))
+ elif match.group(1).lower() == "template":
+ depth, close = 1, None
+ for tag in _TEMPLATE_TAG_RE.finditer(page, match.end()):
+ depth += -1 if tag.group(1) else 1
+ if depth == 0:
+ close = tag
+ break
+ end = close.end() if close else len(page)
+ spans.append((match.end(), close.start() if close else len(page)))
+ else:
+ name = match.group(1).lower()
+ close = (
+ None if name == "plaintext" else _CLOSING_TAG_RES[name].search(page, match.end())
+ )
+ end = close.end() if close else len(page)
+ spans.append((match.end(), close.start() if close else len(page)))
+ at = max(end, match.end())
+ return spans
+
+
+def _open_tag(script: str) -> str:
+ """A script element's start tag, from a match of _MODULE_SCRIPT_RE."""
+ return script[: script.lower().rindex("</script")].rstrip()
+
+
+def _script_attrs(open_tag: str) -> list[tuple[str, str, str]]:
+ """A ``<script ...>`` start tag's attributes as ``(lowercase name, value, source text)``."""
+ attrs = []
+ for match in _TAG_ATTR_RE.finditer(open_tag, len("<script"), len(open_tag) - 1):
+ if match.group(1) is None:
+ continue
+ value = next((group for group in match.groups()[1:] if group is not None), "")
+ attrs.append((match.group(1).lower(), _html.unescape(value), match.group(0)))
+ return attrs
+
+
+def _inline_module_scripts(
+ page: str,
+ base_url: str,
+ cancel_event: Optional[threading.Event] = None,
+) -> str:
+ """Inline the page's self-contained module scripts, which the sandbox can't load itself."""
+ tags: list[tuple[re.Match[str], str, str, bool]] = []
+ inert: Optional[list[tuple[int, int]]] = None
+ for match in _MODULE_SCRIPT_RE.finditer(page):
+ attrs: dict[str, str] = {}
+ for name, value, _text in _script_attrs(_open_tag(match.group(0))):
+ # The first of a repeated attribute is the one that counts.
+ attrs.setdefault(name, value)
+ if attrs.get("type", "").strip().lower() != "module":
+ continue
+ src = attrs.get("src")
+ url = _join(base_url, src) if src else None
+ if not url or not url.lower().startswith("https://"):
+ continue
+ # A tag inside text (comment, textarea, style...) stays; inlined code could end that element.
+ if inert is None:
+ inert = _inert_spans(page)
+ at = bisect.bisect_right(inert, (match.start(), len(page))) - 1
+ if at >= 0 and inert[at][0] <= match.start() < inert[at][1]:
+ continue
+ credentials = attrs.get("crossorigin", "").strip().lower() == "use-credentials"
+ tags.append((match, url, attrs.get("integrity", ""), credentials))
+ if len(tags) == _MAX_INLINED_MODULES:
+ break
+ if not tags:
+ return page
+ deadline = time.monotonic() + _MODULE_TIMEOUT_S
+ codes = list(
+ _MODULE_POOL.map(lambda tag: _fetch_module(*tag[1:], deadline, cancel_event), tags)
+ )
+ parts: list[str] = []
+ end = 0
+ room = _MAX_BROWSER_HTML_BYTES - len(page.encode("utf-8"))
+ for (match, *_), code in zip(tags, codes):
+ size = len(code.encode("utf-8")) if code is not None else 0
+ if code is None or size > room:
+ continue
+ room -= size
+ kept = (
+ text
+ for name, _value, text in _script_attrs(_open_tag(match.group(0)))
+ if name not in _FETCH_ATTRS
+ )
+ open_tag = "".join(["<script", *(" " + text for text in kept), ">"])
+ parts += [page[end : match.start()], open_tag, code, "</script>"]
+ end = match.end()
+ parts.append(page[end:])
+ return "".join(parts)
+
+
def _fetch(
request: BrowserFetchRequest, cancel_event: threading.Event
) -> tuple[Optional[str], bytes, str, dict]:
@@ -1176,7 +1444,12 @@ def _attachment_name(meta: dict) -> Optional[str]:
def _build_response(
- url: str, error: Optional[str], body: bytes, content_type: str, meta: dict
+ url: str,
+ error: Optional[str],
+ body: bytes,
+ content_type: str,
+ meta: dict,
+ cancel_event: Optional[threading.Event] = None,
) -> Response:
"""Build the panel's response. Runs in the fetch pool to keep large pages off the event loop."""
if error is not None:
@@ -1201,6 +1474,7 @@ def _build_response(
detail = f"(page exceeds the {_MAX_BROWSER_HTML_BYTES} byte limit for the panel)",
)
page, base_url, refresh = _prepare_page(_decode_html(body, meta.get("charset")), final_url)
+ page = _inline_module_scripts(page, base_url, cancel_event)
payload = {"url": final_url, "base": base_url, "refresh": refresh, "html": page}
return Response(
content = json.dumps(payload, ensure_ascii = False).encode("utf-8"),
@@ -1232,7 +1506,7 @@ def _build_response(
def _fetch_and_build(request: BrowserFetchRequest, cancel_event: threading.Event) -> Response:
error, body, content_type, meta = _fetch(request, cancel_event)
- return _build_response(request.url, error, body, content_type, meta)
+ return _build_response(request.url, error, body, content_type, meta, cancel_event)
@router.post("/fetch")
diff --git a/studio/backend/tests/test_browser_routes.py b/studio/backend/tests/test_browser_routes.py
index eecd5862267..72823d19e57 100644
--- a/studio/backend/tests/test_browser_routes.py
+++ b/studio/backend/tests/test_browser_routes.py
@@ -343,3 +343,329 @@ def test_a_byte_order_mark_decides_the_encoding():
page = "<p>caf\u00e9</p>"
assert browser_mod._decode_html(page.encode("utf-16"), None) == page
assert browser_mod._decode_html(b"\xef\xbb\xbf" + page.encode("utf-8"), "iso-8859-1") == page
+
+
[email protected](autouse = True)
+def _empty_module_cache(monkeypatch):
+ monkeypatch.setattr(browser_mod, "_MODULE_CACHE", browser_mod.OrderedDict())
+ monkeypatch.setattr(browser_mod, "_module_cache_chars", 0)
+
+
+def _modules(
+ monkeypatch,
+ scripts,
+ allow_origin = None,
+ cache_control = None,
+ age = None,
+):
+ """Serve each URL in `scripts` as (error, body, content_type); return the URLs fetched."""
+ fetched = []
+
+ def fake_fetch(url, **kwargs):
+ fetched.append(url)
+ if allow_origin is not None:
+ kwargs["meta_out"]["allow_origin"] = allow_origin
+ kwargs["meta_out"].update(cache_control = cache_control, age = age)
+ return scripts.get(url, ("Failed to fetch URL: HTTP 404", "", ""))
+
+ monkeypatch.setattr(browser_mod, "_fetch_url_raw", fake_fetch)
+ return fetched
+
+
+def test_self_contained_module_scripts_are_inlined(monkeypatch):
+ _modules(
+ monkeypatch,
+ {
+ "https://example.com/js/app.js": (
+ None,
+ b'customElements.define("x-a", A);s="</script>"',
+ "text/javascript",
+ )
+ },
+ )
+ page = '<p>hi</p><script type="module" defer src="js/app.js" crossorigin integrity="sha-x" data-k="a>b"></script><p>end</p>'
+ out = browser_mod._inline_module_scripts(page, "https://example.com/")
+ assert out == (
+ '<p>hi</p><script type="module" defer data-k="a>b">'
+ 'customElements.define("x-a", A);s="<\\/script>"</script><p>end</p>'
+ )
+
+
+ "result",
+ [
+ (None, b'import {a} from "./b.js";a()', "text/javascript"),
+ (None, b'const m = await import("./lazy.js")', "application/javascript"),
+ (None, b'export * from "./c.js"', "text/javascript"),
+ # Resolves against the module's own URL, which inlining would change to the page's.
+ (None, b'new Worker(new URL("./w.js", import.meta.url))', "text/javascript"),
+ (None, b'import /* webpackChunkName: "lazy" */ ("./chunk.js")', "text/javascript"),
+ (None, b'import//x\n("./chunk.js")', "text/javascript"),
+ (None, b'export { a } from /* re-export */ "./a.js"', "text/javascript"),
+ (None, b'x="<!--";y="<script>"', "text/javascript"),
+ (None, b"a()", "text/plain"),
+ ("Failed to fetch URL: HTTP 404", "", ""),
+ ],
+)
+def test_modules_that_cannot_be_inlined_keep_their_tag(monkeypatch, result):
+ _modules(monkeypatch, {"https://example.com/m.js": result})
+ page = '<script type="module" src="/m.js"></script>'
+ assert browser_mod._inline_module_scripts(page, "https://example.com/page") == page
+
+
+def test_only_live_https_module_tags_are_fetched(monkeypatch):
+ fetched = _modules(monkeypatch, {})
+ page = (
+ '<script src="/classic.js"></script>'
+ '<script type="module">inline()</script>'
+ '<script type="module" src="http://example.com/plain.js"></script>'
+ '<!-- <script type="module" src="/old.js"></script> -->'
+ '<script type="module" src="/live.js"></script>'
+ )
+ assert browser_mod._inline_module_scripts(page, "https://example.com/") == page
+ assert fetched == ["https://example.com/live.js"]
+
+
+def test_a_fetched_page_gets_its_modules_inlined(monkeypatch):
+ def fake_fetch(url, **kwargs):
+ if url.endswith(".js"):
+ assert kwargs["raw_bytes_max"] == browser_mod._MAX_MODULE_BYTES
+ return None, b"ready()", "text/javascript"
+ return None, b'<html><script type="module" src="/a.js"></script></html>', "text/html"
+
+ monkeypatch.setattr(browser_mod, "_fetch_url_raw", fake_fetch)
+ html = json.loads(_call().body)["html"]
+ assert '<script type="module">ready()</script>' in html
+
+
+def _sri(algorithm, body):
+ import base64
+ import hashlib
+ return f"{algorithm}-" + base64.b64encode(hashlib.new(algorithm, body).digest()).decode()
+
+
+def test_an_inlined_module_still_has_its_integrity_checked(monkeypatch):
+ _modules(monkeypatch, {"https://example.com/m.js": (None, b"ready()", "text/javascript")})
+ tag = '<script type="module" src="/m.js" integrity="{}"></script>'
+ good = tag.format(f"{_sri('sha256', b'other')} {_sri('sha384', b'ready()')}")
+ bad = tag.format(f"{_sri('sha256', b'ready()')} {_sri('sha512', b'other')}")
+ assert "ready()" in browser_mod._inline_module_scripts(good, "https://example.com/")
+ assert browser_mod._inline_module_scripts(bad, "https://example.com/") == bad
+
+
+def test_modules_any_origin_may_load_keep_their_tag(monkeypatch):
+ _modules(
+ monkeypatch,
+ {"https://cdn.example/m.js": (None, b"ready()", "application/javascript")},
+ allow_origin = "*",
+ )
+ page = '<script type="module" src="https://cdn.example/m.js"></script>'
+ assert browser_mod._inline_module_scripts(page, "https://example.com/") == page
+ # A wildcard doesn't cover a credentialed request.
+ credentialed = page.replace("<script ", '<script crossorigin="use-credentials" ')
+ out = browser_mod._inline_module_scripts(credentialed, "https://example.com/")
+ assert out == '<script type="module">ready()</script>'
+
+
+def test_a_module_is_fetched_once_for_many_pages(monkeypatch):
+ fetched = _modules(
+ monkeypatch,
+ {"https://example.com/m.js": (None, b"ready()", "text/javascript")},
+ cache_control = "public, max-age=31536000, immutable",
+ )
+ page = '<script type="module" src="/m.js"></script>'
+ for _ in range(3):
+ assert "ready()" in browser_mod._inline_module_scripts(page, "https://example.com/")
+ assert fetched == ["https://example.com/m.js"]
+
+
+ "cache_control, age",
+ [
+ (None, None),
+ ("private, max-age=0", None),
+ ("max-age=600, no-cache", None),
+ ("no-store", None),
+ ("public, max-age=300", "300"),
+ ("private, max-age=600", None),
+ ],
+)
+def test_a_module_the_host_says_to_recheck_is_fetched_again(monkeypatch, cache_control, age):
+ fetched = _modules(
+ monkeypatch,
+ {"https://example.com/m.js": (None, b"ready()", "text/javascript")},
+ cache_control = cache_control,
+ age = age,
+ )
+ page = '<script type="module" src="/m.js"></script>'
+ for _ in range(2):
+ assert "ready()" in browser_mod._inline_module_scripts(page, "https://example.com/")
+ assert fetched == ["https://example.com/m.js"] * 2
+
+
+def test_a_module_is_kept_only_while_fresh():
+ assert browser_mod._fresh_for("public, max-age=60", "20") == 40
+ assert browser_mod._fresh_for("max-age=60, s-maxage=5", None) == 5
+ assert browser_mod._fresh_for("max-age=99999999", None) == browser_mod._MODULE_CACHE_TTL_S
+
+
+def test_inlined_modules_stay_within_the_page_limit(monkeypatch):
+ _modules(
+ monkeypatch,
+ {
+ "https://example.com/a.js": (None, b"a" * 60, "text/javascript"),
+ "https://example.com/b.js": (None, b"b" * 30, "text/javascript"),
+ },
+ )
+ page = '<script type="module" src="/a.js"></script><script type="module" src="/b.js"></script>'
+ monkeypatch.setattr(browser_mod, "_MAX_BROWSER_HTML_BYTES", len(page) + 50)
+ out = browser_mod._inline_module_scripts(page, "https://example.com/")
+ assert (
+ out
+ == '<script type="module" src="/a.js"></script><script type="module">'
+ + "b" * 30
+ + "</script>"
+ )
+
+
+def test_a_module_fetch_that_raises_leaves_the_page_alone(monkeypatch):
+ def boom(url, **kwargs):
+ raise RuntimeError("boom")
+
+ monkeypatch.setattr(browser_mod, "_fetch_url_raw", boom)
+ page = '<p>x</p><script type="module" src="/m.js"></script>'
+ assert browser_mod._inline_module_scripts(page, "https://example.com/") == page
+
+
+def test_script_attributes_are_read_from_the_tag_not_from_values(monkeypatch):
+ fetched = _modules(
+ monkeypatch,
+ {
+ "https://example.com/main.js": (None, b"main()", "text/javascript"),
+ "https://example.com/fallback.js": (None, b"fallback()", "text/javascript"),
+ "https://example.com/classic.js": (None, b"classic()", "text/javascript"),
+ },
+ )
+ page = (
+ """<script type="module" onerror="this.src='/fallback.js'" src="/main.js"></script>"""
+ '<script data-note="type=module" src="/classic.js"></script>'
+ '<script type="text/javascript" type="module" src="/classic.js"></script>'
+ )
+ out = browser_mod._inline_module_scripts(page, "https://example.com/")
+ assert out == (
+ """<script type="module" onerror="this.src='/fallback.js'">main()</script>"""
+ '<script data-note="type=module" src="/classic.js"></script>'
+ '<script type="text/javascript" type="module" src="/classic.js"></script>'
+ )
+ assert fetched == ["https://example.com/main.js"]
+
+
+ "wrap",
+ [
+ "<textarea>{}</textarea>",
+ "<title>{}</title>",
+ "<style>{}</style>",
+ "<noscript>{}</noscript>",
+ "<xmp>{}</xmp>",
+ "<textarea>{}",
+ "<plaintext>{}",
+ ],
+)
+def test_a_module_tag_written_as_text_is_left_alone(monkeypatch, wrap):
+ fetched = _modules(
+ monkeypatch, {"https://example.com/m.js": (None, b"ready()", "text/javascript")}
+ )
+ page = wrap.format('<script type="module" src="/m.js"></script>')
+ assert browser_mod._inline_module_scripts(page, "https://example.com/") == page
+ assert fetched == []
+
+
+def test_text_elements_in_script_code_dont_hide_later_modules(monkeypatch):
+ _modules(monkeypatch, {"https://example.com/m.js": (None, b"ready()", "text/javascript")})
+ page = (
+ "<script>var css = '<style' + '>'; var t = '<textarea>';</script>"
+ "<!-- <title> -->"
+ '<textarea><script type="module" src="/m.js"></script></textarea>'
+ '<script type="module" src="/m.js"></script>'
+ )
+ out = browser_mod._inline_module_scripts(page, "https://example.com/")
+ assert out.endswith('</textarea><script type="module">ready()</script>')
+ assert out.count("ready()") == 1
+
+
+def test_the_page_limit_is_counted_in_bytes(monkeypatch):
+ # 60 two-byte characters: counted as characters, the page would seem to have room.
+ _modules(monkeypatch, {"https://example.com/m.js": (None, b"m" * 50, "text/javascript")})
+ page = "é" * 60 + '<script type="module" src="/m.js"></script>'
+ monkeypatch.setattr(browser_mod, "_MAX_BROWSER_HTML_BYTES", 200)
+ assert browser_mod._inline_module_scripts(page, "https://example.com/") == page
+ monkeypatch.setattr(browser_mod, "_MAX_BROWSER_HTML_BYTES", 220)
+ out = browser_mod._inline_module_scripts(page, "https://example.com/")
+ assert "m" * 50 in out and len(out.encode()) <= 220
+
+
+ "page",
+ [
+ """<div data-example='<script type="module" src="/m.js"></script>'>x</div>""",
+ """<a title="a > b" data-x='<script type=module src=/m.js></script>'>x</a>""",
+ """<img alt="<script type='module' src='/m.js'></script>">""",
+ ],
+)
+def test_a_module_tag_inside_an_attribute_value_is_left_alone(monkeypatch, page):
+ fetched = _modules(
+ monkeypatch, {"https://example.com/m.js": (None, b"ready()", "text/javascript")}
+ )
+ assert browser_mod._inline_module_scripts(page, "https://example.com/") == page
+ assert fetched == []
+
+
+def test_a_module_redirected_to_plain_http_keeps_its_tag(monkeypatch):
+ def fake_fetch(url, **kwargs):
+ kwargs["meta_out"]["url"] = "http://example.com/m.js"
+ return None, b"ready()", "text/javascript"
+
+ monkeypatch.setattr(browser_mod, "_fetch_url_raw", fake_fetch)
+ page = '<p class="a">x</p><script type="module" src="/m.js"></script>'
+ assert browser_mod._inline_module_scripts(page, "https://example.com/") == page
+
+
+ "page",
+ [
+ '<template><script type="module" src="/m.js"></script></template>',
+ '<template><template></template><script type="module" src="/m.js"></script></template>',
+ '<template id="t"><div><script type="module" src="/m.js"></script>',
+ ],
+)
+def test_a_module_tag_in_a_template_is_left_alone(monkeypatch, page):
+ fetched = _modules(
+ monkeypatch, {"https://example.com/m.js": (None, b"ready()", "text/javascript")}
+ )
+ assert browser_mod._inline_module_scripts(page, "https://example.com/") == page
+ assert fetched == []
+
+
+def test_a_module_after_a_template_is_still_inlined(monkeypatch):
+ _modules(monkeypatch, {"https://example.com/m.js": (None, b"ready()", "text/javascript")})
+ page = '<template><p>x</p></template><script type="module" src="/m.js"></script>'
+ out = browser_mod._inline_module_scripts(page, "https://example.com/")
+ assert out == '<template><p>x</p></template><script type="module">ready()</script>'
+
+
+def test_a_redirected_module_is_not_cached(monkeypatch):
+ fetched = []
+
+ def fake_fetch(url, **kwargs):
+ fetched.append(url)
+ kwargs["meta_out"].update(
+ url = "https://example.com/v1.js", cache_control = "public, max-age=600", age = None
+ )
+ return None, b"ready()", "text/javascript"
+
+ monkeypatch.setattr(browser_mod, "_fetch_url_raw", fake_fetch)
+ page = '<script type="module" src="/latest.js"></script>'
+ for _ in range(2):
+ assert "ready()" in browser_mod._inline_module_scripts(page, "https://example.com/")
+ assert fetched == ["https://example.com/latest.js"] * 2
diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsx
index 91a28eeb341..509d7bb9c4f 100644
--- a/studio/frontend/src/app/routes/__root.tsx
+++ b/studio/frontend/src/app/routes/__root.tsx
@@ -11,6 +11,7 @@ import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";
import { fetchDeviceType, usePlatformStore } from "@/config/env";
import { videoNavHint } from "@/config/hardware-verdict";
import { ApiMonitorOverlay } from "@/features/api-monitor/api-monitor-overlay";
+import { DownloadApprovalDialog } from "@/features/browser";
import {
AUTH_SESSION_CLEARED_EVENT,
AUTH_SESSION_STORED_EVENT,
@@ -682,6 +683,7 @@ function RootLayout() {
{!isAuthFlowRoute && <ApiMonitorOverlay />}
<HfTokenWarningDialog />
<RemoteCodeConsentDialog />
+ <DownloadApprovalDialog />
<TransformersUpgradeDialog />
<LlmCompressorConsentDialog />
{/* At the root, not under /chat: a swap can start from the Hub too. */}
diff --git a/studio/frontend/src/features/browser/download-approval-queue.ts b/studio/frontend/src/features/browser/download-approval-queue.ts
new file mode 100644
index 00000000000..a9874b04bee
--- /dev/null
+++ b/studio/frontend/src/features/browser/download-approval-queue.ts
@@ -0,0 +1,51 @@
+// 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 { getLocale, translate } from "@/i18n";
+import { toast } from "@/lib/toast";
+import { create } from "zustand";
+import { hostOf, isWebUrl } from "./address";
+import { useDownloadSitesStore } from "./download-sites-store";
+import { useBrowserPrefsStore } from "./prefs-store";
+
+export type DownloadRequest = { origin: string; label: string; name: string; resolve: (allow: boolean) => void };
+
+export const useApprovalStore = create<{ queue: DownloadRequest[] }>(() => ({ queue: [] }));
+
+/** Origin (scheme, host, port) an answer is kept under, as browsers scope permissions; a blob: URL counts as its creator's origin. "" for data:, about:, opaque blobs. */
+export function downloadSiteOf(site: string): string {
+ if (!isWebUrl(site) && !/^blob:/i.test(site)) return "";
+ try {
+ const { origin } = new URL(site);
+ return isWebUrl(origin) ? origin : "";
+ } catch {
+ return "";
+ }
+}
+
+/** Remembered answer for `site` (default: the file's address), else ask. Only web origins count: one answer for "" would cover blob:/data: everywhere. */
+export function approveDownload(url: string, name: string, site: string = url): Promise<boolean> {
+ const origin = downloadSiteOf(site);
+ const label = (origin && hostOf(origin)) || hostOf(url) || url.slice(0, 80);
+ const remembered = origin ? useDownloadSitesStore.getState().sites[origin] : undefined;
+ if (remembered === "block") {
+ toast.error(translate("browser.downloadPrompt.blocked", { host: label }, getLocale()));
+ return Promise.resolve(false);
+ }
+ if (remembered === "allow" || !useBrowserPrefsStore.getState().askBeforeDownloading) return Promise.resolve(true);
+ return new Promise((resolve) =>
+ useApprovalStore.setState((state) => ({ queue: [...state.queue, { origin, label, name, resolve }] })),
+ );
+}
+
+/** Ignored unless it's the download being asked about. Remembered, it also settles the site's other waiting downloads. */
+export function answerDownload(request: DownloadRequest, allow: boolean, remember: boolean): void {
+ const { queue } = useApprovalStore.getState();
+ if (queue[0] !== request) return;
+ const kept = remember && request.origin !== "";
+ if (kept) useDownloadSitesStore.getState().setSite(request.origin, allow ? "allow" : "block");
+ const answered = kept ? queue.filter((other) => other.origin === request.origin) : [request];
+ useApprovalStore.setState({ queue: queue.filter((other) => !answered.includes(other)) });
+ for (const other of answered) other.resolve(allow);
+}
diff --git a/studio/frontend/src/features/browser/download-approval.tsx b/studio/frontend/src/features/browser/download-approval.tsx
new file mode 100644
index 00000000000..900fe64653f
--- /dev/null
+++ b/studio/frontend/src/features/browser/download-approval.tsx
@@ -0,0 +1,54 @@
+// 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 {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { Checkbox } from "@/components/ui/checkbox";
+import { useT } from "@/i18n";
+import { useId, useState } from "react";
+import { answerDownload, useApprovalStore } from "./download-approval-queue";
+
+export function DownloadApprovalDialog() {
+ const t = useT();
+ const request = useApprovalStore((state) => state.queue[0]);
+ const [remember, setRemember] = useState(false);
+ const checkboxId = useId();
+
+ // Escape or an outside click cancels this once only, so a stray click with the box ticked doesn't block the site for good.
+ const answer = (allow: boolean, kept = true) => {
+ if (!request || useApprovalStore.getState().queue[0] !== request) return;
+ setRemember(false);
+ answerDownload(request, allow, kept && remember);
+ };
+
+ return (
+ <AlertDialog open={request !== undefined} onOpenChange={(open) => !open && answer(false, false)}>
+ <AlertDialogContent onOverlayClick={() => answer(false, false)}>
+ <AlertDialogHeader>
+ <AlertDialogTitle>{t("browser.downloadPrompt.title")}</AlertDialogTitle>
+ <AlertDialogDescription className="break-words">
+ {request ? t("browser.downloadPrompt.description", { host: request.label, name: request.name }) : null}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ {request?.origin ? (
+ <label htmlFor={checkboxId} className="flex cursor-pointer items-center gap-2 text-sm text-foreground">
+ <Checkbox id={checkboxId} checked={remember} onCheckedChange={(checked) => setRemember(checked === true)} />
+ {t("browser.downloadPrompt.remember")}
+ </label>
+ ) : null}
+ <AlertDialogFooter>
+ <AlertDialogCancel onClick={() => answer(false)}>{t("browser.downloadPrompt.cancel")}</AlertDialogCancel>
+ <AlertDialogAction onClick={() => answer(true)}>{t("browser.downloadPrompt.download")}</AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+}
diff --git a/studio/frontend/src/features/browser/download-sites-store.ts b/studio/frontend/src/features/browser/download-sites-store.ts
new file mode 100644
index 00000000000..764d96112fd
--- /dev/null
+++ b/studio/frontend/src/features/browser/download-sites-store.ts
@@ -0,0 +1,35 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Per account, like history: one account's "Always allow" must not skip another's prompt.
+
+import { create } from "zustand";
+import { createJSONStorage, persist } from "zustand/middleware";
+import { accountDatabaseName } from "@/lib/account-transition";
+
+export type DownloadSiteDecision = "allow" | "block";
+
+interface DownloadSitesState {
+ sites: Record<string, DownloadSiteDecision>;
+ setSite: (origin: string, decision: DownloadSiteDecision | null) => void;
+}
+
+export const useDownloadSitesStore = create<DownloadSitesState>()(
+ persist(
+ (set) => ({
+ sites: {},
+ setSite: (origin, decision) =>
+ set((state) => {
+ const sites = { ...state.sites };
+ if (decision) sites[origin] = decision;
+ else delete sites[origin];
+ return { sites };
+ }),
+ }),
+ {
+ name: accountDatabaseName("unsloth_browser_download_sites"),
+ version: 1,
+ storage: createJSONStorage(() => localStorage),
+ },
+ ),
+);
diff --git a/studio/frontend/src/features/browser/downloads.ts b/studio/frontend/src/features/browser/downloads.ts
index ee9631041ec..526476819d1 100644
--- a/studio/frontend/src/features/browser/downloads.ts
+++ b/studio/frontend/src/features/browser/downloads.ts
@@ -1,16 +1,18 @@
// 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 { getLocale, translate } from "@/i18n";
import { isTauri } from "@/lib/api-base";
import { DownloadCancelledError, downloadFile, isDownloadCancelled } from "@/lib/native-files";
import { toast } from "@/lib/toast";
-import { fileNameFromUrl, withBaseUrl } from "./address";
+import { fileNameFromUrl, isWebUrl, withBaseUrl } from "./address";
import { type BrowserPage, fetchBrowserPage } from "./api";
+import { approveDownload } from "./download-approval-queue";
import { useBrowserHistoryStore } from "./history-store";
import { saveNativeDownload } from "./native-downloads";
import { useBrowserPrefsStore } from "./prefs-store";
-export type BrowserDownload = { blob: Blob; name: string; contentType: string; url: string | null };
+export type BrowserDownload = { blob: Blob; name: string; contentType: string; url: string | null; site?: string };
type SaveHandle = {
name: string;
@@ -23,9 +25,8 @@ function saveFilePicker(): SaveFilePicker | null {
return typeof picker === "function" ? picker : null;
}
-/** The desktop app always asks; the web build needs the browser's save dialog (Chromium). */
export function canAskWhereToSave(): boolean {
- return !isTauri && saveFilePicker() !== null;
+ return isTauri || saveFilePicker() !== null;
}
function asksWhereToSave(): boolean {
@@ -51,18 +52,39 @@ async function pickSaveTarget(name: string): Promise<SaveHandle | null> {
}
}
-/** Save a file from the panel and add it to the download history. `target` is a save location
- * already picked, or null for none; left out, the dialog opens here when Settings asks. */
-export async function saveBrowserDownload(
+function approved(url: string | null, name: string, site?: string): Promise<boolean> {
+ return url && isWebUrl(url) ? approveDownload(url, name, site ?? url) : Promise.resolve(true);
+}
+
+/** 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> {
+ if (target === undefined) {
+ if (!(await approved(download.url, download.name, download.site))) 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: download.name }, locale), {
+ action: {
+ label: translate("browser.downloadPrompt.save", {}, locale),
+ onClick: () => void writeDownload(download, undefined),
+ },
+ });
+ return;
+ }
+ }
+ await writeDownload(download, target);
+}
+
+async function writeDownload(
{ blob, name, contentType, url }: BrowserDownload,
- target?: SaveHandle | null,
+ target: SaveHandle | null | undefined,
): Promise<void> {
let saved: { id: string; name: string } | null = null;
let picked: SaveHandle | null = null;
try {
if (isTauri) {
// The app keeps the path so Download history can reveal it.
- saved = await saveNativeDownload(blob, name);
+ saved = await saveNativeDownload(blob, name, useBrowserPrefsStore.getState().askWhereToSave, url);
if (!saved) return;
} else {
picked = target === undefined ? await pickSaveTarget(name) : target;
@@ -121,8 +143,10 @@ export async function saveLinkAs(url: string): Promise<void> {
]);
// A link that already failed has nothing to save: report it without asking for a name.
if (quick && "error" in quick) throw quick.error;
+ const name = quick?.download.name ?? fileNameFromUrl(url);
try {
- target = await pickSaveTarget(quick?.download.name ?? fileNameFromUrl(url));
+ if (!(await approved(url, name))) throw new DownloadCancelledError();
+ target = await pickSaveTarget(name);
} catch (error) {
// No save after all: stop the fetch, which the backend drops on disconnect.
controller.abort();
diff --git a/studio/frontend/src/features/browser/file-kind.ts b/studio/frontend/src/features/browser/file-kind.ts
index 737fd1f74f8..440177ea0b7 100644
--- a/studio/frontend/src/features/browser/file-kind.ts
+++ b/studio/frontend/src/features/browser/file-kind.ts
@@ -45,3 +45,8 @@ export function browserTabType(name: string, contentType: string): string | null
if (kind) return kind === "html" ? null : "text/plain";
return SAFE_TAB_TYPE.test(contentType) ? contentType : null;
}
+
+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;
+}
diff --git a/studio/frontend/src/features/browser/file-view.tsx b/studio/frontend/src/features/browser/file-view.tsx
index aceefba25e0..e3e93eeafb9 100644
--- a/studio/frontend/src/features/browser/file-view.tsx
+++ b/studio/frontend/src/features/browser/file-view.tsx
@@ -14,7 +14,7 @@ import { useT } from "@/i18n";
import { MAX_HIGHLIGHT_CHARS } from "@/lib/markdown-plugins";
import { cn } from "@/lib/utils";
import { useCallback, useEffect, useMemo, useState } from "react";
-import { HTML_NAME, TEXT_NAME, TEXT_TYPE, mediaKind, textFileKind } from "./file-kind";
+import { canShowFile, mediaKind, textFileKind } from "./file-kind";
import { stageEditsPrompt } from "./stage-edits";
import { DEFAULT_FILE_VIEW, useBrowserStore } from "./store";
@@ -213,7 +213,7 @@ export function FileView({
</div>
);
}
- if (plainText || TEXT_TYPE.test(contentType) || TEXT_NAME.test(name) || HTML_NAME.test(name) || !contentType) {
+ if (plainText || canShowFile(name, contentType)) {
return (
<TextFile
blob={blob}
diff --git a/studio/frontend/src/features/browser/index.ts b/studio/frontend/src/features/browser/index.ts
index 3306a4c31d6..f0a3ed8aa01 100644
--- a/studio/frontend/src/features/browser/index.ts
+++ b/studio/frontend/src/features/browser/index.ts
@@ -8,6 +8,14 @@ import { type FileViewMode, type OpenFileInput, useBrowserStore } from "./store"
export { ClearBrowsingDataDialog } from "./clear-data-dialog";
export { BrowserToggleButton } from "./browser-toggle";
export { canAskWhereToSave, saveLinkAs } from "./downloads";
+export { DownloadApprovalDialog } from "./download-approval";
+export { type DownloadSiteDecision, useDownloadSitesStore } from "./download-sites-store";
+export {
+ type DownloadFolder,
+ nativeDownloadFolder,
+ pickNativeDownloadFolder,
+ resetNativeDownloadFolder,
+} from "./native-downloads";
export { BookmarksFileError, exportBookmarksFile, importBookmarksFile } from "./bookmarks-io";
export { MAX_BOOKMARKS } from "./bookmarks-store";
export { canScreenshot } from "./screenshot-support";
diff --git a/studio/frontend/src/features/browser/native-downloads.ts b/studio/frontend/src/features/browser/native-downloads.ts
index 274f1999d41..8197fa021dd 100644
--- a/studio/frontend/src/features/browser/native-downloads.ts
+++ b/studio/frontend/src/features/browser/native-downloads.ts
@@ -6,20 +6,41 @@
import { isTauri } from "@/lib/api-base";
import { NATIVE_FILE_NAME_HEADER, encodeNativeFilename } from "@/lib/native-files";
+import { isWebUrl } from "./address";
async function invoke<T>(command: string, args?: Record<string, unknown>): Promise<T> {
const core = await import("@tauri-apps/api/core");
return core.invoke<T>(command, args);
}
-/** Save through the desktop app's dialog; the saved name and its id, or null if cancelled. */
-export async function saveNativeDownload(blob: Blob, name: string): Promise<{ id: string; name: string } | null> {
+/** Null if cancelled. A website file (`source`) is quarantine-marked so Gatekeeper/SmartScreen check it. */
+export async function saveNativeDownload(
+ blob: Blob,
+ name: string,
+ ask: boolean,
+ source: string | null,
+): Promise<{ id: string; name: string } | null> {
const core = await import("@tauri-apps/api/core");
+ const headers: Record<string, string> = {
+ [NATIVE_FILE_NAME_HEADER]: encodeNativeFilename(name),
+ "x-unsloth-ask": ask ? "1" : "0",
+ };
+ // href is ASCII (punycode host, escaped path), as a header value must be.
+ const href = source && isWebUrl(source) ? safeHref(source) : null;
+ if (href) headers["x-unsloth-source"] = href;
return core.invoke<{ id: string; name: string } | null>("browser_download_save", new Uint8Array(await blob.arrayBuffer()), {
- headers: { [NATIVE_FILE_NAME_HEADER]: encodeNativeFilename(name) },
+ headers,
});
}
+function safeHref(url: string): string | null {
+ try {
+ return new URL(url).href;
+ } catch {
+ return null;
+ }
+}
+
export function revealNativeDownload(id: string): Promise<void> {
return invoke<void>("browser_download_reveal", { id });
}
@@ -30,6 +51,24 @@ export async function nativeDownloadsExist(ids: string[]): Promise<boolean[]> {
return invoke<boolean[]>("browser_download_exists", { ids });
}
+export type DownloadFolder = { path: string; custom: boolean };
+
+export function nativeDownloadFolder(): Promise<DownloadFolder> {
+ return invoke<DownloadFolder>("browser_download_folder");
+}
+
+export function pickNativeDownloadFolder(): Promise<DownloadFolder | null> {
+ return invoke<DownloadFolder | null>("browser_download_folder_pick");
+}
+
+export function resetNativeDownloadFolder(): Promise<DownloadFolder> {
+ return invoke<DownloadFolder>("browser_download_folder_reset");
+}
+
+export function decideNativeDownload(id: string, allow: boolean, ask: boolean): Promise<void> {
+ return invoke<void>("browser_download_decide", { id, allow, ask });
+}
+
/** Forget downloads taken off the history; the files stay. */
export function forgetNativeDownloads(ids: string[]): void {
if (!isTauri || ids.length === 0) return;
diff --git a/studio/frontend/src/features/browser/native-view.ts b/studio/frontend/src/features/browser/native-view.ts
index 4be3a8c03db..2dd30c1a905 100644
--- a/studio/frontend/src/features/browser/native-view.ts
+++ b/studio/frontend/src/features/browser/native-view.ts
@@ -10,9 +10,12 @@ import { openExternalLink } from "@/lib/open-link";
import { toast } from "@/lib/toast";
import { BROWSER_PAGE_INSET_VAR, CHAT_SETTINGS_INSET_VAR } from "@/lib/toast-offset";
import { hostOf } from "./address";
+import { approveDownload, downloadSiteOf } from "./download-approval-queue";
import { proxiedFavicon } from "./favicon";
import { useBrowserHistoryStore } from "./history-store";
+import { decideNativeDownload } from "./native-downloads";
import { callNative as call, nativeClearing, onNativeViewsClosed } from "./native-support";
+import { useBrowserPrefsStore } from "./prefs-store";
import { type BrowserEntry, type BrowserTab, currentEntry, entryKey, useBrowserStore } from "./store";
export { clearNativeBrowsingData, useNativeBrowser } from "./native-support";
@@ -47,7 +50,8 @@ type NativeEvent =
done: boolean;
success: boolean;
downloadId: string | null;
- };
+ }
+ | { kind: "downloadPrompt"; tabId: string; url: string; site: string; name: string; id: string };
type Bounds = { x: number; y: number; width: number; height: number; viewportWidth: number };
@@ -109,9 +113,28 @@ function listenOnce(): void {
);
}
+/** Always answered: an unanswered download would sit in staging until the app quits. */
+function onDownloadPrompt(event: Extract<NativeEvent, { kind: "downloadPrompt" }>, tab: BrowserTab | undefined): void {
+ const { id, url, site, name } = event;
+ const entry = tab ? currentEntry(tab) : null;
+ // The site asking is the page that started it, taken then (a later site's answer must not cover it); blob: counts as its creator. With no web origin yet, the opener or the address asked for.
+ const asking = downloadSiteOf(site) ? site : entry?.kind === "web" ? entry.from || entry.url : "";
+ const decided = entry?.kind === "web" ? approveDownload(url, name, asking) : Promise.resolve(false);
+ void decided
+ .then(async (allow) => {
+ await decideNativeDownload(id, allow, useBrowserPrefsStore.getState().askWhereToSave);
+ if (allow) toast(t("browser.native.downloading", { name }));
+ })
+ .catch(() => undefined);
+}
+
function onNativeEvent(event: NativeEvent): void {
const store = useBrowserStore.getState();
const tab = store.tabs.find((candidate) => candidate.id === event.tabId);
+ if (event.kind === "downloadPrompt") {
+ onDownloadPrompt(event, tab);
+ return;
+ }
if (!tab || currentEntry(tab).kind !== "web") return;
const history = useBrowserHistoryStore.getState();
switch (event.kind) {
@@ -153,11 +176,11 @@ function onNativeEvent(event: NativeEvent): void {
newTabTimes = newTabTimes.filter((time) => now - time < NEW_TAB_WINDOW_MS);
if (newTabTimes.length < NEW_TABS_PER_WINDOW) {
newTabTimes.push(now);
- store.openUrl(event.url, { newTab: true });
+ store.openUrl(event.url, { newTab: true, from: shownUrl(tab) });
} else {
prompt(t("browser.native.externalPrompt", { host: hostOf(shownUrl(tab)), url: event.url }), {
label: t("browser.native.open"),
- onClick: () => store.openUrl(event.url, { newTab: true }),
+ onClick: () => store.openUrl(event.url, { newTab: true, from: shownUrl(tab) }),
});
}
break;
diff --git a/studio/frontend/src/features/browser/prefs-store.ts b/studio/frontend/src/features/browser/prefs-store.ts
index c7e87576c85..0d186ef8adc 100644
--- a/studio/frontend/src/features/browser/prefs-store.ts
+++ b/studio/frontend/src/features/browser/prefs-store.ts
@@ -36,8 +36,8 @@ interface BrowserPrefsState {
/** Days visits are kept (HISTORY_RETENTION_DAYS); 0 for until cleared. */
historyRetentionDays: number;
saveDownloadHistory: boolean;
- /** Web build: a save dialog for each download, where the browser offers one. */
askWhereToSave: boolean;
+ askBeforeDownloading: boolean;
annotationScreenshots: AnnotationScreenshots;
setOpenLinksInBrowser: (value: boolean) => void;
setOpenFilesInBrowser: (value: boolean) => void;
@@ -55,6 +55,7 @@ interface BrowserPrefsState {
setHistoryRetentionDays: (value: number) => void;
setSaveDownloadHistory: (value: boolean) => void;
setAskWhereToSave: (value: boolean) => void;
+ setAskBeforeDownloading: (value: boolean) => void;
setAnnotationScreenshots: (value: AnnotationScreenshots) => void;
}
@@ -76,6 +77,7 @@ export const useBrowserPrefsStore = create<BrowserPrefsState>()(
historyRetentionDays: 0,
saveDownloadHistory: true,
askWhereToSave: false,
+ askBeforeDownloading: true,
annotationScreenshots: "never",
setOpenLinksInBrowser: (openLinksInBrowser) => set({ openLinksInBrowser }),
setOpenFilesInBrowser: (openFilesInBrowser) => set({ openFilesInBrowser }),
@@ -98,6 +100,7 @@ export const useBrowserPrefsStore = create<BrowserPrefsState>()(
setHistoryRetentionDays: (historyRetentionDays) => set({ historyRetentionDays }),
setSaveDownloadHistory: (saveDownloadHistory) => set({ saveDownloadHistory }),
setAskWhereToSave: (askWhereToSave) => set({ askWhereToSave }),
+ setAskBeforeDownloading: (askBeforeDownloading) => set({ askBeforeDownloading }),
setAnnotationScreenshots: (annotationScreenshots) => set({ annotationScreenshots }),
}),
{
diff --git a/studio/frontend/src/features/browser/store.ts b/studio/frontend/src/features/browser/store.ts
index 84ba9ff20f8..c6a8ef33d16 100644
--- a/studio/frontend/src/features/browser/store.ts
+++ b/studio/frontend/src/features/browser/store.ts
@@ -11,7 +11,14 @@ import { defaultZoom } from "./prefs-store";
export type BrowserEntry =
| { kind: "newtab" }
| { kind: "internal"; page: InternalPage }
- | { kind: "web"; url: string; method?: "GET" | "POST"; body?: string }
+ | {
+ kind: "web";
+ url: string;
+ method?: "GET" | "POST";
+ body?: string;
+ /** The page that sent the tab here (link, form, script, refresh); a file here downloads on its behalf. */
+ from?: string;
+ }
| {
kind: "file";
fileId: string;
@@ -118,6 +125,9 @@ const MAX_HISTORY = 50;
const cacheLimit = cacheLimits(reportedDeviceMemory());
const pageCache = new PageCache<BrowserEntry>(cacheLimit.maxPages, cacheLimit.maxTotalBytes);
+// The entry each page-driven navigation left, while it is still the one before it.
+const sentFrom = new WeakMap<BrowserEntry, BrowserEntry>();
+
const entryIds = new WeakMap<BrowserEntry, number>();
let nextEntryId = 0;
@@ -198,8 +208,10 @@ export function currentEntry(tab: BrowserTab): BrowserEntry {
return tab.history[tab.index] ?? { kind: "newtab" };
}
-function webEntry(url: string, method?: "GET" | "POST", body?: string): BrowserEntry {
- return method === "POST" ? { kind: "web", url, method, body } : { kind: "web", url: unwrapRedirect(url) };
+function webEntry(url: string, method?: "GET" | "POST", body?: string, from?: string): BrowserEntry {
+ const entry: BrowserEntry =
+ method === "POST" ? { kind: "web", url, method, body } : { kind: "web", url: unwrapRedirect(url) };
+ return from ? { ...entry, from } : entry;
}
// Pending file refreshes per tab, run in order, and the blobs they will compare.
@@ -279,14 +291,16 @@ type BrowserState = {
closeTabsToRight: (tabId: string) => void;
openUrl: (
url: string,
- options?: { newTab?: boolean; background?: boolean; method?: "GET" | "POST"; body?: string },
+ options?: { newTab?: boolean; background?: boolean; method?: "GET" | "POST"; body?: string; from?: string },
) => void;
openFile: (input: OpenFileInput) => void;
navigate: (
tabId: string,
- request: { url: string; method?: "GET" | "POST"; body?: string },
+ request: { url: string; method?: "GET" | "POST"; body?: string; from?: string },
options?: { replace?: boolean },
) => void;
+ /** A page-sent entry that became a download: back to that page and out of history, unless the tab moved on. */
+ leaveDownload: (tabId: string, entry: BrowserEntry) => void;
goBack: (tabId: string) => void;
goForward: (tabId: string) => void;
reload: (tabId: string) => void;
@@ -470,19 +484,19 @@ export const useBrowserStore = create<BrowserState>((set, get) => {
openUrl: (url, options) => {
if (!isWeb(url)) return;
if (options?.method === "POST") {
- openTab(createTab(webEntry(url, "POST", options.body ?? "")), options.background);
+ openTab(createTab(webEntry(url, "POST", options.body ?? "", options.from)), options.background);
return;
}
const target = unwrapRedirect(url);
const openKey = `url:${target}`;
const { activeTabId } = get();
if (options?.newTab === false && activeTabId) {
- get().navigate(activeTabId, { url: target });
+ get().navigate(activeTabId, { url: target, from: options.from });
set((state) => ({ open: true, openSequence: state.openSequence + 1 }));
return;
}
if (options?.newTab === undefined && focusExisting(openKey)) return;
- openTab(createTab(webEntry(target), openKey), options?.background);
+ openTab(createTab(webEntry(target, undefined, undefined, options?.from), openKey), options?.background);
},
openFile: ({ blob, name, contentType, plainText, key }) => {
const openKey = key ? `file:${key}` : null;
@@ -531,15 +545,24 @@ export const useBrowserStore = create<BrowserState>((set, get) => {
navigate: (tabId, request, options) => {
if (!isWeb(request.url)) return;
set((state) => ({
- tabs: patchTab(state.tabs, tabId, (tab) =>
- pushEntry(
- tab,
- webEntry(request.url, request.method, request.body),
- options?.replace ?? (nativeWebHistory && currentEntry(tab).kind === "web"),
- ),
- ),
+ tabs: patchTab(state.tabs, tabId, (tab) => {
+ const replace = options?.replace ?? (nativeWebHistory && currentEntry(tab).kind === "web");
+ const entry = webEntry(request.url, request.method, request.body, request.from);
+ if (request.from && !replace) sentFrom.set(entry, currentEntry(tab));
+ return pushEntry(tab, entry, replace);
+ }),
}));
},
+ leaveDownload: (tabId, entry) =>
+ set((state) => ({
+ tabs: patchTab(state.tabs, tabId, (tab) => {
+ const previous = tab.history[tab.index - 1];
+ if (currentEntry(tab) !== entry || !previous || sentFrom.get(entry) !== previous) return tab;
+ const history = tab.history.filter((candidate) => candidate !== entry);
+ pageCache.delete(entry);
+ return moveTo({ ...tab, history }, tab.index - 1);
+ }),
+ })),
goBack: (tabId) =>
set((state) => ({
tabs: patchTab(state.tabs, tabId, (tab) => (tab.index > 0 ? moveTo(tab, tab.index - 1) : tab)),
diff --git a/studio/frontend/src/features/browser/tab-view.tsx b/studio/frontend/src/features/browser/tab-view.tsx
index dfbc07a8cb1..04b69a78e9d 100644
--- a/studio/frontend/src/features/browser/tab-view.tsx
+++ b/studio/frontend/src/features/browser/tab-view.tsx
@@ -13,6 +13,8 @@ import { memo, useCallback, useEffect, useState } from "react";
import { fileNameFromUrl, hostOf } from "./address";
import { BrowserFetchError, type BrowserPage, fetchBrowserPage } from "./api";
import { proxiedFavicon } from "./favicon";
+import { saveBrowserDownload } from "./downloads";
+import { canShowFile } from "./file-kind";
import { FileView } from "./file-view";
import { BROWSER_FIND_TARGET, pageLoadedForFind, receiveFindResult } from "./find";
import { useBrowserHistoryStore } from "./history-store";
@@ -63,24 +65,32 @@ function safeFavicon(url: string | null): string | null {
}
}
+function pageAddress(tab: BrowserTab | undefined): string | undefined {
+ const entry = tab ? currentEntry(tab) : null;
+ return tab && entry?.kind === "web" ? (tab.displayUrl ?? entry.url) : undefined;
+}
+
function useFrameMessages(tabId: string, origin: string | null) {
const t = useT();
return useCallback(
(message: FrameMessage) => {
const store = useBrowserStore.getState();
switch (message.type) {
- case "navigate":
+ case "navigate": {
+ const from = pageAddress(store.tabs.find((candidate) => candidate.id === tabId));
if (message.newTab) {
store.openUrl(message.url, {
newTab: true,
background: message.background && !useBrowserPrefsStore.getState().switchToNewTabs,
method: message.method,
body: message.body,
+ from,
});
} else {
- store.navigate(tabId, message, { replace: message.replace });
+ store.navigate(tabId, { url: message.url, method: message.method, body: message.body, from }, { replace: message.replace });
}
break;
+ }
case "external":
openExternalLink(message.url);
break;
@@ -279,6 +289,15 @@ function WebPage({
cachePage(entry, page);
setState({ status: "ready", page });
show(page);
+ // A file the panel can't show downloads, as in a browser; fresh loads only, so returning to the tab doesn't ask again.
+ if (page.kind === "raw") {
+ const name = page.fileName ?? fileNameFromUrl(page.url);
+ if (!canShowFile(name, page.contentType)) {
+ // The sending page, else the address asked for (not the redirect target), so another site's "allow" can't cover it.
+ void saveBrowserDownload({ blob: page.blob, name, contentType: page.contentType, url: page.url, site: entry.from ?? url });
+ if (entry.kind === "web" && entry.from) useBrowserStore.getState().leaveDownload(tab.id, entry);
+ }
+ }
})
.catch((error: unknown) => {
if (controller.signal.aborted) return;
diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.ts
index 0c4b918a9c5..e59d9796002 100644
--- a/studio/frontend/src/features/settings/settings-search.ts
+++ b/studio/frontend/src/features/settings/settings-search.ts
@@ -158,6 +158,8 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {
"browser.importBookmarksSetting",
"browser.downloadsTitle",
"browser.askWhereToSaveSetting",
+ "browser.askBeforeDownloadingSetting",
+ "browser.downloadSitesSetting",
"browser.saveDownloadHistorySetting",
"browser.browsingDataTitle",
"browser.saveHistorySetting",
@@ -362,13 +364,10 @@ export function createSettingsSearchIndex({
// and searching Settings for "repair" answered "No settings found."
"settings.general.repairInstall.label",
],
+ browser: [...SETTINGS_SEARCH_INDEX.browser, "browser.downloadLocationSetting"],
about: SETTINGS_SEARCH_INDEX.about.filter(
(key) => key !== "settings.about.updates",
),
- // The row is web only.
- browser: SETTINGS_SEARCH_INDEX.browser.filter(
- (key) => key !== "browser.askWhereToSaveSetting",
- ),
};
}
diff --git a/studio/frontend/src/features/settings/tabs/browser-tab.tsx b/studio/frontend/src/features/settings/tabs/browser-tab.tsx
index 886f9ba5897..d82260cf742 100644
--- a/studio/frontend/src/features/settings/tabs/browser-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/browser-tab.tsx
@@ -13,6 +13,8 @@ import { Switch } from "@/components/ui/switch";
import {
type AnnotationScreenshots,
type BookmarksToolbarMode,
+ type DownloadFolder,
+ type DownloadSiteDecision,
ClearBrowsingDataDialog,
DEFAULT_ZOOM_STEPS,
HISTORY_RETENTION_DAYS,
@@ -24,8 +26,12 @@ import {
canScreenshot,
exportBookmarksFile,
importBookmarksFile,
+ nativeDownloadFolder,
+ pickNativeDownloadFolder,
+ resetNativeDownloadFolder,
useBrowserPrefsStore,
useBrowserStore,
+ useDownloadSitesStore,
useNativeBrowser,
} from "@/features/browser";
import { useChatRuntimeStore } from "@/features/chat";
@@ -33,6 +39,8 @@ import { type TranslationKey, useLocale, useT } from "@/i18n";
import { isTauri } from "@/lib/api-base";
import { isDownloadCancelled } from "@/lib/native-files";
import { toast } from "@/lib/toast";
+import { Cancel01Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
import { useEffect, useMemo, useRef, useState } from "react";
import { SettingsRow } from "../components/settings-row";
import { SettingsSection } from "../components/settings-section";
@@ -46,6 +54,93 @@ const RETENTION_LABELS: Record<number, TranslationKey> = {
1: "browser.retention.days1",
};
+function DownloadLocationRow() {
+ const t = useT();
+ const [folder, setFolder] = useState<DownloadFolder | null>(null);
+ useEffect(() => {
+ let live = true;
+ nativeDownloadFolder().then(
+ (current) => live && setFolder(current),
+ () => undefined,
+ );
+ return () => {
+ live = false;
+ };
+ }, []);
+ const failed = (error: unknown) => toast.error(error instanceof Error ? error.message : String(error));
+ const change = () =>
+ pickNativeDownloadFolder().then((picked) => picked && setFolder(picked), failed);
+ const reset = () => resetNativeDownloadFolder().then(setFolder, failed);
+ return (
+ <SettingsRow
+ label={t("browser.downloadLocationSetting")}
+ description={
+ <span className="break-all">
+ {folder ? (folder.custom ? folder.path : t("browser.downloadLocationDefault")) : null}
+ </span>
+ }
+ >
+ <div className="flex gap-2">
+ {folder?.custom ? (
+ <Button variant="ghost" size="sm" onClick={reset}>
+ {t("browser.downloadLocationReset")}
+ </Button>
+ ) : null}
+ <Button variant="outline" size="sm" onClick={change}>
+ {t("browser.downloadLocationChange")}
+ </Button>
+ </div>
+ </SettingsRow>
+ );
+}
+
+function DownloadSiteRows() {
+ const t = useT();
+ const sites = useDownloadSitesStore((state) => state.sites);
+ const { setSite: setDownloadSite } = useDownloadSitesStore.getState();
+ const origins = Object.keys(sites).sort();
+ return (
+ <SettingsRow
+ label={t("browser.downloadSitesSetting")}
+ description={t("browser.downloadSitesSettingDescription")}
+ below={
+ origins.length > 0 ? (
+ <ul className="flex w-full flex-col divide-y divide-border/60 rounded-lg border border-border/80">
+ {origins.map((origin) => (
+ <li key={origin} className="flex items-center gap-3 py-1.5 pl-3 pr-1.5">
+ <span className="min-w-0 flex-1 truncate text-sm text-foreground">{origin}</span>
+ <Select
+ value={sites[origin]}
+ onValueChange={(value) => setDownloadSite(origin, value as DownloadSiteDecision)}
+ >
+ <SelectTrigger className="w-40" aria-label={t("browser.downloadSitesFor", { host: origin })}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="allow">{t("browser.downloadSiteAllow")}</SelectItem>
+ <SelectItem value="block">{t("browser.downloadSiteBlock")}</SelectItem>
+ </SelectContent>
+ </Select>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-8"
+ aria-label={t("browser.downloadSitesRemove", { host: origin })}
+ onClick={() => setDownloadSite(origin, null)}
+ >
+ <HugeiconsIcon icon={Cancel01Icon} strokeWidth={1.75} className="size-4" />
+ </Button>
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <span className="w-full text-xs text-muted-foreground">{t("browser.downloadSitesNone")}</span>
+ )
+ }
+ />
+ );
+}
+
export function BrowserTab() {
const t = useT();
const locale = useLocale();
@@ -65,6 +160,7 @@ export function BrowserTab() {
const historyRetentionDays = useBrowserPrefsStore((state) => state.historyRetentionDays);
const saveDownloadHistory = useBrowserPrefsStore((state) => state.saveDownloadHistory);
const askWhereToSave = useBrowserPrefsStore((state) => state.askWhereToSave);
+ const askBeforeDownloading = useBrowserPrefsStore((state) => state.askBeforeDownloading);
const annotationScreenshots = useBrowserPrefsStore((state) => state.annotationScreenshots);
const {
setOpenLinksInBrowser,
@@ -82,6 +178,7 @@ export function BrowserTab() {
setHistoryRetentionDays,
setSaveDownloadHistory,
setAskWhereToSave,
+ setAskBeforeDownloading,
setAnnotationScreenshots,
} = useBrowserPrefsStore.getState();
const [clearOpen, setClearOpen] = useState(false);
@@ -353,22 +450,31 @@ export function BrowserTab() {
</SettingsSection>
<SettingsSection title={t("browser.downloadsTitle")}>
- {/* Web only: the desktop app asks for saved files, but page downloads go to Downloads. */}
- {isTauri ? null : (
- <SettingsRow
- label={t("browser.askWhereToSaveSetting")}
- description={t(
- canAsk ? "browser.askWhereToSaveSettingDescription" : "browser.askWhereToSaveUnsupported",
- )}
- >
- <Switch
- aria-label={t("browser.askWhereToSaveSetting")}
- checked={canAsk && askWhereToSave}
- disabled={!canAsk}
- onCheckedChange={setAskWhereToSave}
- />
- </SettingsRow>
- )}
+ {isTauri ? <DownloadLocationRow /> : null}
+ <SettingsRow
+ label={t("browser.askWhereToSaveSetting")}
+ description={t(
+ canAsk ? "browser.askWhereToSaveSettingDescription" : "browser.askWhereToSaveUnsupported",
+ )}
+ >
+ <Switch
+ aria-label={t("browser.askWhereToSaveSetting")}
+ checked={canAsk && askWhereToSave}
+ disabled={!canAsk}
+ onCheckedChange={setAskWhereToSave}
+ />
+ </SettingsRow>
+ <SettingsRow
+ label={t("browser.askBeforeDownloadingSetting")}
+ description={t("browser.askBeforeDownloadingSettingDescription")}
+ >
+ <Switch
+ aria-label={t("browser.askBeforeDownloadingSetting")}
+ checked={askBeforeDownloading}
+ onCheckedChange={setAskBeforeDownloading}
+ />
+ </SettingsRow>
+ <DownloadSiteRows />
<SettingsRow
label={t("browser.saveDownloadHistorySetting")}
description={t("browser.saveDownloadHistorySettingDescription")}
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 01e62129906..33b54d981c6 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -165,6 +165,29 @@ export const ar = {
askWhereToSaveSetting: "السؤال عن مكان حفظ كل ملف",
askWhereToSaveSettingDescription: "عرض نافذة حفظ للملفات التي تنزّلها في المتصفح.",
askWhereToSaveUnsupported: "يحفظ متصفح الويب لديك التنزيلات في مجلد التنزيلات الخاص به.",
+ downloadLocationSetting: "الموقع",
+ downloadLocationDefault: "مجلد التنزيلات في النظام",
+ downloadLocationChange: "تغيير",
+ downloadLocationReset: "إعادة تعيين",
+ askBeforeDownloadingSetting: "السؤال قبل التنزيل",
+ askBeforeDownloadingSettingDescription: "تأكيد الملفات القادمة من المواقع قبل حفظها.",
+ downloadSitesSetting: "أذونات التنزيل للمواقع",
+ downloadSitesSettingDescription: "المواقع التي اخترت السماح دائمًا بتنزيلاتها أو حظرها.",
+ downloadSitesNone: "حدّد «تذكّر للمرة القادمة» عند السؤال، وسيظهر الموقع هنا.",
+ downloadSitesFor: "التنزيلات من {host}",
+ downloadSitesRemove: "نسيان {host}",
+ downloadSiteAllow: "السماح دائمًا",
+ downloadSiteBlock: "الحظر دائمًا",
+ downloadPrompt: {
+ title: "هل تريد تنزيل هذا الملف؟",
+ description: "يريد {host} حفظ {name} على جهاز الكمبيوتر.",
+ remember: "تذكّر للمرة القادمة",
+ cancel: "إلغاء",
+ download: "تنزيل",
+ blocked: "تم حظر تنزيل من {host}.",
+ ready: "{name} جاهز للحفظ",
+ save: "حفظ",
+ },
saveDownloadHistorySetting: "الاحتفاظ بسجل التنزيلات",
saveDownloadHistorySettingDescription: "إدراج الملفات التي تنزّلها من المتصفح ضمن سجل التنزيلات.",
saveHistorySetting: "حفظ سجل التصفح",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 52611820277..cc08ef6cf52 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -165,6 +165,29 @@ export const de = {
askWhereToSaveSetting: "Für jede Datei fragen, wo sie gespeichert werden soll",
askWhereToSaveSettingDescription: "Zeigt einen Speichern-Dialog für Dateien, die du im Browser herunterlädst.",
askWhereToSaveUnsupported: "Dein Webbrowser speichert Downloads in seinem eigenen Download-Ordner.",
+ downloadLocationSetting: "Speicherort",
+ downloadLocationDefault: "System-Downloadordner",
+ downloadLocationChange: "Ändern",
+ downloadLocationReset: "Zurücksetzen",
+ askBeforeDownloadingSetting: "Vor dem Herunterladen fragen",
+ askBeforeDownloadingSettingDescription: "Dateien von Websites vor dem Speichern bestätigen.",
+ downloadSitesSetting: "Download-Berechtigungen für Websites",
+ downloadSitesSettingDescription: "Websites, deren Downloads du immer erlaubst oder blockierst.",
+ downloadSitesNone: "Aktiviere bei der Nachfrage „Für das nächste Mal merken“, dann erscheint die Website hier.",
+ downloadSitesFor: "Downloads von {host}",
+ downloadSitesRemove: "{host} vergessen",
+ downloadSiteAllow: "Immer erlauben",
+ downloadSiteBlock: "Immer blockieren",
+ downloadPrompt: {
+ title: "Diese Datei herunterladen?",
+ description: "{host} möchte {name} auf deinem Computer speichern.",
+ remember: "Für das nächste Mal merken",
+ cancel: "Abbrechen",
+ download: "Herunterladen",
+ blocked: "Ein Download von {host} wurde blockiert.",
+ ready: "{name} kann gespeichert werden",
+ save: "Speichern",
+ },
saveDownloadHistorySetting: "Downloadverlauf behalten",
saveDownloadHistorySettingDescription: "Aus dem Browser heruntergeladene Dateien unter Downloadverlauf auflisten.",
saveHistorySetting: "Browserverlauf speichern",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index a20f730b4f4..d5aeec4e71e 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -162,6 +162,29 @@ export const en = {
askWhereToSaveSetting: "Ask where to save each file",
askWhereToSaveSettingDescription: "Show a save dialog for files you download in the browser.",
askWhereToSaveUnsupported: "Your web browser saves downloads to its own downloads folder.",
+ downloadLocationSetting: "Location",
+ downloadLocationDefault: "System Downloads folder",
+ downloadLocationChange: "Change",
+ downloadLocationReset: "Reset",
+ askBeforeDownloadingSetting: "Ask before downloading",
+ askBeforeDownloadingSettingDescription: "Confirm files from websites before they're saved.",
+ downloadSitesSetting: "Site download permissions",
+ downloadSitesSettingDescription: "Sites you chose to always allow or block downloads from.",
+ downloadSitesNone: "Check Remember for next time when asked, and the site shows up here.",
+ downloadSitesFor: "Downloads from {host}",
+ downloadSitesRemove: "Forget {host}",
+ downloadSiteAllow: "Always allow",
+ downloadSiteBlock: "Always block",
+ downloadPrompt: {
+ title: "Download this file?",
+ description: "{host} wants to save {name} to your computer.",
+ remember: "Remember for next time",
+ cancel: "Cancel",
+ download: "Download",
+ blocked: "Blocked a download from {host}.",
+ ready: "{name} is ready to save",
+ save: "Save",
+ },
saveDownloadHistorySetting: "Keep download history",
saveDownloadHistorySettingDescription: "List files you download from the browser under Download history.",
saveHistorySetting: "Save browsing history",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index aaf89782c06..74f4d02692c 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -165,6 +165,29 @@ export const es = {
askWhereToSaveSetting: "Preguntar dónde guardar cada archivo",
askWhereToSaveSettingDescription: "Muestra un cuadro para guardar los archivos que descargas en el navegador.",
askWhereToSaveUnsupported: "Tu navegador web guarda las descargas en su propia carpeta de descargas.",
+ downloadLocationSetting: "Ubicación",
+ downloadLocationDefault: "Carpeta de descargas del sistema",
+ downloadLocationChange: "Cambiar",
+ downloadLocationReset: "Restablecer",
+ askBeforeDownloadingSetting: "Preguntar antes de descargar",
+ askBeforeDownloadingSettingDescription: "Confirma los archivos de sitios web antes de guardarlos.",
+ downloadSitesSetting: "Permisos de descarga por sitio",
+ downloadSitesSettingDescription: "Sitios cuyas descargas elegiste permitir o bloquear siempre.",
+ downloadSitesNone: "Marca Recordar para la próxima vez cuando se te pregunte y el sitio aparecerá aquí.",
+ downloadSitesFor: "Descargas de {host}",
+ downloadSitesRemove: "Olvidar {host}",
+ downloadSiteAllow: "Permitir siempre",
+ downloadSiteBlock: "Bloquear siempre",
+ downloadPrompt: {
+ title: "¿Descargar este archivo?",
+ description: "{host} quiere guardar {name} en tu equipo.",
+ remember: "Recordar para la próxima vez",
+ cancel: "Cancelar",
+ download: "Descargar",
+ blocked: "Se bloqueó una descarga de {host}.",
+ ready: "{name} está listo para guardar",
+ save: "Guardar",
+ },
saveDownloadHistorySetting: "Conservar el historial de descargas",
saveDownloadHistorySettingDescription: "Lista los archivos que descargas del navegador en Historial de descargas.",
saveHistorySetting: "Guardar historial de navegación",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index a2bc940933a..14f2cfaa643 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -165,6 +165,29 @@ export const fr = {
askWhereToSaveSetting: "Demander où enregistrer chaque fichier",
askWhereToSaveSettingDescription: "Afficher une boîte d'enregistrement pour les fichiers téléchargés dans le navigateur.",
askWhereToSaveUnsupported: "Votre navigateur web enregistre les téléchargements dans son propre dossier.",
+ downloadLocationSetting: "Emplacement",
+ downloadLocationDefault: "Dossier Téléchargements du système",
+ downloadLocationChange: "Modifier",
+ downloadLocationReset: "Réinitialiser",
+ askBeforeDownloadingSetting: "Demander avant de télécharger",
+ askBeforeDownloadingSettingDescription: "Confirmer les fichiers provenant de sites web avant de les enregistrer.",
+ downloadSitesSetting: "Autorisations de téléchargement par site",
+ downloadSitesSettingDescription: "Sites dont vous avez choisi de toujours autoriser ou bloquer les téléchargements.",
+ downloadSitesNone: "Cochez Se souvenir pour la prochaine fois lorsqu'on vous le demande, et le site apparaîtra ici.",
+ downloadSitesFor: "Téléchargements depuis {host}",
+ downloadSitesRemove: "Oublier {host}",
+ downloadSiteAllow: "Toujours autoriser",
+ downloadSiteBlock: "Toujours bloquer",
+ downloadPrompt: {
+ title: "Télécharger ce fichier ?",
+ description: "{host} souhaite enregistrer {name} sur votre ordinateur.",
+ remember: "Se souvenir pour la prochaine fois",
+ cancel: "Annuler",
+ download: "Télécharger",
+ blocked: "Un téléchargement depuis {host} a été bloqué.",
+ ready: "{name} est prêt à être enregistré",
+ save: "Enregistrer",
+ },
saveDownloadHistorySetting: "Conserver l'historique des téléchargements",
saveDownloadHistorySettingDescription: "Lister les fichiers téléchargés depuis le navigateur dans l'historique des téléchargements.",
saveHistorySetting: "Enregistrer l'historique de navigation",
diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.ts
index 8d68d6d92ae..c1df5051732 100644
--- a/studio/frontend/src/i18n/locales/he.ts
+++ b/studio/frontend/src/i18n/locales/he.ts
@@ -174,6 +174,29 @@ export const he = {
askWhereToSaveSetting: "לשאול היכן לשמור כל קובץ",
askWhereToSaveSettingDescription: "הצגת חלון שמירה עבור קבצים שמורידים בדפדפן.",
askWhereToSaveUnsupported: "דפדפן האינטרנט שלכם שומר הורדות בתיקיית ההורדות שלו.",
+ downloadLocationSetting: "מיקום",
+ downloadLocationDefault: "תיקיית ההורדות של המערכת",
+ downloadLocationChange: "שינוי",
+ downloadLocationReset: "איפוס",
+ askBeforeDownloadingSetting: "לשאול לפני הורדה",
+ askBeforeDownloadingSettingDescription: "אישור קבצים מאתרים לפני שהם נשמרים.",
+ downloadSitesSetting: "הרשאות הורדה לאתרים",
+ downloadSitesSettingDescription: "אתרים שבחרתם תמיד לאפשר או לחסום מהם הורדות.",
+ downloadSitesNone: "סמנו \"לזכור לפעם הבאה\" כשתישאלו, והאתר יופיע כאן.",
+ downloadSitesFor: "הורדות מ-{host}",
+ downloadSitesRemove: "לשכוח את {host}",
+ downloadSiteAllow: "תמיד לאפשר",
+ downloadSiteBlock: "תמיד לחסום",
+ downloadPrompt: {
+ title: "להוריד את הקובץ הזה?",
+ description: "{host} רוצה לשמור את {name} במחשב שלכם.",
+ remember: "לזכור לפעם הבאה",
+ cancel: "ביטול",
+ download: "הורדה",
+ blocked: "נחסמה הורדה מ-{host}.",
+ ready: "{name} מוכן לשמירה",
+ save: "שמירה",
+ },
saveDownloadHistorySetting: "שמירת היסטוריית הורדות",
saveDownloadHistorySettingDescription: "הצגת קבצים שהורדתם מהדפדפן תחת היסטוריית הורדות.",
saveHistorySetting: "שמירת היסטוריית גלישה",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index bc84dfe888c..3d7e2450688 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -165,6 +165,29 @@ export const hi = {
askWhereToSaveSetting: "हर फ़ाइल के लिए पूछें कि कहाँ सहेजना है",
askWhereToSaveSettingDescription: "ब्राउज़र में डाउनलोड की गई फ़ाइलों के लिए सहेजने का डायलॉग दिखाएँ।",
askWhereToSaveUnsupported: "आपका वेब ब्राउज़र डाउनलोड को अपने डाउनलोड फ़ोल्डर में सहेजता है।",
+ downloadLocationSetting: "स्थान",
+ downloadLocationDefault: "सिस्टम डाउनलोड फ़ोल्डर",
+ downloadLocationChange: "बदलें",
+ downloadLocationReset: "रीसेट करें",
+ askBeforeDownloadingSetting: "डाउनलोड से पहले पूछें",
+ askBeforeDownloadingSettingDescription: "वेबसाइटों की फ़ाइलें सहेजने से पहले पुष्टि करें।",
+ downloadSitesSetting: "साइट डाउनलोड अनुमतियाँ",
+ downloadSitesSettingDescription: "वे साइटें जिनसे डाउनलोड को आपने हमेशा अनुमति देना या ब्लॉक करना चुना है।",
+ downloadSitesNone: "पूछे जाने पर 'अगली बार के लिए याद रखें' चुनें, फिर साइट यहाँ दिखेगी।",
+ downloadSitesFor: "{host} से डाउनलोड",
+ downloadSitesRemove: "{host} भूलें",
+ downloadSiteAllow: "हमेशा अनुमति दें",
+ downloadSiteBlock: "हमेशा ब्लॉक करें",
+ downloadPrompt: {
+ title: "यह फ़ाइल डाउनलोड करें?",
+ description: "{host} आपके कंप्यूटर पर {name} सहेजना चाहता है।",
+ remember: "अगली बार के लिए याद रखें",
+ cancel: "रद्द करें",
+ download: "डाउनलोड करें",
+ blocked: "{host} से एक डाउनलोड ब्लॉक किया गया।",
+ ready: "{name} सहेजने के लिए तैयार है",
+ save: "सहेजें",
+ },
saveDownloadHistorySetting: "डाउनलोड इतिहास रखें",
saveDownloadHistorySettingDescription: "ब्राउज़र से डाउनलोड की गई फ़ाइलों को डाउनलोड इतिहास में दिखाएँ।",
saveHistorySetting: "ब्राउज़िंग इतिहास सहेजें",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 04a1cad3be9..6564e99654f 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -164,6 +164,29 @@ export const it = {
askWhereToSaveSetting: "Chiedi dove salvare ogni file",
askWhereToSaveSettingDescription: "Mostra una finestra di salvataggio per i file scaricati nel browser.",
askWhereToSaveUnsupported: "Il tuo browser web salva i download nella propria cartella dei download.",
+ downloadLocationSetting: "Posizione",
+ downloadLocationDefault: "Cartella Download di sistema",
+ downloadLocationChange: "Cambia",
+ downloadLocationReset: "Ripristina",
+ askBeforeDownloadingSetting: "Chiedi prima di scaricare",
+ askBeforeDownloadingSettingDescription: "Conferma i file dai siti web prima di salvarli.",
+ downloadSitesSetting: "Autorizzazioni di download per sito",
+ downloadSitesSettingDescription: "Siti da cui hai scelto di consentire o bloccare sempre i download.",
+ downloadSitesNone: "Spunta Ricorda per la prossima volta quando ti viene chiesto e il sito apparirà qui.",
+ downloadSitesFor: "Download da {host}",
+ downloadSitesRemove: "Dimentica {host}",
+ downloadSiteAllow: "Consenti sempre",
+ downloadSiteBlock: "Blocca sempre",
+ downloadPrompt: {
+ title: "Scaricare questo file?",
+ description: "{host} vuole salvare {name} sul tuo computer.",
+ remember: "Ricorda per la prossima volta",
+ cancel: "Annulla",
+ download: "Scarica",
+ blocked: "Bloccato un download da {host}.",
+ ready: "{name} è pronto per il salvataggio",
+ save: "Salva",
+ },
saveDownloadHistorySetting: "Conserva la cronologia dei download",
saveDownloadHistorySettingDescription: "Elenca i file scaricati dal browser in Cronologia download.",
saveHistorySetting: "Salva la cronologia di navigazione",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 6cf41eced3d..be69db5263e 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -166,6 +166,29 @@ export const ja = {
askWhereToSaveSetting: "ファイルごとに保存先を確認する",
askWhereToSaveSettingDescription: "ブラウザでダウンロードするファイルに保存ダイアログを表示します。",
askWhereToSaveUnsupported: "お使いの Web ブラウザは、独自のダウンロードフォルダにファイルを保存します。",
+ downloadLocationSetting: "保存先",
+ downloadLocationDefault: "システムのダウンロードフォルダ",
+ downloadLocationChange: "変更",
+ downloadLocationReset: "リセット",
+ askBeforeDownloadingSetting: "ダウンロード前に確認",
+ askBeforeDownloadingSettingDescription: "Web サイトからのファイルを保存する前に確認します。",
+ downloadSitesSetting: "サイトごとのダウンロード許可",
+ downloadSitesSettingDescription: "ダウンロードを常に許可またはブロックすると選んだサイトです。",
+ downloadSitesNone: "確認時に「次回から記憶する」にチェックすると、そのサイトがここに表示されます。",
+ downloadSitesFor: "{host} からのダウンロード",
+ downloadSitesRemove: "{host} を削除",
+ downloadSiteAllow: "常に許可",
+ downloadSiteBlock: "常にブロック",
+ downloadPrompt: {
+ title: "このファイルをダウンロードしますか?",
+ description: "{host} が {name} をこのコンピュータに保存しようとしています。",
+ remember: "次回から記憶する",
+ cancel: "キャンセル",
+ download: "ダウンロード",
+ blocked: "{host} からのダウンロードをブロックしました。",
+ ready: "{name} を保存できます",
+ save: "保存",
+ },
saveDownloadHistorySetting: "ダウンロード履歴を保持",
saveDownloadHistorySettingDescription: "ブラウザからダウンロードしたファイルをダウンロード履歴に表示します。",
saveHistorySetting: "閲覧履歴を保存",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 70d7ebd8237..9fd4a17637b 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -165,6 +165,29 @@ export const ko = {
askWhereToSaveSetting: "파일마다 저장 위치 묻기",
askWhereToSaveSettingDescription: "브라우저에서 다운로드하는 파일에 저장 대화상자를 표시합니다.",
askWhereToSaveUnsupported: "웹 브라우저가 자체 다운로드 폴더에 파일을 저장합니다.",
+ downloadLocationSetting: "위치",
+ downloadLocationDefault: "시스템 다운로드 폴더",
+ downloadLocationChange: "변경",
+ downloadLocationReset: "재설정",
+ askBeforeDownloadingSetting: "다운로드 전에 묻기",
+ askBeforeDownloadingSettingDescription: "웹사이트의 파일을 저장하기 전에 확인합니다.",
+ downloadSitesSetting: "사이트별 다운로드 권한",
+ downloadSitesSettingDescription: "다운로드를 항상 허용하거나 차단하기로 선택한 사이트입니다.",
+ downloadSitesNone: "물어볼 때 '다음에도 기억'을 선택하면 해당 사이트가 여기에 표시됩니다.",
+ downloadSitesFor: "{host}의 다운로드",
+ downloadSitesRemove: "{host} 삭제",
+ downloadSiteAllow: "항상 허용",
+ downloadSiteBlock: "항상 차단",
+ downloadPrompt: {
+ title: "이 파일을 다운로드할까요?",
+ description: "{host}에서 {name}을(를) 컴퓨터에 저장하려고 합니다.",
+ remember: "다음에도 기억",
+ cancel: "취소",
+ download: "다운로드",
+ blocked: "{host}의 다운로드를 차단했습니다.",
+ ready: "{name}을(를) 저장할 수 있습니다",
+ save: "저장",
+ },
saveDownloadHistorySetting: "다운로드 기록 유지",
saveDownloadHistorySettingDescription: "브라우저에서 다운로드한 파일을 다운로드 기록에 표시합니다.",
saveHistorySetting: "방문 기록 저장",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index c42ebc4295b..5ebe79c5e0d 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -165,6 +165,29 @@ export const ptBR = {
askWhereToSaveSetting: "Perguntar onde salvar cada arquivo",
askWhereToSaveSettingDescription: "Mostra uma janela para salvar os arquivos que você baixa no navegador.",
askWhereToSaveUnsupported: "Seu navegador salva os downloads na própria pasta de downloads.",
+ downloadLocationSetting: "Local",
+ downloadLocationDefault: "Pasta de downloads do sistema",
+ downloadLocationChange: "Alterar",
+ downloadLocationReset: "Redefinir",
+ askBeforeDownloadingSetting: "Perguntar antes de baixar",
+ askBeforeDownloadingSettingDescription: "Confirme arquivos de sites antes de salvá-los.",
+ downloadSitesSetting: "Permissões de download por site",
+ downloadSitesSettingDescription: "Sites dos quais você escolheu sempre permitir ou bloquear downloads.",
+ downloadSitesNone: "Marque Lembrar na próxima vez quando for perguntado, e o site aparecerá aqui.",
+ downloadSitesFor: "Downloads de {host}",
+ downloadSitesRemove: "Esquecer {host}",
+ downloadSiteAllow: "Sempre permitir",
+ downloadSiteBlock: "Sempre bloquear",
+ downloadPrompt: {
+ title: "Baixar este arquivo?",
+ description: "{host} quer salvar {name} no seu computador.",
+ remember: "Lembrar na próxima vez",
+ cancel: "Cancelar",
+ download: "Baixar",
+ blocked: "Um download de {host} foi bloqueado.",
+ ready: "{name} está pronto para salvar",
+ save: "Salvar",
+ },
saveDownloadHistorySetting: "Manter histórico de downloads",
saveDownloadHistorySettingDescription: "Lista os arquivos baixados do navegador em Histórico de downloads.",
saveHistorySetting: "Salvar histórico de navegação",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 51e64796aad..bff7c0ceac6 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -165,6 +165,29 @@ export const ru = {
askWhereToSaveSetting: "Спрашивать, куда сохранять каждый файл",
askWhereToSaveSettingDescription: "Показывать диалог сохранения для файлов, загружаемых в браузере.",
askWhereToSaveUnsupported: "Ваш веб-браузер сохраняет загрузки в свою папку загрузок.",
+ downloadLocationSetting: "Расположение",
+ downloadLocationDefault: "Системная папка загрузок",
+ downloadLocationChange: "Изменить",
+ downloadLocationReset: "Сбросить",
+ askBeforeDownloadingSetting: "Спрашивать перед загрузкой",
+ askBeforeDownloadingSettingDescription: "Подтверждать файлы с веб-сайтов перед сохранением.",
+ downloadSitesSetting: "Разрешения на загрузку для сайтов",
+ downloadSitesSettingDescription: "Сайты, загрузки с которых вы решили всегда разрешать или блокировать.",
+ downloadSitesNone: "Отметьте «Запомнить на будущее» при запросе, и сайт появится здесь.",
+ downloadSitesFor: "Загрузки с {host}",
+ downloadSitesRemove: "Забыть {host}",
+ downloadSiteAllow: "Всегда разрешать",
+ downloadSiteBlock: "Всегда блокировать",
+ downloadPrompt: {
+ title: "Загрузить этот файл?",
+ description: "{host} хочет сохранить {name} на ваш компьютер.",
+ remember: "Запомнить на будущее",
+ cancel: "Отмена",
+ download: "Загрузить",
+ blocked: "Загрузка с {host} заблокирована.",
+ ready: "Файл {name} готов к сохранению",
+ save: "Сохранить",
+ },
saveDownloadHistorySetting: "Хранить историю загрузок",
saveDownloadHistorySettingDescription: "Показывать файлы, загруженные из браузера, в истории загрузок.",
saveHistorySetting: "Сохранять историю просмотров",
diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.ts
index 1f68081e587..6377807e162 100644
--- a/studio/frontend/src/i18n/locales/sv.ts
+++ b/studio/frontend/src/i18n/locales/sv.ts
@@ -176,6 +176,29 @@ export const sv = {
askWhereToSaveSetting: "Fråga var varje fil ska sparas",
askWhereToSaveSettingDescription: "Visa en spara-dialog för filer du hämtar i webbläsaren.",
askWhereToSaveUnsupported: "Din webbläsare sparar hämtade filer i sin egen mapp för hämtade filer.",
+ downloadLocationSetting: "Plats",
+ downloadLocationDefault: "Systemets mapp för hämtade filer",
+ downloadLocationChange: "Ändra",
+ downloadLocationReset: "Återställ",
+ askBeforeDownloadingSetting: "Fråga innan hämtning",
+ askBeforeDownloadingSettingDescription: "Bekräfta filer från webbplatser innan de sparas.",
+ downloadSitesSetting: "Behörigheter för hämtning per webbplats",
+ downloadSitesSettingDescription: "Webbplatser du har valt att alltid tillåta eller blockera hämtningar från.",
+ downloadSitesNone: "Markera Kom ihåg till nästa gång när du tillfrågas, så visas webbplatsen här.",
+ downloadSitesFor: "Hämtningar från {host}",
+ downloadSitesRemove: "Glöm {host}",
+ downloadSiteAllow: "Tillåt alltid",
+ downloadSiteBlock: "Blockera alltid",
+ downloadPrompt: {
+ title: "Hämta den här filen?",
+ description: "{host} vill spara {name} på din dator.",
+ remember: "Kom ihåg till nästa gång",
+ cancel: "Avbryt",
+ download: "Hämta",
+ blocked: "En hämtning från {host} blockerades.",
+ ready: "{name} är redo att sparas",
+ save: "Spara",
+ },
saveDownloadHistorySetting: "Behåll hämtningshistorik",
saveDownloadHistorySettingDescription: "Lista filer du hämtar från webbläsaren under Hämtningshistorik.",
saveHistorySetting: "Spara webbhistorik",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 03bbb56efb0..962cd9e39c6 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -165,6 +165,29 @@ export const zhCN = {
askWhereToSaveSetting: "每次询问文件保存位置",
askWhereToSaveSettingDescription: "为在浏览器中下载的文件显示保存对话框。",
askWhereToSaveUnsupported: "你的网页浏览器会将下载内容保存到其自己的下载文件夹。",
+ downloadLocationSetting: "位置",
+ downloadLocationDefault: "系统下载文件夹",
+ downloadLocationChange: "更改",
+ downloadLocationReset: "重置",
+ askBeforeDownloadingSetting: "下载前询问",
+ askBeforeDownloadingSettingDescription: "保存来自网站的文件前先确认。",
+ downloadSitesSetting: "网站下载权限",
+ downloadSitesSettingDescription: "你选择始终允许或阻止下载的网站。",
+ downloadSitesNone: "在询问时勾选“下次记住”,该网站就会显示在这里。",
+ downloadSitesFor: "来自 {host} 的下载",
+ downloadSitesRemove: "忘记 {host}",
+ downloadSiteAllow: "始终允许",
+ downloadSiteBlock: "始终阻止",
+ downloadPrompt: {
+ title: "要下载此文件吗?",
+ description: "{host} 想要将 {name} 保存到你的电脑。",
+ remember: "下次记住",
+ cancel: "取消",
+ download: "下载",
+ blocked: "已阻止来自 {host} 的下载。",
+ ready: "{name} 已可保存",
+ save: "保存",
+ },
saveDownloadHistorySetting: "保留下载记录",
saveDownloadHistorySettingDescription: "在下载记录中列出从浏览器下载的文件。",
saveHistorySetting: "保存浏览记录",
diff --git a/studio/frontend/tests/browser-settings.test.ts b/studio/frontend/tests/browser-settings.test.ts
index ce22de927ad..5ad8042a405 100644
--- a/studio/frontend/tests/browser-settings.test.ts
+++ b/studio/frontend/tests/browser-settings.test.ts
@@ -271,3 +271,160 @@ test("a page the reader set to 100% keeps it after a fetched file", async () =>
assert.equal(zoom(), 1);
useBrowserPrefsStore.getState().setDefaultZoom(1);
});
+
+test("a site's download answer is remembered, changed and forgotten, per account", async () => {
+ const { useDownloadSitesStore } = await import("../src/features/browser/download-sites-store.ts");
+ const { accountDatabaseName } = await import("../src/lib/account-transition.ts");
+ const sites = useDownloadSitesStore.getState();
+ sites.setSite("example.com", "allow");
+ sites.setSite("example.org", "block");
+ assert.deepEqual(useDownloadSitesStore.getState().sites, { "example.com": "allow", "example.org": "block" });
+ sites.setSite("example.com", "block");
+ sites.setSite("example.org", null);
+ assert.deepEqual(useDownloadSitesStore.getState().sites, { "example.com": "block" });
+ const name = useDownloadSitesStore.persist.getOptions().name;
+ assert.equal(name, accountDatabaseName("unsloth_browser_download_sites"));
+ assert.notEqual(name, "unsloth_browser_download_sites");
+ assert.ok(data.has(name!));
+ const prefs = JSON.parse(data.get("unsloth_browser_prefs") ?? "{}") as { state?: Record<string, unknown> };
+ assert.equal(prefs.state?.downloadSites, undefined);
+ assert.equal(useBrowserPrefsStore.getState().askBeforeDownloading, true);
+ sites.setSite("example.com", null);
+});
+
+test("a remembered answer settles the site's other waiting downloads", async () => {
+ const { approveDownload, answerDownload, useApprovalStore } = await import(
+ "../src/features/browser/download-approval-queue.ts"
+ );
+ const { useDownloadSitesStore } = await import("../src/features/browser/download-sites-store.ts");
+ const first = approveDownload("https://a.example/1.zip", "1.zip");
+ const second = approveDownload("https://a.example/2.zip", "2.zip");
+ const other = approveDownload("https://b.example/3.zip", "3.zip");
+ answerDownload(useApprovalStore.getState().queue[0], false, true);
+ assert.equal(await first, false);
+ assert.equal(await second, false);
+ assert.deepEqual(useApprovalStore.getState().queue.map((request) => request.origin), ["https://b.example"]);
+ assert.equal(useDownloadSitesStore.getState().sites["https://a.example"], "block");
+ const fourth = approveDownload("https://b.example/4.zip", "4.zip");
+ answerDownload(useApprovalStore.getState().queue[0], true, false);
+ assert.equal(await other, true);
+ assert.equal(useApprovalStore.getState().queue.length, 1);
+ answerDownload(useApprovalStore.getState().queue[0], true, false);
+ assert.equal(await fourth, true);
+ assert.equal(useDownloadSitesStore.getState().sites["https://b.example"], undefined);
+ useDownloadSitesStore.getState().setSite("https://a.example", null);
+});
+
+test("download answers are kept per origin, never for every site", async () => {
+ const { downloadSiteOf: siteOf } = await import("../src/features/browser/download-approval-queue.ts");
+ // A blob: URL is its creator's; an opaque one, or data: and about:, belongs to no site.
+ assert.equal(siteOf("blob:https://a.example/uuid"), "https://a.example");
+ assert.equal(siteOf("blob:null/uuid"), "");
+ assert.equal(siteOf("data:text/plain,x"), "");
+ assert.equal(siteOf("about:blank"), "");
+ const { approveDownload, answerDownload, useApprovalStore } = await import(
+ "../src/features/browser/download-approval-queue.ts"
+ );
+ const { useDownloadSitesStore } = await import("../src/features/browser/download-sites-store.ts");
+ const blob = approveDownload("blob:null/uuid", "file.bin", "blob:null/uuid");
+ const request = useApprovalStore.getState().queue[0];
+ assert.equal(request.origin, "");
+ answerDownload(request, true, true);
+ assert.equal(await blob, true);
+ assert.deepEqual(useDownloadSitesStore.getState().sites, {});
+ const paged = approveDownload("blob:https://cdn.example/uuid", "file.bin", "https://a.example/page");
+ assert.equal(useApprovalStore.getState().queue[0].origin, "https://a.example");
+ answerDownload(useApprovalStore.getState().queue[0], true, true);
+ assert.equal(await paged, true);
+ assert.deepEqual(useDownloadSitesStore.getState().sites, { "https://a.example": "allow" });
+ // Another scheme, port or subdomain is another site: it is asked about again.
+ const { downloadSiteOf } = await import("../src/features/browser/download-approval-queue.ts");
+ assert.equal(downloadSiteOf("https://www.a.example/x"), "https://www.a.example");
+ assert.equal(downloadSiteOf("http://a.example:8443/x"), "http://a.example:8443");
+ const other = approveDownload("http://a.example:8443/f.zip", "f.zip");
+ assert.equal(useApprovalStore.getState().queue.length, 1);
+ answerDownload(useApprovalStore.getState().queue[0], false, false);
+ assert.equal(await other, false);
+ assert.equal(await approveDownload("https://a.example/g.zip", "g.zip"), true);
+ useDownloadSitesStore.getState().setSite("https://a.example", null);
+});
+
+test("a download whose click has expired waits for Save rather than skip the save dialog", async () => {
+ const picked: string[] = [];
+ const written: Blob[] = [];
+ let active = false;
+ // Chromium's picker refuses to open without a recent click.
+ Object.assign(globalThis, {
+ showSaveFilePicker: async ({ suggestedName }: { suggestedName: string }) => {
+ if (!active) throw new DOMException("Must be handling a user gesture", "SecurityError");
+ picked.push(suggestedName);
+ return {
+ name: suggestedName,
+ createWritable: async () => ({ write: async (data: Blob) => void written.push(data), close: async () => {} }),
+ };
+ },
+ });
+ Object.defineProperty(globalThis, "navigator", { value: { userActivation: { get isActive() { return active; } } }, configurable: true });
+ const { saveBrowserDownload } = await import("../src/features/browser/downloads.ts");
+ const prefs = useBrowserPrefsStore.getState();
+ prefs.setAskWhereToSave(true);
+ prefs.setAskBeforeDownloading(false);
+ (globalThis as { __toasts?: unknown[] }).__toasts = [];
+ const blob = new Blob(["x"]);
+ await saveBrowserDownload({ blob, name: "setup.dmg", contentType: "application/octet-stream", url: "https://a.example/setup.dmg" });
+ const toasts = (globalThis as { __toasts?: { message: string; options?: { action?: { onClick: () => void } } }[] }).__toasts!;
+ assert.equal(toasts.length, 1);
+ assert.equal(toasts[0].message, "browser.downloadPrompt.ready");
+ assert.deepEqual(picked, []);
+ active = true;
+ toasts[0].options!.action!.onClick();
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ assert.deepEqual(picked, ["setup.dmg"]);
+ assert.equal(written.length, 1);
+ prefs.setAskWhereToSave(false);
+ prefs.setAskBeforeDownloading(true);
+ delete (globalThis as { showSaveFilePicker?: unknown }).showSaveFilePicker;
+});
+
+test("a file a page sends the tab to is asked about for that page, not the file's site", async () => {
+ const { useBrowserStore, currentEntry } = await import("../src/features/browser/store.ts");
+ 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 store = useBrowserStore.getState();
+ store.openUrl("https://a.example/page", { newTab: true });
+ const tabId = useBrowserStore.getState().activeTabId!;
+ store.navigate(tabId, { url: "https://b.example/setup.zip", from: "https://a.example/page" });
+ const tab = useBrowserStore.getState().tabs.find((candidate) => candidate.id === tabId)!;
+ const entry = currentEntry(tab);
+ assert.ok(entry.kind === "web");
+ assert.equal(entry.from, "https://a.example/page");
+ store.navigate(tabId, { url: "https://b.example/other.zip" });
+ const typed = currentEntry(useBrowserStore.getState().tabs.find((candidate) => candidate.id === tabId)!);
+ assert.ok(typed.kind === "web" && typed.from === undefined);
+
+ // b.example is trusted, but a.example sent the tab there: still asked, for a.example.
+ useDownloadSitesStore.getState().setSite("https://b.example", "allow");
+ const blob = new Blob(["x"]);
+ const saving = saveBrowserDownload({ blob, name: "setup.zip", contentType: "application/zip", url: "https://b.example/setup.zip", site: entry.from });
+ 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);
+ await saving;
+ useDownloadSitesStore.getState().setSite("https://b.example", null);
+ store.closeTab(tabId);
+});
+
+test("a blocked site's blob: page can't download past the block", async () => {
+ const { approveDownload } = await import("../src/features/browser/download-approval-queue.ts");
+ const { useDownloadSitesStore } = await import("../src/features/browser/download-sites-store.ts");
+ const prefs = useBrowserPrefsStore.getState();
+ prefs.setAskBeforeDownloading(false);
+ useDownloadSitesStore.getState().setSite("https://a.example", "block");
+ assert.equal(await approveDownload("blob:https://a.example/f", "f.zip", "blob:https://a.example/doc"), false);
+ assert.equal(await approveDownload("https://cdn.example/f.zip", "f.zip", "https://b.example/"), true);
+ useDownloadSitesStore.getState().setSite("https://a.example", null);
+ prefs.setAskBeforeDownloading(true);
+});
diff --git a/studio/frontend/tests/browser-store-reopen.test.ts b/studio/frontend/tests/browser-store-reopen.test.ts
index a414f4ed51e..7ff3a1a1a86 100644
--- a/studio/frontend/tests/browser-store-reopen.test.ts
+++ b/studio/frontend/tests/browser-store-reopen.test.ts
@@ -187,3 +187,34 @@ test("going Back to a keyed file restores its key, so its card finds the tab aga
store.goBack(copy?.id ?? "");
assert.equal(useBrowserStore.getState().tabs.find((candidate) => candidate.id === copy?.id)?.openKey, null);
});
+
+test("a page's link that turns out to be a download leaves that page showing", () => {
+ const store = useBrowserStore.getState();
+ store.openUrl("https://a.example/page", { newTab: true });
+ const tabId = useBrowserStore.getState().activeTabId ?? "";
+ const tab = () => useBrowserStore.getState().tabs.find((candidate) => candidate.id === tabId)!;
+ const page = currentEntry(tab());
+ store.navigate(tabId, { url: "https://cdn.example/setup.zip", from: "https://a.example/page" });
+ const file = currentEntry(tab());
+ assert.equal(file.kind === "web" && file.from, "https://a.example/page");
+ store.leaveDownload(tabId, file);
+ assert.equal(currentEntry(tab()), page);
+ assert.equal(tab().history.length, 1);
+ assert.equal(tab().history.includes(file), false);
+ store.navigate(tabId, { url: "https://a.example/wait" });
+ store.navigate(tabId, { url: "https://cdn.example/f.zip", from: "https://a.example/wait" }, { replace: true });
+ const replaced = currentEntry(tab());
+ store.leaveDownload(tabId, replaced);
+ assert.equal(currentEntry(tab()), replaced);
+ store.navigate(tabId, { url: "https://cdn.example/typed.zip" });
+ const typed = currentEntry(tab());
+ store.leaveDownload(tabId, typed);
+ assert.equal(currentEntry(tab()), typed);
+ store.navigate(tabId, { url: "https://cdn.example/g.zip", from: "https://cdn.example/typed.zip" });
+ const later = currentEntry(tab());
+ store.navigate(tabId, { url: "https://b.example/" });
+ store.leaveDownload(tabId, later);
+ const after = currentEntry(tab());
+ assert.equal(after.kind === "web" && after.url, "https://b.example/");
+ store.closeTab(tabId);
+});
diff --git a/studio/frontend/tests/helpers/browser-store-resolver.mjs b/studio/frontend/tests/helpers/browser-store-resolver.mjs
index 7ef03e3da13..6ea2e5e7bab 100644
--- a/studio/frontend/tests/helpers/browser-store-resolver.mjs
+++ b/studio/frontend/tests/helpers/browser-store-resolver.mjs
@@ -6,8 +6,26 @@ const CHAT_STUB =
"data:text/javascript," +
encodeURIComponent("export const useChatArtifactsStore = { getState: () => ({ closeArtifactSurface() {} }) };");
+const I18N_STUB =
+ "data:text/javascript," +
+ encodeURIComponent("export const getLocale = () => \"en\"; export const translate = (key) => key;");
+
+const TOAST_STUB =
+ "data:text/javascript," +
+ encodeURIComponent(
+ "const toast = (message, options) => void (globalThis.__toasts ??= []).push({ message, options });" +
+ " toast.error = toast.success = toast; export { toast };",
+ );
+
+const AUTH_STUB =
+ "data:text/javascript," +
+ encodeURIComponent("export const authFetch = () => { throw new Error(\"no network in tests\"); };");
+
export function resolve(specifier, context, next) {
+ if (specifier === "@/features/auth") return { url: AUTH_STUB, shortCircuit: true };
+ if (specifier === "@/lib/toast") return { url: TOAST_STUB, shortCircuit: true };
if (specifier === "@/features/chat") return { url: CHAT_STUB, shortCircuit: true };
+ if (specifier === "@/i18n") return { url: I18N_STUB, shortCircuit: true };
if (specifier.startsWith("@/lib/")) {
return next(new URL(`../../src/lib/${specifier.slice(6)}.ts`, import.meta.url).href, context);
}
diff --git a/studio/frontend/tests/helpers/native-view-resolver.mjs b/studio/frontend/tests/helpers/native-view-resolver.mjs
index 8f9ae239f1c..6f61ae35491 100644
--- a/studio/frontend/tests/helpers/native-view-resolver.mjs
+++ b/studio/frontend/tests/helpers/native-view-resolver.mjs
@@ -21,6 +21,10 @@ const STUBS = {
export const clearNativeBrowsingData = async () => {};
`),
"./favicon": stub("export const proxiedFavicon = async () => null;"),
+ "./native-downloads": stub("export const decideNativeDownload = async () => {};"),
+ "./download-approval-queue": stub(
+ "export const approveDownload = async () => false; export const downloadSiteOf = () => '';",
+ ),
"./history-store": stub(
"export const useBrowserHistoryStore = { getState: () => ({ recordVisit() {}, recordDownload() {} }) };",
),
diff --git a/studio/src-tauri/src/browser_downloads.rs b/studio/src-tauri/src/browser_downloads.rs
index 52f6f0b2abb..7acec46c92d 100644
--- a/studio/src-tauri/src/browser_downloads.rs
+++ b/studio/src-tauri/src/browser_downloads.rs
@@ -1,18 +1,29 @@
-//! Paths of files saved from the browser panel, so Download history can reveal them or flag
-//! them deleted. The webview only gets opaque ids.
+//! Browser panel downloads: folder, approval for site downloads, and where each landed. The webview only gets opaque ids.
use serde::{Deserialize, Serialize};
+use std::collections::HashMap;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;
-use tauri::{AppHandle, Manager, Runtime, State};
+use std::time::Duration;
+use tauri::{AppHandle, Manager, Runtime, State, Url};
+use tauri_plugin_dialog::DialogExt;
/// Well past MAX_DOWNLOADS in history-store.ts. The history forgets ids it drops, so only orphans
/// (a tab closed mid-download) build up toward this, not rows the history still shows.
const MAX_ENTRIES: usize = 1000;
const ID_BYTES: usize = 16;
const FILE_NAME: &str = "browser-downloads.json";
+const FOLDER_FILE_NAME: &str = "browser-download-folder.json";
+const STAGING_DIR: &str = "browser-download-staging";
+const ASK_HEADER: &str = "x-unsloth-ask";
+const SOURCE_HEADER: &str = "x-unsloth-source";
+/// Per-tab cap on unanswered page downloads, so an ignored prompt can't fill the disk with staged files.
+pub(crate) const MAX_UNANSWERED_PER_TAB: usize = 3;
+/// An unanswered prompt (window reloaded, say) counts as Cancel after this.
+const ANSWER_TIMEOUT: Duration = Duration::from_secs(10 * 60);
#[derive(Clone, Serialize, Deserialize, PartialEq, Debug)]
struct Entry {
@@ -20,10 +31,30 @@ struct Entry {
path: PathBuf,
}
-/// Loaded from disk on first use, newest last.
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum Decision {
+ Allow { ask: bool },
+ Deny,
+}
+
+struct Pending {
+ tab_id: String,
+ url: Url,
+ name: String,
+ staged: PathBuf,
+ decision: Option<Decision>,
+ finished: Option<bool>,
+}
+
#[derive(Default)]
pub struct BrowserDownloads {
+ /// Loaded from disk on first use, newest last.
entries: Mutex<Option<Vec<Entry>>>,
+ pending: Mutex<HashMap<String, Pending>>,
+ /// None = system Downloads; outer None = not loaded yet.
+ folder: Mutex<Option<Option<PathBuf>>>,
+ staging_cleared: AtomicBool,
+ naming: Mutex<()>,
}
pub fn new_browser_downloads() -> BrowserDownloads {
@@ -37,6 +68,18 @@ pub struct SavedDownload {
name: String,
}
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct DownloadFolder {
+ path: String,
+ custom: bool,
+}
+
+#[derive(Serialize, Deserialize)]
+struct FolderFile {
+ path: PathBuf,
+}
+
fn store_path<R: Runtime>(app: &AppHandle<R>) -> Option<PathBuf> {
app.path()
.app_local_data_dir()
@@ -69,25 +112,25 @@ fn load(path: Option<&Path>) -> Vec<Entry> {
.unwrap_or_default()
}
-/// Written to a temp file and renamed, so a crash never leaves half a list.
-fn save(path: Option<&Path>, entries: &[Entry]) {
- let Some(path) = path else {
- return;
- };
- let Some(parent) = path.parent() else {
- return;
- };
- let Ok(bytes) = serde_json::to_vec(entries) else {
- return;
- };
- let _ = fs::create_dir_all(parent).and_then(|()| {
- let mut temporary = tempfile::NamedTempFile::new_in(parent)?;
- temporary.write_all(&bytes)?;
- temporary
- .persist(path)
- .map(|_| ())
- .map_err(|error| error.error)
- });
+fn save(path: Option<&Path>, value: &impl Serialize) {
+ if let Some(path) = path {
+ let _ = write_json(path, value);
+ }
+}
+
+/// Written to a temp file and renamed, so a crash never leaves half a file.
+fn write_json(path: &Path, value: &impl Serialize) -> std::io::Result<()> {
+ let parent = path
+ .parent()
+ .ok_or_else(|| std::io::Error::other("no parent folder"))?;
+ let bytes = serde_json::to_vec(value)?;
+ fs::create_dir_all(parent)?;
+ let mut temporary = tempfile::NamedTempFile::new_in(parent)?;
+ temporary.write_all(&bytes)?;
+ temporary
+ .persist(path)
+ .map(|_| ())
+ .map_err(|error| error.error)
}
fn with_entries<R: Runtime, T>(
@@ -100,7 +143,7 @@ fn with_entries<R: Runtime, T>(
let entries = guard.get_or_insert_with(|| load(path.as_deref()));
let (result, changed) = change(entries);
if changed {
- save(path.as_deref(), entries);
+ save(path.as_deref(), &*entries);
}
result
}
@@ -129,7 +172,7 @@ fn path_of(entries: &[Entry], id: &str) -> Option<PathBuf> {
.map(|entry| entry.path.clone())
}
-/// Save a panel file where the user picks, like `save_native_file`, and remember it.
+/// Save a panel file in the download folder, or via a dialog when `x-unsloth-ask` is set, and remember it.
#[tauri::command]
pub async fn browser_download_save(
webview: tauri::Webview,
@@ -137,10 +180,33 @@ pub async fn browser_download_save(
request: tauri::ipc::Request<'_>,
) -> Result<Option<SavedDownload>, String> {
crate::native_intents::ensure_main_window(&webview)?;
- let Some(path) = crate::native_file_dialogs::save_request_with_dialog(&app, &request).await?
- else {
+ let ask = request
+ .headers()
+ .get(ASK_HEADER)
+ .is_some_and(|value| value.as_bytes() == b"1");
+ let source = request
+ .headers()
+ .get(SOURCE_HEADER)
+ .and_then(|value| value.to_str().ok())
+ .and_then(|value| Url::parse(value).ok())
+ .filter(|url| matches!(url.scheme(), "http" | "https"));
+ let folder = download_folder(&app)?;
+ let saved = if ask {
+ crate::native_file_dialogs::save_request_with_dialog(&app, &request, Some(&folder)).await?
+ } else {
+ let state = app.state::<BrowserDownloads>();
+ let _naming = state.naming.lock().unwrap();
+ Some(crate::native_file_dialogs::save_request_in(
+ &request, &folder,
+ )?)
+ };
+ let Some(path) = saved else {
return Ok(None);
};
+ // Quarantined like a page download, so Gatekeeper or SmartScreen checks it.
+ if let Some(source) = &source {
+ crate::browser_webview::mark_downloaded(&path, source);
+ }
let name = path
.file_name()
.map(|name| name.to_string_lossy().into_owned())
@@ -204,6 +270,345 @@ pub fn browser_download_forget(
Ok(())
}
+fn folder_file<R: Runtime>(app: &AppHandle<R>) -> Option<PathBuf> {
+ app.path()
+ .app_local_data_dir()
+ .ok()
+ .map(|dir| dir.join(FOLDER_FILE_NAME))
+}
+
+fn custom_folder<R: Runtime>(app: &AppHandle<R>) -> Option<PathBuf> {
+ let state = app.state::<BrowserDownloads>();
+ let mut guard = state.folder.lock().unwrap();
+ let folder = guard.get_or_insert_with(|| {
+ folder_file(app)
+ .and_then(|path| fs::read(path).ok())
+ .and_then(|bytes| serde_json::from_slice::<FolderFile>(&bytes).ok())
+ .map(|file| file.path)
+ });
+ folder.clone().filter(|path| path.is_dir())
+}
+
+pub(crate) fn download_folder<R: Runtime>(app: &AppHandle<R>) -> Result<PathBuf, String> {
+ if let Some(folder) = custom_folder(app) {
+ return Ok(folder);
+ }
+ let folder = app
+ .path()
+ .download_dir()
+ .ok()
+ .or_else(dirs::home_dir)
+ .ok_or_else(|| "Could not find a Downloads folder.".to_string())?;
+ // XDG can name a Downloads folder that was never created.
+ fs::create_dir_all(&folder)
+ .map_err(|error| format!("Failed to prepare {}: {error}", folder.display()))?;
+ Ok(folder)
+}
+
+fn folder_info<R: Runtime>(app: &AppHandle<R>) -> Result<DownloadFolder, String> {
+ Ok(DownloadFolder {
+ path: crate::native_file_dialogs::display_path(&download_folder(app)?),
+ custom: custom_folder(app).is_some(),
+ })
+}
+
+/// Cached only once written, so Settings never shows a choice a restart would lose.
+fn set_folder<R: Runtime>(app: &AppHandle<R>, folder: Option<PathBuf>) -> Result<(), String> {
+ let file = folder_file(app).ok_or_else(|| "Could not find the app data folder.".to_string())?;
+ let written = match &folder {
+ Some(path) => write_json(&file, &FolderFile { path: path.clone() }),
+ None => match fs::remove_file(&file) {
+ Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error),
+ _ => Ok(()),
+ },
+ };
+ written.map_err(|error| format!("Failed to save the download location: {error}"))?;
+ *app.state::<BrowserDownloads>().folder.lock().unwrap() = Some(folder);
+ Ok(())
+}
+
+#[tauri::command]
+pub fn browser_download_folder(
+ webview: tauri::Webview,
+ app: AppHandle,
+) -> Result<DownloadFolder, String> {
+ crate::native_intents::ensure_main_window(&webview)?;
+ folder_info(&app)
+}
+
+/// The webview never names a path: the folder comes from the system dialog.
+#[tauri::command]
+pub async fn browser_download_folder_pick(
+ webview: tauri::Webview,
+ app: AppHandle,
+) -> Result<Option<DownloadFolder>, String> {
+ crate::native_intents::ensure_main_window(&webview)?;
+ let (tx, rx) = tokio::sync::oneshot::channel();
+ app.dialog()
+ .file()
+ .set_title("Choose download location")
+ .set_directory(download_folder(&app)?)
+ .pick_folder(move |path| {
+ let _ = tx.send(path);
+ });
+ let Some(picked) = rx.await.map_err(|_| "Dialog closed".to_string())? else {
+ return Ok(None);
+ };
+ let path = picked
+ .into_path()
+ .map_err(|_| "Only local folders are supported.".to_string())?;
+ set_folder(&app, Some(path))?;
+ folder_info(&app).map(Some)
+}
+
+#[tauri::command]
+pub fn browser_download_folder_reset(
+ webview: tauri::Webview,
+ app: AppHandle,
+) -> Result<DownloadFolder, String> {
+ crate::native_intents::ensure_main_window(&webview)?;
+ set_folder(&app, None)?;
+ folder_info(&app)
+}
+
+/// A fresh staging folder for one page download, with its id; the staging root is emptied on first use after launch.
+pub(crate) fn staging_dir<R: Runtime>(app: &AppHandle<R>) -> Option<(String, PathBuf)> {
+ let root = app.path().app_cache_dir().ok()?.join(STAGING_DIR);
+ let state = app.state::<BrowserDownloads>();
+ if !state.staging_cleared.swap(true, Ordering::SeqCst) {
+ let _ = fs::remove_dir_all(&root);
+ }
+ let id = new_id();
+ let dir = root.join(&id);
+ fs::create_dir_all(&dir).ok()?;
+ Some((id, dir))
+}
+
+pub(crate) fn unanswered<R: Runtime>(app: &AppHandle<R>, tab_id: &str) -> usize {
+ app.state::<BrowserDownloads>()
+ .pending
+ .lock()
+ .unwrap()
+ .values()
+ .filter(|entry| entry.tab_id == tab_id && entry.decision.is_none())
+ .count()
+}
+
+pub(crate) fn add_pending<R: Runtime>(
+ app: &AppHandle<R>,
+ id: String,
+ tab_id: String,
+ url: Url,
+ staged: PathBuf,
+) {
+ let name = staged
+ .file_name()
+ .map(|name| name.to_string_lossy().into_owned())
+ .unwrap_or_default();
+ let pending = Pending {
+ tab_id,
+ url,
+ name,
+ staged,
+ decision: None,
+ finished: None,
+ };
+ app.state::<BrowserDownloads>()
+ .pending
+ .lock()
+ .unwrap()
+ .insert(id.clone(), pending);
+ let app = app.clone();
+ tauri::async_runtime::spawn(async move {
+ tokio::time::sleep(ANSWER_TIMEOUT).await;
+ let expired = {
+ let state = app.state::<BrowserDownloads>();
+ let mut pending = state.pending.lock().unwrap();
+ match pending.get_mut(&id) {
+ Some(entry) if entry.decision.is_none() => {
+ entry.decision = Some(Decision::Deny);
+ true
+ }
+ _ => false,
+ }
+ };
+ if expired {
+ settle(&app, &id);
+ }
+ });
+}
+
+pub(crate) fn finished<R: Runtime>(app: &AppHandle<R>, staged: &Path, success: bool) {
+ let id = {
+ let state = app.state::<BrowserDownloads>();
+ let mut pending = state.pending.lock().unwrap();
+ let Some((id, entry)) = pending.iter_mut().find(|(_, entry)| entry.staged == staged) else {
+ return;
+ };
+ entry.finished = Some(success);
+ id.clone()
+ };
+ settle(app, &id);
+}
+
+#[tauri::command]
+pub fn browser_download_decide(
+ webview: tauri::Webview,
+ app: AppHandle,
+ id: String,
+ allow: bool,
+ ask: bool,
+) -> Result<(), String> {
+ crate::native_intents::ensure_main_window(&webview)?;
+ let decision = if allow {
+ Decision::Allow { ask }
+ } else {
+ Decision::Deny
+ };
+ decide(
+ &mut app.state::<BrowserDownloads>().pending.lock().unwrap(),
+ &id,
+ decision,
+ )?;
+ settle(&app, &id);
+ Ok(())
+}
+
+/// A second answer is refused: after ANSWER_TIMEOUT denied it, a late Download click must not allow it.
+fn decide(
+ pending: &mut HashMap<String, Pending>,
+ id: &str,
+ decision: Decision,
+) -> Result<(), String> {
+ let entry = pending
+ .get_mut(id)
+ .ok_or_else(|| "Unknown download.".to_string())?;
+ if entry.decision.is_some() {
+ return Err("This download was already answered.".to_string());
+ }
+ entry.decision = Some(decision);
+ Ok(())
+}
+
+/// Once answered and finished, move the download out of staging or drop it.
+fn settle<R: Runtime>(app: &AppHandle<R>, id: &str) {
+ let entry = {
+ let state = app.state::<BrowserDownloads>();
+ let mut pending = state.pending.lock().unwrap();
+ match pending.get(id) {
+ Some(entry) if entry.decision.is_some() && entry.finished.is_some() => {
+ pending.remove(id)
+ }
+ _ => None,
+ }
+ };
+ let Some(entry) = entry else {
+ return;
+ };
+ let app = app.clone();
+ tauri::async_runtime::spawn(async move {
+ let staging = entry.staged.parent().map(Path::to_path_buf);
+ let result = match (entry.decision, entry.finished) {
+ (Some(Decision::Allow { ask }), Some(true)) => deliver(&app, &entry, ask).await,
+ (Some(Decision::Allow { .. }), _) => Err("failed".to_string()),
+ _ => Ok(None),
+ };
+ if let Some(staging) = staging {
+ let _ = fs::remove_dir_all(staging);
+ }
+ match result {
+ Ok(Some((path, download_id))) => crate::browser_webview::emit_download_done(
+ &app,
+ &entry.tab_id,
+ &entry.url,
+ &path,
+ Some(download_id),
+ ),
+ Ok(None) => {}
+ Err(_) => crate::browser_webview::emit_download_failed(
+ &app,
+ &entry.tab_id,
+ &entry.url,
+ &entry.name,
+ ),
+ }
+ });
+}
+
+/// None if the save dialog was cancelled.
+async fn deliver<R: Runtime>(
+ app: &AppHandle<R>,
+ entry: &Pending,
+ ask: bool,
+) -> Result<Option<(PathBuf, String)>, String> {
+ let folder = download_folder(app)?;
+ let staged = entry.staged.clone();
+ let target = if ask {
+ let (tx, rx) = tokio::sync::oneshot::channel();
+ app.dialog()
+ .file()
+ .set_title("Save download")
+ .set_directory(&folder)
+ .set_file_name(&entry.name)
+ .save_file(move |path| {
+ let _ = tx.send(path);
+ });
+ let Some(picked) = rx.await.map_err(|_| "Dialog closed".to_string())? else {
+ return Ok(None);
+ };
+ let target = picked
+ .into_path()
+ .map_err(|_| "Only local paths are supported.".to_string())?;
+ let to = target.clone();
+ blocking(move || move_file(&staged, &to)).await?;
+ target
+ } else {
+ let app = app.clone();
+ let name = entry.name.clone();
+ blocking(move || {
+ let state = app.state::<BrowserDownloads>();
+ let _naming = state.naming.lock().unwrap();
+ let target = crate::native_file_dialogs::unique_destination(&folder, &name)?;
+ move_file(&staged, &target)?;
+ Ok(target)
+ })
+ .await?
+ };
+ crate::browser_webview::mark_downloaded(&target, &entry.url);
+ let id = record(app, target.clone());
+ Ok(Some((target, id)))
+}
+
+/// A cross-volume copy can take minutes; keep it off the workers IPC and timers share.
+async fn blocking<T: Send + 'static>(
+ work: impl FnOnce() -> Result<T, String> + Send + 'static,
+) -> Result<T, String> {
+ tauri::async_runtime::spawn_blocking(work)
+ .await
+ .map_err(|error| format!("Failed to save the download: {error}"))?
+}
+
+fn move_file(from: &Path, to: &Path) -> Result<(), String> {
+ if fs::rename(from, to).is_ok() {
+ return Ok(());
+ }
+ copy_into_place(from, to)
+}
+
+/// Copied beside `to` and renamed over it once complete, so a failed copy leaves no half file and the target intact.
+fn copy_into_place(from: &Path, to: &Path) -> Result<(), String> {
+ let failed = |error: std::io::Error| format!("Failed to save {}: {error}", to.display());
+ let mut temporary = crate::native_file_dialogs::staged_temp_file(to)?;
+ let mut source = fs::File::open(from).map_err(failed)?;
+ std::io::copy(&mut source, temporary.as_file_mut())
+ .and_then(|_| temporary.as_file().sync_all())
+ .map_err(failed)?;
+ temporary
+ .persist(to)
+ .map(|_| ())
+ .map_err(|error| failed(error.error))
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -232,6 +637,69 @@ mod tests {
);
}
+ #[test]
+ fn a_copy_replaces_its_target_only_once_complete() {
+ let dir = tempfile::tempdir().unwrap();
+ let to = dir.path().join("file.zip");
+ fs::write(&to, b"kept").unwrap();
+ assert!(copy_into_place(&dir.path().join("missing.zip"), &to).is_err());
+ assert_eq!(fs::read(&to).unwrap(), b"kept");
+ assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
+ let from = dir.path().join("staged.zip");
+ fs::write(&from, b"new").unwrap();
+ copy_into_place(&from, &to).unwrap();
+ assert_eq!(fs::read(&to).unwrap(), b"new");
+ assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 2);
+ }
+
+ #[test]
+ fn a_failed_location_write_is_reported() {
+ let dir = tempfile::tempdir().unwrap();
+ let blocker = dir.path().join("blocker");
+ fs::write(&blocker, b"x").unwrap();
+ let folder = FolderFile {
+ path: dir.path().to_path_buf(),
+ };
+ assert!(write_json(&blocker.join("folder.json"), &folder).is_err());
+ let file = dir.path().join("folder.json");
+ write_json(&file, &folder).unwrap();
+ let read: FolderFile = serde_json::from_slice(&fs::read(&file).unwrap()).unwrap();
+ assert_eq!(read.path, dir.path());
+ }
+
+ #[test]
+ fn a_download_is_answered_once() {
+ let mut pending = HashMap::new();
+ pending.insert(
+ "a".to_string(),
+ Pending {
+ tab_id: "t".into(),
+ url: Url::parse("https://example.com/f.zip").unwrap(),
+ name: "f.zip".into(),
+ staged: PathBuf::from("f.zip"),
+ decision: None,
+ finished: None,
+ },
+ );
+ // A late Download click after the timeout's Deny changes nothing.
+ decide(&mut pending, "a", Decision::Deny).unwrap();
+ assert!(decide(&mut pending, "a", Decision::Allow { ask: false }).is_err());
+ assert_eq!(pending["a"].decision, Some(Decision::Deny));
+ assert!(decide(&mut pending, "b", Decision::Deny).is_err());
+ }
+
+ #[test]
+ fn a_staged_download_moves_to_its_target() {
+ let dir = tempfile::tempdir().unwrap();
+ let from = dir.path().join("staged.zip");
+ let to = dir.path().join("out").join("file.zip");
+ fs::write(&from, b"zip").unwrap();
+ fs::create_dir_all(to.parent().unwrap()).unwrap();
+ move_file(&from, &to).unwrap();
+ assert_eq!(fs::read(&to).unwrap(), b"zip");
+ assert!(!from.exists());
+ }
+
#[test]
fn saved_lists_load_back_and_bad_ids_are_dropped() {
let dir = tempfile::tempdir().unwrap();
diff --git a/studio/src-tauri/src/browser_webview.rs b/studio/src-tauri/src/browser_webview.rs
index 795be9434be..09264b8fd48 100644
--- a/studio/src-tauri/src/browser_webview.rs
+++ b/studio/src-tauri/src/browser_webview.rs
@@ -154,6 +154,8 @@ struct ViewsState {
polling: bool,
/** Tabs the reader muted; macOS mutes each page they load, Windows the view once. */
muted: HashSet<String>,
+ /// Tabs whose view committed a page of its own since it opened or was last sent somewhere; until then a download's site is the address asked for (or the opener).
+ committed: HashSet<String>,
}
pub fn new_browser_views() -> BrowserViews {
@@ -236,6 +238,14 @@ enum BrowserEvent {
/// A finished download's handle for Download history (browser_downloads.rs).
download_id: Option<String>,
},
+ DownloadPrompt {
+ tab_id: String,
+ url: String,
+ /// Page showing when the download started (the site a remembered answer is for); "" before the view showed one.
+ site: String,
+ name: String,
+ id: String,
+ },
}
#[derive(Deserialize)]
@@ -519,6 +529,52 @@ fn emit<R: Runtime>(app: &AppHandle<R>, event: BrowserEvent) {
let _ = app.emit_to(MAIN_WEBVIEW, EVENT, event);
}
+pub(crate) fn emit_download_done<R: Runtime>(
+ app: &AppHandle<R>,
+ tab_id: &str,
+ url: &Url,
+ path: &Path,
+ download_id: Option<String>,
+) {
+ emit(
+ app,
+ BrowserEvent::Download {
+ tab_id: tab_id.to_string(),
+ url: url.to_string(),
+ name: path
+ .file_name()
+ .map(|name| name.to_string_lossy().into_owned())
+ .unwrap_or_default(),
+ path: None,
+ size: std::fs::metadata(path).ok().map(|m| m.len()),
+ done: true,
+ success: true,
+ download_id,
+ },
+ );
+}
+
+pub(crate) fn emit_download_failed<R: Runtime>(
+ app: &AppHandle<R>,
+ tab_id: &str,
+ url: &Url,
+ name: &str,
+) {
+ emit(
+ app,
+ BrowserEvent::Download {
+ tab_id: tab_id.to_string(),
+ url: url.to_string(),
+ name: name.to_string(),
+ path: None,
+ size: None,
+ done: true,
+ success: false,
+ download_id: None,
+ },
+ );
+}
+
pub(crate) fn view<R: Runtime>(app: &AppHandle<R>, tab_id: &str) -> Result<Webview<R>, String> {
let label = label_for(tab_id)?;
app.get_webview(&label).ok_or_else(|| "no such tab".into())
@@ -624,18 +680,7 @@ fn download_destination(dir: &Path, suggested: &Path, reserved: &HashSet<&Path>)
let name = suggested
.file_name()
.and_then(|name| name.to_str())
- .map(|name| {
- name.chars()
- .map(|c| {
- if c.is_control() || "/\\:".contains(c) {
- '_'
- } else {
- c
- }
- })
- .collect::<String>()
- })
- .filter(|name| !name.trim_matches('.').is_empty())
+ .map(crate::native_file_dialogs::safe_download_name)
.unwrap_or_else(|| "download".into());
// Windows and macOS file systems ignore case, so `Report.pdf` and `report.pdf` are one file.
let same = |a: &Path, b: &Path| {
@@ -666,7 +711,7 @@ fn download_destination(dir: &Path, suggested: &Path, reserved: &HashSet<&Path>)
}
/// Mark a download as from the internet, so Gatekeeper or SmartScreen checks it.
-fn mark_downloaded(path: &Path, url: &Url) {
+pub(crate) fn mark_downloaded(path: &Path, url: &Url) {
#[cfg(target_os = "macos")]
{
use std::ffi::CString;
@@ -864,7 +909,6 @@ fn create_view<R: Runtime>(
let window_app = app.clone();
let window_tab = tab.clone();
let download_tab = tab.clone();
- let downloads_dir = app.path().download_dir().ok();
#[cfg(target_os = "macos")]
let (initial, deferred) = (Url::parse("about:blank").unwrap(), Some(url));
@@ -895,12 +939,15 @@ fn create_view<R: Runtime>(
}
let url = payload.url().to_string();
let loading = matches!(payload.event(), PageLoadEvent::Started);
- app.state::<BrowserViews>()
- .inner
- .lock()
- .unwrap()
- .urls
- .insert(load_tab.clone(), url.clone());
+ {
+ let state = app.state::<BrowserViews>();
+ let mut inner = state.inner.lock().unwrap();
+ inner.urls.insert(load_tab.clone(), url.clone());
+ // Started is a commit (WebKit) or content loading (WebView2): never a download.
+ if loading {
+ inner.committed.insert(load_tab.clone());
+ }
+ }
emit(
app,
BrowserEvent::Load {
@@ -963,52 +1010,44 @@ fn create_view<R: Runtime>(
let app = webview.app_handle();
match event {
DownloadEvent::Requested { url, destination } => {
- let Some(dir) = downloads_dir.as_deref() else {
+ if crate::browser_downloads::unanswered(app, &download_tab)
+ >= crate::browser_downloads::MAX_UNANSWERED_PER_TAB
+ {
+ let name = destination
+ .file_name()
+ .map(|name| name.to_string_lossy().into_owned())
+ .unwrap_or_default();
+ emit_download_failed(app, &download_tab, &url, &name);
+ return false;
+ }
+ let Some((id, staging)) = crate::browser_downloads::staging_dir(app) else {
return false;
};
- // Picked and recorded under one lock, so two downloads can't take one name.
let path = {
let state = app.state::<BrowserViews>();
let mut inner = state.inner.lock().unwrap();
// macOS reports no path when a download finishes, so two of one URL at
- // once couldn't be told apart (and quarantined right): one at a time.
- if cfg!(target_os = "macos") && inner.downloads.contains_key(url.as_str()) {
- return false;
- }
+ // once couldn't be told apart: one at a time.
+ let busy =
+ cfg!(target_os = "macos") && inner.downloads.contains_key(url.as_str());
let in_flight = inner.downloads.values().map(Vec::len).sum();
let starts = inner
.download_starts
.entry(download_tab.clone())
.or_default();
- if !download_allowed(in_flight, starts, Instant::now()) {
+ if busy || !download_allowed(in_flight, starts, Instant::now()) {
drop(inner);
- emit(
- app,
- BrowserEvent::Download {
- tab_id: download_tab.clone(),
- url: url.to_string(),
- name: destination
- .file_name()
- .map(|name| name.to_string_lossy().into_owned())
- .unwrap_or_default(),
- path: None,
- size: None,
- done: true,
- success: false,
- download_id: None,
- },
- );
+ let _ = std::fs::remove_dir_all(&staging);
+ if !busy {
+ let name = destination
+ .file_name()
+ .map(|name| name.to_string_lossy().into_owned())
+ .unwrap_or_default();
+ emit_download_failed(app, &download_tab, &url, &name);
+ }
return false;
}
- let path = {
- let reserved: HashSet<&Path> = inner
- .downloads
- .values()
- .flatten()
- .map(PathBuf::as_path)
- .collect();
- download_destination(dir, destination, &reserved)
- };
+ let path = download_destination(&staging, destination, &HashSet::new());
inner
.downloads
.entry(url.to_string())
@@ -1020,18 +1059,34 @@ fn create_view<R: Runtime>(
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default();
- *destination = path;
+ *destination = path.clone();
+ crate::browser_downloads::add_pending(
+ app,
+ id.clone(),
+ download_tab.clone(),
+ url.clone(),
+ path,
+ );
+ // "" before the view showed its own page: the frontend knows the tab's address or opener.
+ let committed = app
+ .state::<BrowserViews>()
+ .inner
+ .lock()
+ .unwrap()
+ .committed
+ .contains(&download_tab);
+ let site = match webview.url() {
+ Ok(page) if committed => page.to_string(),
+ _ => String::new(),
+ };
emit(
app,
- BrowserEvent::Download {
+ BrowserEvent::DownloadPrompt {
tab_id: download_tab.clone(),
url: url.to_string(),
+ site,
name,
- path: None,
- size: None,
- done: false,
- success: false,
- download_id: None,
+ id,
},
);
true
@@ -1051,34 +1106,9 @@ fn create_view<R: Runtime>(
}
recorded
};
- let path = path.or(recorded);
- let download_id = match (success, path.as_deref()) {
- (true, Some(saved)) => {
- mark_downloaded(saved, &url);
- Some(crate::browser_downloads::record(app, saved.to_path_buf()))
- }
- _ => None,
- };
- emit(
- app,
- BrowserEvent::Download {
- tab_id: download_tab.clone(),
- url: url.to_string(),
- name: path
- .as_deref()
- .and_then(|p| p.file_name())
- .map(|name| name.to_string_lossy().into_owned())
- .unwrap_or_default(),
- size: path
- .as_deref()
- .and_then(|p| std::fs::metadata(p).ok())
- .map(|m| m.len()),
- path: path.map(|p| p.to_string_lossy().into_owned()),
- done: true,
- success,
- download_id,
- },
- );
+ if let Some(staged) = path.or(recorded) {
+ crate::browser_downloads::finished(app, &staged, success);
+ }
true
}
_ => false,
@@ -1296,9 +1326,15 @@ pub fn browser_view_navigate<R: Runtime>(
) -> Result<(), String> {
require_main(&webview)?;
let url = parse_page_url(&url)?;
- view(webview.app_handle(), &tab_id)?
- .navigate(url)
- .map_err(|error| error.to_string())
+ let page = view(webview.app_handle(), &tab_id)?;
+ webview
+ .state::<BrowserViews>()
+ .inner
+ .lock()
+ .unwrap()
+ .committed
+ .remove(&tab_id);
+ page.navigate(url).map_err(|error| error.to_string())
}
#[tauri::command]
@@ -1542,6 +1578,7 @@ pub fn browser_view_close<R: Runtime>(
{
let mut inner = state.inner.lock().unwrap();
inner.urls.remove(&tab_id);
+ inner.committed.remove(&tab_id);
inner.download_starts.remove(&tab_id);
// `muted` stays: a pruned view reopens muted; unmuting is what forgets it.
if inner.shown.as_deref() == Some(tab_id.as_str()) {
@@ -1568,6 +1605,7 @@ pub async fn browser_view_clear_data<R: Runtime>(
{
let mut inner = state.inner.lock().unwrap();
inner.urls.clear();
+ inner.committed.clear();
set_shown(&state, &mut inner, None);
}
for page in browser_views(&app) {
diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rs
index 25c3fdc730b..83859118abd 100644
--- a/studio/src-tauri/src/main.rs
+++ b/studio/src-tauri/src/main.rs
@@ -2260,6 +2260,10 @@ fn main() {
browser_downloads::browser_download_reveal,
browser_downloads::browser_download_exists,
browser_downloads::browser_download_forget,
+ browser_downloads::browser_download_decide,
+ browser_downloads::browser_download_folder,
+ browser_downloads::browser_download_folder_pick,
+ browser_downloads::browser_download_folder_reset,
browser_capture::browser_view_print,
set_training_active,
set_renderer_activity,
diff --git a/studio/src-tauri/src/native_file_dialogs.rs b/studio/src-tauri/src/native_file_dialogs.rs
index fbb4da1d6bd..ff2f5ae7428 100644
--- a/studio/src-tauri/src/native_file_dialogs.rs
+++ b/studio/src-tauri/src/native_file_dialogs.rs
@@ -212,7 +212,7 @@ fn local_dialog_path(path: tauri_plugin_dialog::FilePath) -> Result<PathBuf, Str
}
/// Stage the write beside the destination so a partial file never replaces a real one.
-fn staged_temp_file(path: &Path) -> Result<tempfile::NamedTempFile, String> {
+pub(crate) fn staged_temp_file(path: &Path) -> Result<tempfile::NamedTempFile, String> {
let parent = path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
@@ -442,16 +442,14 @@ pub async fn save_native_file(
request: tauri::ipc::Request<'_>,
) -> Result<Option<String>, String> {
crate::native_intents::ensure_main_window(&webview)?;
- Ok(save_request_with_dialog(&app, &request)
+ Ok(save_request_with_dialog(&app, &request, None)
.await?
.map(|path| saved_file_name(&path)))
}
-/// Save the request body where the user picks; None if cancelled. Keep the path off the webview.
-pub(crate) async fn save_request_with_dialog(
- app: &AppHandle,
- request: &tauri::ipc::Request<'_>,
-) -> Result<Option<PathBuf>, String> {
+fn request_file<'a>(
+ request: &'a tauri::ipc::Request<'_>,
+) -> Result<(String, Cow<'a, [u8]>), String> {
let encoded_name = request
.headers()
.get(NATIVE_FILE_NAME_HEADER)
@@ -461,17 +459,31 @@ pub(crate) async fn save_request_with_dialog(
let file_name = decode_default_file_name(encoded_name)?;
let content = invoke_body_bytes(request.body())
.ok_or_else(|| "Native export content must be binary.".to_string())?;
+ Ok((file_name, content))
+}
+
+/// Save the request body where the user picks, starting in `directory`; None if cancelled.
+pub(crate) async fn save_request_with_dialog(
+ app: &AppHandle,
+ request: &tauri::ipc::Request<'_>,
+ directory: Option<&Path>,
+) -> Result<Option<PathBuf>, String> {
+ let (file_name, content) = request_file(request)?;
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()
+ let mut dialog = app
+ .dialog()
.file()
.set_title("Save Unsloth export")
.set_file_name(file_name)
- .add_filter(filter_name, &extension_refs)
- .save_file(move |path| {
- let _ = tx.send(path);
- });
+ .add_filter(filter_name, &extension_refs);
+ if let Some(directory) = directory {
+ dialog = dialog.set_directory(directory);
+ }
+ dialog.save_file(move |path| {
+ let _ = tx.send(path);
+ });
let selected_path = rx
.await
.map_err(|_| "Save dialog closed unexpectedly.".to_string())?
@@ -563,6 +575,61 @@ pub fn cancel_native_file_save(
Ok(())
}
+/// Room under the usual 255-byte name limit for the " (999)" a taken name gets.
+const MAX_DOWNLOAD_NAME_BYTES: usize = 240;
+const WINDOWS_DEVICE_NAMES: [&str; 22] = [
+ "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8",
+ "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
+];
+
+/// A website's file name made safe everywhere: no separators, control or reserved characters, trailing dots/spaces or device names; length capped.
+pub(crate) fn safe_download_name(name: &str) -> String {
+ let mut name: String = name
+ .chars()
+ .map(|c| {
+ if c.is_control() || "/\\:*?\"<>|".contains(c) {
+ '_'
+ } else {
+ c
+ }
+ })
+ .collect();
+ let kept = name.trim_end_matches(['.', ' ']).len();
+ name.truncate(kept);
+ if name.trim_matches(['.', ' ']).is_empty() {
+ return "download".into();
+ }
+ let device = name.split('.').next().unwrap_or("").trim_end();
+ if WINDOWS_DEVICE_NAMES
+ .iter()
+ .any(|reserved| reserved.eq_ignore_ascii_case(device))
+ {
+ name.insert(0, '_');
+ }
+ if name.len() > MAX_DOWNLOAD_NAME_BYTES {
+ let extension = name
+ .rfind('.')
+ .filter(|&at| at > 0 && name.len() - at <= 32)
+ .map_or("", |at| &name[at..]);
+ let mut end = MAX_DOWNLOAD_NAME_BYTES - extension.len();
+ while !name.is_char_boundary(end) {
+ end -= 1;
+ }
+ name = format!("{}{extension}", &name[..end]);
+ }
+ name
+}
+
+pub(crate) fn save_request_in(
+ request: &tauri::ipc::Request<'_>,
+ directory: &Path,
+) -> Result<PathBuf, String> {
+ let (file_name, content) = request_file(request)?;
+ let path = unique_destination(directory, &safe_download_name(&file_name))?;
+ save_selected_file(Some(path), content.as_ref())?
+ .ok_or_else(|| "Failed to save the file.".to_string())
+}
+
/// Save a backend URL by streaming it to the chosen path.
///
/// `save_native_file` carries the bytes through IPC, so the caller buffers the whole body
@@ -711,7 +778,7 @@ fn log_archive_directory() -> Result<PathBuf, String> {
/// an issue. Best effort by nature -- another process can take the name between the check
/// and the rename -- but it removes the case that actually happens, which is the same
/// user pressing the button again.
-fn unique_destination(directory: &Path, file_name: &str) -> Result<PathBuf, String> {
+pub(crate) fn unique_destination(directory: &Path, file_name: &str) -> Result<PathBuf, String> {
let candidate = directory.join(file_name);
if !candidate.exists() {
return Ok(candidate);
@@ -873,7 +940,7 @@ fn strip_verbatim_prefix(text: String) -> String {
}
/// The absolute, symlink-resolved path to show the user.
-fn display_path(path: &Path) -> String {
+pub(crate) fn display_path(path: &Path) -> String {
let resolved = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
strip_verbatim_prefix(resolved.display().to_string())
}
@@ -1029,6 +1096,26 @@ pub async fn pick_native_training_config(
#[cfg(test)]
mod tests {
use super::*;
+
+ #[test]
+ fn download_names_are_safe_on_every_platform() {
+ assert_eq!(safe_download_name("report:2026.pdf"), "report_2026.pdf");
+ assert_eq!(
+ safe_download_name("a<b>c|d?e*f\"g.txt"),
+ "a_b_c_d_e_f_g.txt"
+ );
+ assert_eq!(safe_download_name("evil\u{7}name.sh"), "evil_name.sh");
+ assert_eq!(safe_download_name("CON"), "_CON");
+ assert_eq!(safe_download_name("nul.tar.gz"), "_nul.tar.gz");
+ assert_eq!(safe_download_name("console.log"), "console.log");
+ assert_eq!(safe_download_name("notes. . "), "notes");
+ assert_eq!(safe_download_name(".."), "download");
+ assert_eq!(safe_download_name(" "), "download");
+ let long = format!("{}.pdf", "\u{3042}".repeat(255));
+ let safe = safe_download_name(&long);
+ assert!(safe.len() <= MAX_DOWNLOAD_NAME_BYTES, "{}", safe.len());
+ assert!(safe.ends_with("\u{3042}.pdf"));
+ }
use std::time::{SystemTime, UNIX_EPOCH};
fn temp_path(name: &str) -> PathBuf {