Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: Downloads button in the browser panel (#13009)
Michael Han0ff80678929c
diff --git a/studio/frontend/src/features/browser/browser-panel.tsx b/studio/frontend/src/features/browser/browser-panel.tsxindex 2c475f62706..58a1265cc65 100644--- a/studio/frontend/src/features/browser/browser-panel.tsx+++ b/studio/frontend/src/features/browser/browser-panel.tsx@@ -104,6 +104,7 @@ import { OtherSurfaceError, canPrintFrames, printPage, screenshotPage } from "./import { canScreenshot } from "./screenshot-support";import { stageEditsPrompt } from "./stage-edits";import { type BrowserDownload, saveBrowserDownload, saveNeedsClick } from "./downloads";+import { DownloadsButton } from "./downloads-button";import { BROWSER_FIND_TARGET, registerBrowserFind } from "./find";import { ClearBrowsingDataDialog } from "./clear-data-dialog";import { SiteFavicon } from "./site-favicon";@@ -1051,20 +1052,12 @@ function webAddress(tab: BrowserTab | undefined): string | null {return entry?.kind === "web" ? (tab?.displayUrl ?? entry.url) : null;}-function WebActions({ tab }: { tab: BrowserTab | undefined }) {- const t = useT();- const download = tabDownload(tab);+function WebActions({ tab, visible }: { tab: BrowserTab | undefined; visible: boolean }) {return (<><AnnotatePageButton tab={tab} />- <IconButton- label={t("browser.download")}- disabled={!download}- onClick={() => download && void saveBrowserDownload(download)}- className={NAV_BUTTON}- >- <HugeiconsIcon icon={Download01Icon} strokeWidth={1.75} className="size-4.5" />- </IconButton>+ {/* Recent downloads and the one in flight; saving the page itself is in the menu. */}+ <DownloadsButton className={NAV_BUTTON} visible={visible} /></>);}@@ -1184,6 +1177,7 @@ function PanelMenu({ tab, children }: { tab: BrowserTab | undefined; children?:const device = useBrowserStore((state) => state.device);const [clearOpen, setClearOpen] = useState(false);const webUrl = webAddress(tab);+ const pageSave = fileTab ? undefined : tabDownload(tab);const bookmarked = useBookmarkFor(webUrl) !== undefined;const toolbarMode = useBrowserPrefsStore((state) => state.bookmarksToolbar);// The star's editor opens as the menu closes; focus going back to the menu button would shut it.@@ -1272,6 +1266,12 @@ function PanelMenu({ tab, children }: { tab: BrowserTab | undefined; children?:<DropdownMenuItem disabled={!webUrl} onSelect={() => webUrl && openExternalLink(webUrl)}>{t("browser.openExternal")}</DropdownMenuItem>+ <DropdownMenuItem+ disabled={!pageSave}+ onSelect={() => pageSave && void saveBrowserDownload(pageSave)}+ >+ {t("browser.downloads.savePage")}+ </DropdownMenuItem><DropdownMenuSeparator /></>)}@@ -1396,7 +1396,8 @@ function AnnotatePageButton({ tab }: { tab: BrowserTab | undefined }) {);}-function WebToolbar({ tab }: { tab: BrowserTab | undefined }) {+/** `visible`: the panel's chat is shown (BrowserPanel `active`). */+function WebToolbar({ tab, visible }: { tab: BrowserTab | undefined; visible: boolean }) {const t = useT();const { goBack, goForward, reload } = useBrowserStore.getState();const native = nativePage(tab);@@ -1455,7 +1456,7 @@ function WebToolbar({ tab }: { tab: BrowserTab | undefined }) {}/><div className="flex shrink-0 items-center gap-0.5">- <WebActions tab={tab} />+ <WebActions tab={tab} visible={visible} /><PanelMenu tab={tab} /></div></>@@ -1475,7 +1476,8 @@ function isVideoEntry(entry: Extract<BrowserEntry, { kind: "file" }>): boolean {function BrowserFileToolbar({tab,entry,-}: { tab: BrowserTab; entry: Extract<BrowserEntry, { kind: "file" }> }) {+ visible,+}: { tab: BrowserTab; entry: Extract<BrowserEntry, { kind: "file" }>; visible: boolean }) {const t = useT();const navigate = useNavigate();const requestEdits = useBrowserStore((state) => state.requestEdits);@@ -1673,6 +1675,7 @@ function BrowserFileToolbar({><HugeiconsIcon icon={Download01Icon} strokeWidth={1.75} className="size-4.5" /></IconButton>+ <DownloadsButton className={NAV_BUTTON} visible={visible} idleHidden={true} /><PanelMenu tab={tab}><div className="flex items-start gap-3 px-3 py-2 text-sm"><KindIcon name={entry.name} contentType={entry.contentType} className="mt-0.5 size-4.5" mono={true} />@@ -1737,7 +1740,8 @@ function BrowserFileToolbar({function FloatingFileToolbar({tab,entry,-}: { tab: BrowserTab; entry: Extract<BrowserEntry, { kind: "file" }> }) {+ visible,+}: { tab: BrowserTab; entry: Extract<BrowserEntry, { kind: "file" }>; visible: boolean }) {const t = useT();const navigate = useNavigate();const requestEdits = useBrowserStore((state) => state.requestEdits);@@ -2058,6 +2062,7 @@ function FloatingFileToolbar({onClick={() => download && void saveBrowserDownload(download)}className="size-9"/>+ <DownloadsButton className={cn(PILL, "size-9")} visible={visible} idleHidden={true} /></>);}@@ -2080,7 +2085,8 @@ function SplitChevron() {function VideoFileToolbar({tab,entry,-}: { tab: BrowserTab; entry: Extract<BrowserEntry, { kind: "file" }> }) {+ visible,+}: { tab: BrowserTab; entry: Extract<BrowserEntry, { kind: "file" }>; visible: boolean }) {const t = useT();const navigate = useNavigate();const download = tabDownload(tab);@@ -2227,6 +2233,7 @@ function VideoFileToolbar({</DropdownMenuContent></DropdownMenu></div>+ <DownloadsButton className={NAV_BUTTON} visible={visible} idleHidden={true} /><PanelMenu tab={tab} /></>);@@ -2387,14 +2394,14 @@ export const BrowserPanel = memo(function BrowserPanel({ active = true }: { acti>{activeTab && activeEntry?.kind === "file" ? (floatingFileControls ? (- <FloatingFileToolbar tab={activeTab} entry={activeEntry} />+ <FloatingFileToolbar tab={activeTab} entry={activeEntry} visible={active} />) : isVideoEntry(activeEntry) ? (- <VideoFileToolbar tab={activeTab} entry={activeEntry} />+ <VideoFileToolbar tab={activeTab} entry={activeEntry} visible={active} />) : (- <BrowserFileToolbar tab={activeTab} entry={activeEntry} />+ <BrowserFileToolbar tab={activeTab} entry={activeEntry} visible={active} />)) : (- <WebToolbar tab={activeTab} />+ <WebToolbar tab={activeTab} visible={active} />)}</div>{floatingFileControls || (activeEntry?.kind === "file" && isVideoEntry(activeEntry)) ? null : (diff --git a/studio/frontend/src/features/browser/download-activity.ts b/studio/frontend/src/features/browser/download-activity.tsnew file mode 100644index 00000000000..19c9d50be0a--- /dev/null+++ b/studio/frontend/src/features/browser/download-activity.ts@@ -0,0 +1,147 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Live state for the toolbar's Downloads button: running downloads and the latest finish.+// Session only; history-store.ts keeps the lasting record.++import { getLocale, translate } from "@/i18n";+import { toast } from "@/lib/toast";+import { create } from "zustand";+import { useBrowserHistoryStore } from "./history-store";++export type FinishedDownload = {+ key: string;+ name: string;+ size: number;+ contentType: string;+ url: string | null;+ /** Desktop app id for the saved file, to reveal or open it. */+ nativeId?: string;+ /** Its Download history row, when history is kept. */+ historyId?: string;+ failed: boolean;+};++type DownloadActivity = {+ active: Record<string, string>;+ /** The result a Downloads button is showing; null once dismissed or when none was on screen. */+ finished: FinishedDownload | null;+ /** Bumped per finish, so the same file downloaded twice shows again. */+ finishedSequence: number;+ /** Downloads buttons on screen. With none, a finish has nowhere to show but a toast. */+ buttons: number;+ dismissFinished: () => void;+};++// Saved from the panel this session, so Open can show the file again without the disk.+const MAX_KEPT_FILES = 8;+const keptFiles = new Map<string, { blob: Blob; name: string; contentType: string }>();++/** A result with no history row can only be reached from its notice: drop its bytes as that goes. */+function release(finished: FinishedDownload | null): void {+ if (finished && !finished.historyId) keptFiles.delete(finished.key);+}++export const useDownloadActivity = create<DownloadActivity>((set, get) => ({+ active: {},+ finished: null,+ finishedSequence: 0,+ buttons: 0,+ dismissFinished: () => {+ release(get().finished);+ set({ finished: null });+ },+}));++export function keptDownloadFile(id: string | undefined) {+ return id ? (keptFiles.get(id) ?? null) : null;+}++// Kept under a history row's id: they go when the row does (removed, cleared or pushed out).+const keptRows = new Set<string>();+let watchingRows = false;++/** Subscribed on first use, not at load: the history store sits in the chat import cycle. */+function watchRows(): void {+ if (watchingRows) return;+ watchingRows = true;+ useBrowserHistoryStore.subscribe((state, previous) => {+ if (state.downloads === previous.downloads || keptRows.size === 0) return;+ const rows = new Set(state.downloads.map((item) => item.id));+ for (const id of keptRows) {+ if (rows.has(id)) continue;+ keptRows.delete(id);+ keptFiles.delete(id);+ }+ });+}++function keepFile(id: string, file: { blob: Blob; name: string; contentType: string }, row: boolean): void {+ keptFiles.delete(id);+ keptFiles.set(id, file);+ if (row) {+ watchRows();+ keptRows.add(id);+ }+ for (const old of [...keptFiles.keys()].slice(0, Math.max(0, keptFiles.size - MAX_KEPT_FILES))) {+ keptFiles.delete(old);+ keptRows.delete(old);+ }+}++export function mountDownloadsButton(): () => void {+ useDownloadActivity.setState((state) => ({ buttons: state.buttons + 1 }));+ return () => {+ useDownloadActivity.setState((state) => ({ buttons: state.buttons - 1 }));+ // With the last button its notice and timer go too. A tab change swaps buttons in one commit,+ // so only once none came back.+ queueMicrotask(() => {+ const { buttons, dismissFinished } = useDownloadActivity.getState();+ if (buttons === 0) dismissFinished();+ });+ };+}++/** Marks a download as running under `key`; the button spins until it ends. */+export function beginDownload(key: string, name: string): void {+ useDownloadActivity.setState((state) => ({ active: { ...state.active, [key]: name } }));+}++/** Drops a download that never started (a save dialog cancelled), without a result to show. */+export function abandonDownload(key: string): void {+ useDownloadActivity.setState((state) => {+ if (!(key in state.active)) return state;+ const active = { ...state.active };+ delete active[key];+ return { active };+ });+}++/** Ends `key` and shows the result on the Downloads button. `historyId`: what recordDownload returned.+ * False when no button is on screen. */+export function finishDownload(+ key: string,+ result: Omit<FinishedDownload, "key">,+ file?: { blob: Blob; name: string; contentType: string },+): boolean {+ const { finished: replaced, buttons } = useDownloadActivity.getState();+ // A replaced result the list can't show (failed or unrecorded) would vanish: toast it instead.+ if (replaced && !replaced.historyId) {+ const title = replaced.failed ? "browser.downloads.failed" : "browser.downloads.complete";+ toast[replaced.failed ? "error" : "success"](translate(title, {}, getLocale()), { description: replaced.name });+ }+ release(replaced);+ // Unrecorded, its native id was forgotten (history-store.ts), so it can't open or reveal.+ const nativeId = result.historyId ? result.nativeId : undefined;+ // Only a history row or a notice on screen can reach the copy; with neither it would only sit in memory.+ if (file && (result.historyId || buttons > 0)) keepFile(result.historyId ?? key, file, Boolean(result.historyId));+ const active = { ...useDownloadActivity.getState().active };+ delete active[key];+ // With no button on screen the caller toasts it, so nothing holds it here.+ useDownloadActivity.setState((state) => ({+ active,+ finished: buttons > 0 ? { ...result, nativeId, key } : null,+ finishedSequence: state.finishedSequence + 1,+ }));+ return buttons > 0;+}diff --git a/studio/frontend/src/features/browser/download-approval.tsx b/studio/frontend/src/features/browser/download-approval.tsxindex f631b1f2f94..1a8f3c55dea 100644--- a/studio/frontend/src/features/browser/download-approval.tsx+++ b/studio/frontend/src/features/browser/download-approval.tsx@@ -43,7 +43,8 @@ export function DownloadApprovalDialog() {</p>) : null}</AlertDialogHeader>- {request?.origin ? (+ {/* Files that run code ask every time, so there's nothing to remember. */}+ {request?.origin && !request.dangerous ? (<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")}diff --git a/studio/frontend/src/features/browser/download-format.ts b/studio/frontend/src/features/browser/download-format.tsnew file mode 100644index 00000000000..b7de3d1c3f3--- /dev/null+++ b/studio/frontend/src/features/browser/download-format.ts@@ -0,0 +1,27 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/** Decimal units, as file managers show sizes. */+export function formatSize(bytes: number, locale: string): string {+ const units = ["byte", "kilobyte", "megabyte", "gigabyte"] as const;+ let value = bytes;+ let unit = 0;+ while (value >= 1000 && unit < units.length - 1) {+ value /= 1000;+ unit++;+ }+ return new Intl.NumberFormat(locale, {+ style: "unit",+ unit: units[unit],+ unitDisplay: "short",+ maximumFractionDigits: value < 10 && unit > 0 ? 1 : 0,+ }).format(value);+}++/** Each platform's own name for showing a file in its folder. */+export function revealLabelKey() {+ const platform = typeof navigator === "undefined" ? "" : navigator.userAgent;+ if (/Mac/i.test(platform)) return "browser.pages.showInFinder" as const;+ if (/Windows/i.test(platform)) return "browser.pages.showInExplorer" as const;+ return "browser.pages.showInFolder" as const;+}diff --git a/studio/frontend/src/features/browser/download-open.ts b/studio/frontend/src/features/browser/download-open.tsnew file mode 100644index 00000000000..ad8f1bfc8e0--- /dev/null+++ b/studio/frontend/src/features/browser/download-open.ts@@ -0,0 +1,36 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Open and Show in folder for a download, shared by the Downloads button and the Downloads page.++import { isTauri } from "@/lib/api-base";+import { keptDownloadFile } from "./download-activity";+import { isDangerousDownload } from "./download-safety";+import type { DownloadItem } from "./history-store";+import { openNativeDownload, revealNativeDownload } from "./native-downloads";+import { useBrowserStore } from "./store";++export type Target = Pick<DownloadItem, "name" | "contentType" | "url" | "nativeId"> & { keptId?: string };++/** Open a download: the saved file on the desktop, this session's copy in a tab, else its page. */+export function openTarget(target: Target, onFailed: (name: string) => void): (() => void) | undefined {+ if (isTauri && target.nativeId) {+ // The app refuses to open programs and scripts (browser_download_open); Show in folder still works.+ if (isDangerousDownload(target.name)) return undefined;+ const id = target.nativeId;+ return () => void openNativeDownload(id).catch(() => onFailed(target.name));+ }+ const kept = keptDownloadFile(target.keptId);+ if (kept) {+ return () =>+ useBrowserStore.getState().openFile({ ...kept, key: `download:${target.keptId}` });+ }+ const url = target.url;+ return url ? () => useBrowserStore.getState().openUrl(url, { newTab: true }) : undefined;+}++export function revealTarget(target: Target, onFailed: (name: string) => void): (() => void) | undefined {+ if (!isTauri || !target.nativeId) return undefined;+ const id = target.nativeId;+ return () => void revealNativeDownload(id).catch(() => onFailed(target.name));+}diff --git a/studio/frontend/src/features/browser/downloads-button.tsx b/studio/frontend/src/features/browser/downloads-button.tsxnew file mode 100644index 00000000000..f0c2ea4152d--- /dev/null+++ b/studio/frontend/src/features/browser/downloads-button.tsx@@ -0,0 +1,412 @@+// 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 {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { Popover, PopoverAnchor, PopoverContent } from "@/components/ui/popover";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { ATTACHMENT_KIND_ICON_CLASS, ATTACHMENT_KIND_ICONS, attachmentFileKind } from "@/features/chat";+import { useLocale, useT } from "@/i18n";+import { isTauri } from "@/lib/api-base";+import { copyToClipboard } from "@/lib/copy-to-clipboard";+import { toast } from "@/lib/toast";+import { cn } from "@/lib/utils";+import {+ Alert02Icon,+ CheckmarkCircle02Icon,+ Copy01Icon,+ Delete02Icon,+ Download01Icon,+ Folder01Icon,+ MoreHorizontalIcon,+ ArrowUpRight01Icon,+} from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import { useEffect, useState } from "react";+import { type FinishedDownload, mountDownloadsButton, useDownloadActivity } from "./download-activity";+import { formatSize, revealLabelKey } from "./download-format";+import { type Target, openTarget, revealTarget } from "./download-open";+import { type DownloadItem, useBrowserHistoryStore } from "./history-store";+import { nativeDownloadsExist } from "./native-downloads";+import { useBrowserStore } from "./store";++const RECENT_COUNT = 8;+// Long enough to read and reach for Open; hovering keeps it up.+const COMPLETE_SHOWN_MS = 6000;++const ROUND_ACTION =+ "flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-[color-mix(in_oklab,var(--foreground)_7%,transparent)] hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40 data-[state=open]:bg-[color-mix(in_oklab,var(--foreground)_8%,transparent)]";++/** Desktop downloads missing from disk, by native id. Checked as the list opens, on window focus, and+ * after an action fails, as the Downloads page does. */+function useMissing(downloads: DownloadItem[], enabled: boolean) {+ const [missing, setMissing] = useState<ReadonlySet<string>>(() => new Set());+ const [checks, setChecks] = useState(0);+ // Keyed by the ids, not the array, which is new on every render.+ const ids = downloads.flatMap((item) => (item.nativeId ? [item.nativeId] : [])).join("\n");+ useEffect(() => {+ if (!enabled || !isTauri || !ids) return;+ const list = ids.split("\n");+ let live = true;+ const check = () =>+ nativeDownloadsExist(list).then(+ (found) => live && setMissing(new Set(list.filter((_, index) => !found[index]))),+ () => undefined,+ );+ void check();+ window.addEventListener("focus", check);+ return () => {+ live = false;+ window.removeEventListener("focus", check);+ };+ }, [ids, enabled, checks]);+ return { missing, recheck: () => setChecks((count) => count + 1) };+}++function KindTile({ name, contentType, muted }: { name: string; contentType: string; muted?: boolean }) {+ const kind = attachmentFileKind(name, contentType);+ return (+ <span className="flex size-10 shrink-0 items-center justify-center rounded-xl bg-[color-mix(in_oklab,var(--foreground)_6%,transparent)]">+ <HugeiconsIcon+ icon={ATTACHMENT_KIND_ICONS[kind]}+ strokeWidth={1.75}+ className={cn("size-4.5", muted ? "text-muted-foreground" : ATTACHMENT_KIND_ICON_CLASS[kind])}+ />+ </span>+ );+}++function DownloadRow({+ item,+ missing,+ onFailed,+ onDone,+}: {+ item: DownloadItem;+ missing: boolean;+ /** After Open or Show in folder fails, so the row can learn the file is gone. */+ onFailed: () => void;+ onDone: () => void;+}) {+ const t = useT();+ const locale = useLocale();+ const failed = (key: "browser.downloads.openFailed" | "browser.pages.revealFailed") => (name: string) => {+ toast.error(t(key, { name }));+ onFailed();+ };+ const target: Target = { ...item, keptId: item.id };+ const open = missing ? undefined : openTarget(target, failed("browser.downloads.openFailed"));+ const reveal = missing ? undefined : revealTarget(target, failed("browser.pages.revealFailed"));+ const time = new Intl.DateTimeFormat(locale, { timeStyle: "short" }).format(item.downloadedAt);+ const status = t(missing ? "browser.downloads.missing" : "browser.downloads.downloaded");+ const revealLabel = t(revealLabelKey());+ const run = (action: (() => void) | undefined) => () => {+ action?.();+ onDone();+ };+ return (+ <li className="group/row flex items-center gap-3 rounded-2xl px-2 py-1.5 hover:bg-[color-mix(in_oklab,var(--foreground)_4%,transparent)]">+ <button+ type="button"+ onClick={run(open)}+ disabled={!open}+ title={item.name}+ className="flex min-w-0 flex-1 cursor-pointer items-center gap-3 text-start focus-visible:outline-none disabled:cursor-default"+ >+ <KindTile name={item.name} contentType={item.contentType} muted={missing} />+ <span className="flex min-w-0 flex-col">+ <span className={cn("truncate text-ui-14", missing ? "text-muted-foreground" : "text-foreground")}>+ {item.name}+ </span>+ <span className="truncate text-ui-12 text-muted-foreground tabular-nums">+ {[status, item.size > 0 ? formatSize(item.size, locale) : null, time].filter(Boolean).join(" · ")}+ </span>+ </span>+ </button>+ {isTauri ? (+ <Tooltip>+ <TooltipTrigger asChild={true}>+ <button type="button" aria-label={revealLabel} disabled={!reveal} onClick={run(reveal)} className={ROUND_ACTION}>+ <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-4.5" />+ </button>+ </TooltipTrigger>+ <TooltipContent className="tooltip-compact">{revealLabel}</TooltipContent>+ </Tooltip>+ ) : null}+ <DropdownMenu>+ <DropdownMenuTrigger asChild={true}>+ <button type="button" aria-label={t("browser.more")} className={ROUND_ACTION}>+ <HugeiconsIcon icon={MoreHorizontalIcon} strokeWidth={1.75} className="size-4.5" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="browser-menu min-w-48 rounded-[20px] p-1.5">+ <DropdownMenuItem disabled={!open} onSelect={run(open)}>+ <HugeiconsIcon icon={ArrowUpRight01Icon} strokeWidth={1.75} className="size-4" />+ {t("browser.downloads.open")}+ </DropdownMenuItem>+ {isTauri ? (+ <DropdownMenuItem disabled={!reveal} onSelect={run(reveal)}>+ <HugeiconsIcon icon={Folder01Icon} strokeWidth={1.75} className="size-4" />+ {revealLabel}+ </DropdownMenuItem>+ ) : null}+ {item.url ? (+ <DropdownMenuItem+ onSelect={() =>+ void copyToClipboard(item.url ?? "").then((ok) => ok && toast.success(t("browser.linkCopied")))+ }+ >+ <HugeiconsIcon icon={Copy01Icon} strokeWidth={1.75} className="size-4" />+ {t("browser.downloads.copyLink")}+ </DropdownMenuItem>+ ) : null}+ <DropdownMenuItem onSelect={() => useBrowserHistoryStore.getState().removeDownload(item.id)}>+ <HugeiconsIcon icon={Delete02Icon} strokeWidth={1.75} className="size-4" />+ {t("browser.pages.removeFromHistory")}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </li>+ );+}++function RecentDownloads({ open, onDone }: { open: boolean; onDone: () => void }) {+ const t = useT();+ const downloads = useBrowserHistoryStore((state) => state.downloads);+ const active = useDownloadActivity((state) => state.active);+ const recent = downloads.slice(0, RECENT_COUNT);+ const { missing, recheck } = useMissing(recent, open);+ const running = Object.entries(active);+ return (+ <>+ <div className="flex items-center justify-between gap-2 pr-1 pl-2">+ <span className="text-ui-14 font-medium text-foreground">{t("browser.downloads.title")}</span>+ <button+ type="button"+ onClick={() => {+ useBrowserStore.getState().openInternal("downloads");+ onDone();+ }}+ className="h-7 cursor-pointer rounded-full px-2.5 text-ui-12p5 text-muted-foreground transition-colors hover:bg-[color-mix(in_oklab,var(--foreground)_7%,transparent)] hover:text-foreground"+ >+ {t("browser.downloads.showAll")}+ </button>+ </div>+ {running.length === 0 && recent.length === 0 ? (+ <p className="px-2 py-6 text-center text-ui-13 text-muted-foreground">{t("browser.pages.noDownloads")}</p>+ ) : (+ <ul className="flex flex-col">+ {running.map(([key, name]) => (+ <li key={key} className="flex items-center gap-3 px-2 py-1.5">+ <KindTile name={name} contentType="" />+ <span className="flex min-w-0 flex-col">+ <span className="truncate text-ui-14 text-foreground">{name}</span>+ <span className="text-ui-12 text-muted-foreground">{t("browser.downloads.inProgress")}</span>+ </span>+ </li>+ ))}+ {recent.map((item) => (+ <DownloadRow+ key={item.id}+ item={item}+ missing={item.nativeId !== undefined && missing.has(item.nativeId)}+ onFailed={recheck}+ onDone={onDone}+ />+ ))}+ </ul>+ )}+ </>+ );+}++function FinishedNotice({ finished, onDone }: { finished: FinishedDownload; onDone: () => void }) {+ const t = useT();+ const failed = (key: "browser.downloads.openFailed" | "browser.pages.revealFailed") => (name: string) =>+ toast.error(t(key, { name }));+ const target: Target = { ...finished, keptId: finished.historyId ?? finished.key };+ const open = finished.failed ? undefined : openTarget(target, failed("browser.downloads.openFailed"));+ const reveal = finished.failed ? undefined : revealTarget(target, failed("browser.pages.revealFailed"));+ const run = (action: () => void) => () => {+ action();+ onDone();+ };+ return (+ <div className="flex flex-col gap-3 px-1">+ <div className="flex min-w-0 items-start gap-2.5">+ <HugeiconsIcon+ icon={finished.failed ? Alert02Icon : CheckmarkCircle02Icon}+ strokeWidth={2}+ className={cn("mt-0.5 size-5 shrink-0", finished.failed ? "text-destructive" : "text-primary")}+ />+ <span className="flex min-w-0 flex-col">+ <span className="text-ui-14 font-medium text-foreground">+ {t(finished.failed ? "browser.downloads.failed" : "browser.downloads.complete")}+ </span>+ <span className="truncate text-ui-13 text-muted-foreground" title={finished.name}>+ {finished.name}+ </span>+ </span>+ </div>+ {open || reveal ? (+ <div className="flex justify-end gap-2">+ {reveal ? (+ <button+ type="button"+ onClick={run(reveal)}+ className="h-8 cursor-pointer rounded-full bg-[color-mix(in_oklab,var(--foreground)_8%,transparent)] px-3.5 text-ui-13 text-foreground transition-colors hover:bg-[color-mix(in_oklab,var(--foreground)_12%,transparent)]"+ >+ {t(revealLabelKey())}+ </button>+ ) : null}+ {open ? (+ <button+ type="button"+ onClick={run(open)}+ className="h-8 cursor-pointer rounded-full bg-foreground px-3.5 text-ui-13 text-background transition-opacity hover:opacity-85"+ >+ {t("browser.downloads.open")}+ </button>+ ) : null}+ </div>+ ) : null}+ </div>+ );+}++/** The download glyph while a file downloads: its arrow inside a spinning ring, the tray bar below. */+function DownloadingIcon() {+ return (+ <svg+ aria-hidden={true}+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth={1.75}+ strokeLinecap="round"+ strokeLinejoin="round"+ className="size-5"+ >+ <path d="M12 13.5V6M15.25 10.5c0 0-2.4 3.25-3.25 3.25s-3.25-3.25-3.25-3.25" />+ <path d="M6.5 21.5h11" />+ <circle cx="12" cy="10" r="8.5" strokeOpacity={0.25} />+ <circle+ cx="12"+ cy="10"+ r="8.5"+ strokeDasharray="17 36.4"+ className="animate-spin [animation-duration:1.4s] [transform-box:view-box] [transform-origin:12px_10px]"+ />+ </svg>+ );+}++/** Toolbar Downloads button: a ring while files download, a notice when one finishes, recent downloads on click. */+/** `visible`: false while its panel stays mounted off screen, so results go to a toast instead.+ * `idleHidden`: file tabs keep their own save button, so the glyph shows only while a download runs+ * or its result is up. It stays registered meanwhile, so a quick save still finds it. */+export function DownloadsButton({+ className,+ visible = true,+ idleHidden = false,+}: { className?: string; visible?: boolean; idleHidden?: boolean }) {+ const t = useT();+ const active = useDownloadActivity((state) => Object.keys(state.active).length > 0);+ const finished = useDownloadActivity((state) => state.finished);+ const finishedSequence = useDownloadActivity((state) => state.finishedSequence);+ // A notice another toolbar's button was showing (the tab changed) carries on here.+ const [mode, setMode] = useState<"closed" | "list" | "finished">(() =>+ visible && finished ? "finished" : "closed",+ );+ const [hovered, setHovered] = useState(false);+ // Only finishes after mount pop the notice. An open list shows recorded ones itself; the rest still need it.+ const [seen, setSeen] = useState(finishedSequence);+ if (finishedSequence !== seen) {+ setSeen(finishedSequence);+ if (visible && finished && (mode !== "list" || !finished.historyId)) {+ setMode("finished");+ setHovered(false);+ }+ }++ // Off screen its popover, portaled out of the panel, would stay up over the next page.+ if (!visible && mode !== "closed") {+ setMode("closed");+ setHovered(false);+ }++ useEffect(() => (visible ? mountDownloadsButton() : undefined), [visible]);++ const close = () => {+ setMode("closed");+ setHovered(false);+ useDownloadActivity.getState().dismissFinished();+ };++ // Hovering holds the notice; leaving starts the countdown again.+ useEffect(() => {+ if (mode !== "finished" || hovered) return;+ const timer = window.setTimeout(() => {+ setMode("closed");+ useDownloadActivity.getState().dismissFinished();+ }, COMPLETE_SHOWN_MS);+ return () => window.clearTimeout(timer);+ }, [mode, hovered, finishedSequence]);+ const label = t(active ? "browser.downloads.inProgressLabel" : "browser.downloads.title");+ const lit = active || mode === "finished";++ return (+ <Popover open={mode !== "closed"} onOpenChange={(open) => (open ? setMode("list") : close())}>+ <PopoverAnchor asChild={true}>+ <span+ className={cn(+ "relative flex shrink-0",+ idleHidden && !active && !finished && mode === "closed" && "hidden",+ )}+ >+ <Tooltip>+ <TooltipTrigger asChild={true}>+ <button+ type="button"+ aria-label={label}+ aria-expanded={mode !== "closed"}+ onClick={() => (mode === "list" ? close() : setMode("list"))}+ className={cn(className, lit && "text-primary hover:text-primary")}+ >+ {active ? (+ <DownloadingIcon />+ ) : (+ <HugeiconsIcon icon={Download01Icon} strokeWidth={1.75} className="size-4.5" />+ )}+ </button>+ </TooltipTrigger>+ <TooltipContent side="bottom" className="tooltip-compact">+ {label}+ </TooltipContent>+ </Tooltip>+ </span>+ </PopoverAnchor>+ <PopoverContent+ align="end"+ sideOffset={8}+ onOpenAutoFocus={(event) => mode === "finished" && event.preventDefault()}+ onMouseEnter={() => setHovered(true)}+ onMouseLeave={() => setHovered(false)}+ className={cn(+ "browser-menu gap-2 rounded-[22px] p-2",+ mode === "finished" ? "w-80 p-3" : "w-96 max-h-[min(32rem,var(--radix-popover-content-available-height))]",+ )}+ >+ {mode === "finished" && finished ? (+ <FinishedNotice finished={finished} onDone={close} />+ ) : (+ <RecentDownloads open={mode === "list"} onDone={close} />+ )}+ </PopoverContent>+ </Popover>+ );+}diff --git a/studio/frontend/src/features/browser/downloads.ts b/studio/frontend/src/features/browser/downloads.tsindex b127bb22922..67c3ae3d114 100644--- a/studio/frontend/src/features/browser/downloads.ts+++ b/studio/frontend/src/features/browser/downloads.ts@@ -7,6 +7,7 @@ import { DownloadCancelledError, downloadFile, isDownloadCancelled } from "@/libimport { toast } from "@/lib/toast";import { fileNameFromUrl, isWebUrl, safeDownloadName, withBaseUrl } from "./address";import { type BrowserPage, fetchBrowserPage } from "./api";+import { abandonDownload, beginDownload, finishDownload } from "./download-activity";import { approveDownload } from "./download-approval-queue";import { isDangerousDownload } from "./download-safety";import { useBrowserHistoryStore } from "./history-store";@@ -81,11 +82,16 @@ async function writeDownload(download: BrowserDownload, target: SaveHandle | nulconst name = safeDownloadName(download.name);let saved: SavedNativeDownload | null = null;let picked: SaveHandle | null = null;+ const key = `save:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`;+ beginDownload(key, name);try {if (isTauri) {// The app keeps the path so Download history can reveal it.saved = await saveNativeDownload(blob, name, useBrowserPrefsStore.getState().askWhereToSave, url);- if (!saved) return;+ if (!saved) {+ abandonDownload(key);+ return;+ }} else {picked = target === undefined ? await pickSaveTarget(name) : target;if (picked) {@@ -97,18 +103,28 @@ async function writeDownload(download: BrowserDownload, target: SaveHandle | nul}}} catch (error) {+ abandonDownload(key);if (!isDownloadCancelled(error)) toast.error(error instanceof Error ? error.message : String(error));return;}- useBrowserHistoryStore.getState().recordDownload({- name: saved?.name || picked?.name || name,+ const savedName = saved?.name || picked?.name || name;+ const historyId = useBrowserHistoryStore.getState().recordDownload({+ name: savedName,url,size: blob.size,contentType,nativeId: saved?.id,});+ // Open uses the saved file when the app kept it; only otherwise does this session hold the bytes.+ const shown = finishDownload(+ key,+ { name: savedName, size: blob.size, contentType, url, nativeId: saved?.id, historyId, failed: false },+ saved && historyId ? undefined : { blob, name: savedName, contentType },+ );if (saved?.marked === false) {- toast.warning(translate("browser.native.notMarked", { name: saved.name || name }, getLocale()));+ toast.warning(translate("browser.native.notMarked", { name: savedName }, getLocale()));+ } else if (!shown) {+ toast.success(translate("browser.downloads.complete", {}, getLocale()), { description: savedName });}}diff --git a/studio/frontend/src/features/browser/history-store.ts b/studio/frontend/src/features/browser/history-store.tsindex 26626ac208f..51770f84bc2 100644--- a/studio/frontend/src/features/browser/history-store.ts+++ b/studio/frontend/src/features/browser/history-store.ts@@ -25,6 +25,14 @@ const MAX_DOWNLOADS = 200;// Pages pick their URLs and titles; cap them so history can't fill Studio's storage.export const MAX_URL_CHARS = 2048;export const MAX_TITLE_CHARS = 200;++/** Bounded like a title, but keeping a short extension: it says what the file is, and whether it runs code. */+function boundedName(name: string): string {+ if (name.length <= MAX_TITLE_CHARS) return name;+ const dot = name.lastIndexOf(".");+ const extension = dot > 0 && name.length - dot <= 32 ? name.slice(dot) : "";+ return name.slice(0, MAX_TITLE_CHARS - extension.length) + extension;+}// The icons sites declare, by host: most sites name theirs in the page, not at /favicon.ico.const MAX_ICONS = 300;const PERSIST_DELAY_MS = 1000;@@ -81,7 +89,8 @@ interface BrowserHistoryState {icons: Record<string, string>;recordVisit: (url: string, title: string) => void;recordIcon: (host: string, icon: string) => void;- recordDownload: (item: Omit<DownloadItem, "id" | "downloadedAt">) => void;+ /** The new row's id; undefined when download history is off. */+ recordDownload: (item: Omit<DownloadItem, "id" | "downloadedAt">) => string | undefined;removeVisit: (id: string) => void;removeVisits: (ids: ReadonlySet<string>) => void;removeDownload: (id: string) => void;@@ -123,26 +132,29 @@ export const useBrowserHistoryStore = create<BrowserHistoryState>()(const icons = kept.length < state.history.length ? iconsFor(history, state.icons) : state.icons;return { history, icons };}),- recordDownload: (item) =>+ recordDownload: (item) => {+ if (!useBrowserPrefsStore.getState().saveDownloadHistory) {+ if (item.nativeId) forgetNativeDownloads([item.nativeId]);+ return undefined;+ }+ const id = newId();set((state) => {- if (!useBrowserPrefsStore.getState().saveDownloadHistory) {- if (item.nativeId) forgetNativeDownloads([item.nativeId]);- return state;- }// A page picks these: bounded like a visit, keeping the download without an overlong address.const entry = {...item,- name: item.name.slice(0, MAX_TITLE_CHARS),+ name: boundedName(item.name),url: item.url !== null && item.url.length <= MAX_URL_CHARS ? item.url : null,contentType: item.contentType.slice(0, MAX_TITLE_CHARS),- id: newId(),+ id,downloadedAt: Date.now(),};const downloads = [entry, ...state.downloads];const dropped = downloads.slice(MAX_DOWNLOADS).flatMap((item) => (item.nativeId ? [item.nativeId] : []));forgetNativeDownloads(dropped);return { downloads: downloads.slice(0, MAX_DOWNLOADS) };- }),+ });+ return id;+ },removeVisit: (id) => set((state) => ({ history: state.history.filter((item) => item.id !== id) })),removeVisits: (ids) => set((state) => ({ history: state.history.filter((item) => !ids.has(item.id)) })),removeDownload: (id) =>diff --git a/studio/frontend/src/features/browser/internal-pages.tsx b/studio/frontend/src/features/browser/internal-pages.tsxindex 2ea058a18aa..5ea8479e599 100644--- a/studio/frontend/src/features/browser/internal-pages.tsx+++ b/studio/frontend/src/features/browser/internal-pages.tsx@@ -42,6 +42,8 @@ import { BookmarkEditPopover, bookmarkTitle, removeBookmarkWithUndo } from "./boimport { type Bookmark, useBrowserBookmarksStore } from "./bookmarks-store";import { ClearBrowsingDataDialog } from "./clear-data-dialog";import { type DownloadItem, type HistoryItem, useBrowserHistoryStore } from "./history-store";+import { formatSize, revealLabelKey } from "./download-format";+import { openTarget } from "./download-open";import { LinkContextMenu, MenuRow } from "./link-context-menu";import { nativeDownloadsExist, revealNativeDownload } from "./native-downloads";import { SiteFavicon } from "./site-favicon";@@ -60,22 +62,6 @@ function addDays(day: number, days: number): number {return date.getTime();}-function formatSize(bytes: number, locale: string): string {- const units = ["byte", "kilobyte", "megabyte", "gigabyte"] as const;- let value = bytes;- let unit = 0;- while (value >= 1000 && unit < units.length - 1) {- value /= 1000;- unit++;- }- return new Intl.NumberFormat(locale, {- style: "unit",- unit: units[unit],- unitDisplay: "short",- maximumFractionDigits: value < 10 && unit > 0 ? 1 : 0,- }).format(value);-}-function PageShell({title,query,@@ -654,14 +640,6 @@ function HistoryPage({ tabId }: { tabId: string }) {);}-/** Each platform's own name for showing a file in its folder. */-function revealLabelKey() {- const platform = typeof navigator === "undefined" ? "" : navigator.userAgent;- if (/Mac/i.test(platform)) return "browser.pages.showInFinder" as const;- if (/Windows/i.test(platform)) return "browser.pages.showInExplorer" as const;- return "browser.pages.showInFolder" as const;-}-/** Desktop downloads missing from disk, by native id; rechecked on window focus. */function useMissingDownloads(downloads: DownloadItem[]) {const [missing, setMissing] = useState<ReadonlySet<string>>(() => new Set());@@ -694,12 +672,12 @@ function DownloadRow({item,time,deleted,- onRevealFailed,+ onActionFailed,}: {item: DownloadItem;time: string;deleted: boolean;- onRevealFailed: () => void;+ onActionFailed: () => void;}) {const t = useT();const locale = useLocale();@@ -712,11 +690,14 @@ function DownloadRow({? () =>void revealNativeDownload(nativeId).catch(() => {toast.error(t("browser.pages.revealFailed", { name: item.name }));- onRevealFailed();+ onActionFailed();}): undefined;- // Files aren't kept; the row reopens the source page.- const open = item.url ? () => useBrowserStore.getState().openUrl(item.url ?? "", { newTab: true }) : undefined;+ // As the Downloads button opens it: the saved file on the desktop, else this session's copy or the source page.+ const open = openTarget({ ...item, nativeId, keptId: item.id }, (name) => {+ toast.error(t("browser.downloads.openFailed", { name }));+ onActionFailed();+ });return (<LinkContextMenuurl={item.url}@@ -855,7 +836,7 @@ function DownloadsPage() {item={item}time={timeFormat.format(item.downloadedAt)}deleted={item.nativeId !== undefined && missing.has(item.nativeId)}- onRevealFailed={recheck}+ onActionFailed={recheck}/>))}</DayCard>diff --git a/studio/frontend/src/features/browser/native-downloads.ts b/studio/frontend/src/features/browser/native-downloads.tsindex 6e65110226c..d5b86170d13 100644--- a/studio/frontend/src/features/browser/native-downloads.ts+++ b/studio/frontend/src/features/browser/native-downloads.ts@@ -49,6 +49,11 @@ export function revealNativeDownload(id: string): Promise<void> {return invoke<void>("browser_download_reveal", { id });}+/** Opens with the default app; programs and scripts are refused. */+export function openNativeDownload(id: string): Promise<void> {+ return invoke<void>("browser_download_open", { id });+}+/** Whether each download is still where it was saved; all true outside the desktop app. */export async function nativeDownloadsExist(ids: string[]): Promise<boolean[]> {if (!isTauri || ids.length === 0) return ids.map(() => true);diff --git a/studio/frontend/src/features/browser/native-view.ts b/studio/frontend/src/features/browser/native-view.tsindex 977e05e842d..ef069fb526a 100644--- a/studio/frontend/src/features/browser/native-view.ts+++ b/studio/frontend/src/features/browser/native-view.ts@@ -11,6 +11,7 @@ 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 { abandonDownload, beginDownload, finishDownload, useDownloadActivity } from "./download-activity";import { proxiedFavicon } from "./favicon";import { useBrowserHistoryStore } from "./history-store";import { decideNativeDownload } from "./native-downloads";@@ -52,8 +53,11 @@ type NativeEvent =downloadId: string | null;/** False when the file couldn't be marked as downloaded from the internet; null where nothing marks. */marked?: boolean | null;+ /** The downloadPrompt `id` it was asked under; null when refused before asking. */+ promptId?: string | null;}- | { kind: "downloadPrompt"; tabId: string; url: string; site: string; name: string; id: string };+ | { kind: "downloadPrompt"; tabId: string; url: string; site: string; name: string; id: string }+ | { kind: "downloadCancelled"; tabId: string; url: string; promptId: string };type Bounds = { x: number; y: number; width: number; height: number; viewportWidth: number };@@ -118,6 +122,9 @@ function listenOnce(): void {);}+/** One running download in the Downloads button, from approval until it ends. */+const downloadKey = (promptId: string) => `native:${promptId}`;+/** 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;@@ -125,14 +132,20 @@ function onDownloadPrompt(event: Extract<NativeEvent, { kind: "downloadPrompt" }// 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);+ const key = downloadKey(id);void decided.then(async (allow) => {+ // Begun before deciding: a file that finished while the prompt was open lands at once.+ if (allow) beginDownload(key, name);await decideNativeDownload(id, allow, useBrowserPrefsStore.getState().askWhereToSave);- if (allow) toast(t("browser.native.downloading", { name }));+ // Still running: one that landed during the decide call has already said so.+ const { active, buttons } = useDownloadActivity.getState();+ if (allow && buttons === 0 && key in active) toast(t("browser.native.downloading", { name }));})- .catch(() => undefined);+ .catch(() => abandonDownload(key));}+function onNativeEvent(event: NativeEvent): void {const store = useBrowserStore.getState();const tab = store.tabs.find((candidate) => candidate.id === event.tabId);@@ -140,6 +153,10 @@ function onNativeEvent(event: NativeEvent): void {onDownloadPrompt(event, tab);return;}+ if (event.kind === "downloadCancelled") {+ abandonDownload(downloadKey(event.promptId));+ return;+ }// A download outlives its page: it often lands after the tab closed or moved on, and still belongs in history.if (event.kind === "download") {if (openedTabs.has(event.tabId)) onDownload(event);@@ -204,22 +221,32 @@ function onNativeEvent(event: NativeEvent): void {}}+/** Shown on the toolbar's Downloads button; toasts only when none is on screen. */function onDownload(event: Extract<NativeEvent, { kind: "download" }>): void {- if (!event.done) {- toast(t("browser.native.downloading", { name: event.name }));- } else if (event.success) {- useBrowserHistoryStore.getState().recordDownload({- name: event.name,- url: event.url,- size: event.size ?? 0,- contentType: "",- nativeId: event.downloadId ?? undefined,- });- if (event.marked === false) toast.warning(t("browser.native.notMarked", { name: event.name }));- else toast.success(t("browser.native.downloaded", { name: event.name }));- } else {- toast.error(t("browser.native.downloadFailed", { name: event.name }));- }+ // Refused before asking, it never ran: there's nothing to end, only a result to show.+ const key = event.promptId ? downloadKey(event.promptId) : `native:${event.tabId}:${event.url}`;+ if (!event.done) return;+ const historyId = event.success+ ? useBrowserHistoryStore.getState().recordDownload({+ name: event.name,+ url: event.url,+ size: event.size ?? 0,+ contentType: "",+ nativeId: event.downloadId ?? undefined,+ })+ : undefined;+ const shown = finishDownload(key, {+ name: event.name,+ size: event.size ?? 0,+ contentType: "",+ url: event.url,+ nativeId: event.downloadId ?? undefined,+ historyId,+ failed: !event.success,+ });+ if (event.success && event.marked === false) toast.warning(t("browser.native.notMarked", { name: event.name }));+ else if (!shown && event.success) toast.success(t("browser.native.downloaded", { name: event.name }));+ else if (!shown) toast.error(t("browser.native.downloadFailed", { name: event.name }));}// Pages can ask in a loop: one prompt on screen, replaced at most once a second.diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex fb626441072..e46f9a40c0f 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -262,6 +262,20 @@ export const en = {tablet: "Tablet",close: "Hide device toolbar",},+ downloads: {+ title: "Downloads",+ inProgressLabel: "Downloading",+ inProgress: "Downloading…",+ complete: "Download complete",+ failed: "Download failed",+ downloaded: "Downloaded",+ missing: "File moved or deleted",+ open: "Open",+ openFailed: "Couldn't open {name}.",+ copyLink: "Copy download link",+ showAll: "Show all",+ savePage: "Save page as…",+ },file: {openIn: "Open in",newChat: "New chat",diff --git a/studio/frontend/tests/browser-native-view-snapshot.test.ts b/studio/frontend/tests/browser-native-view-snapshot.test.tsindex a64ee1970f4..fa795f75668 100644--- a/studio/frontend/tests/browser-native-view-snapshot.test.ts+++ b/studio/frontend/tests/browser-native-view-snapshot.test.ts@@ -230,3 +230,149 @@ test("a finished download is listed and reported after its tab closed, and warnsstop();}});++test("an approved download runs on the Downloads button until it lands or its save is cancelled", async () => {+ const stop = startNativeViews();+ const g = globalThis as {+ nativeViewListener?: (event: { payload: unknown }) => void;+ nativeViewSeen?: unknown;+ nativeViewActivity?: string[];+ nativeViewApprove?: boolean;+ nativeViewDownloadsButton?: boolean;+ };+ g.nativeViewApprove = true;+ g.nativeViewDownloadsButton = true;+ try {+ useBrowserStore.getState().openUrl("https://example.org/", { newTab: true });+ await frame();+ const tabId = useBrowserStore.getState().activeTabId as string;+ g.nativeViewSeen = [];+ g.nativeViewActivity = [];+ const prompt = { kind: "downloadPrompt", tabId, site: "https://example.org/", name: "a.zip" };+ g.nativeViewListener?.({ payload: { ...prompt, url: "https://example.org/a.zip", id: "p1" } });+ g.nativeViewListener?.({ payload: { ...prompt, url: "https://example.org/b.zip", id: "p2" } });+ await frame();+ g.nativeViewListener?.({+ payload: {+ kind: "download", tabId, url: "https://example.org/a.zip", name: "a.zip", path: null, size: 3,+ done: true, success: true, downloadId: "d1", marked: true, promptId: "p1",+ },+ });+ g.nativeViewListener?.({+ payload: { kind: "downloadCancelled", tabId, url: "https://example.org/b.zip", promptId: "p2" },+ });+ assert.deepEqual(g.nativeViewActivity, ["begin native:p1", "begin native:p2", "finish native:p1", "abandon native:p2"]);+ // The button shows it running, so no "downloading" toast.+ assert.deepEqual(g.nativeViewSeen, [{ level: "history", message: "d1" }]);+ } finally {+ g.nativeViewApprove = false;+ g.nativeViewDownloadsButton = false;+ stop();+ }+});++test("two downloads of one address run apart: the first to land doesn't end the other", async () => {+ const stop = startNativeViews();+ const g = globalThis as {+ nativeViewListener?: (event: { payload: unknown }) => void;+ nativeViewSeen?: unknown;+ nativeViewActivity?: string[];+ nativeViewApprove?: boolean;+ };+ g.nativeViewApprove = true;+ try {+ useBrowserStore.getState().openUrl("https://example.org/", { newTab: true });+ await frame();+ const tabId = useBrowserStore.getState().activeTabId as string;+ const url = "https://example.org/same.zip";+ g.nativeViewSeen = [];+ g.nativeViewActivity = [];+ const prompt = { kind: "downloadPrompt", tabId, url, site: "https://example.org/", name: "same.zip" };+ g.nativeViewListener?.({ payload: { ...prompt, id: "p1" } });+ g.nativeViewListener?.({ payload: { ...prompt, id: "p2" } });+ await frame();+ g.nativeViewListener?.({+ payload: {+ kind: "download", tabId, url, name: "same.zip", path: null, size: 3,+ done: true, success: true, downloadId: "d1", marked: true, promptId: "p1",+ },+ });+ assert.deepEqual(g.nativeViewActivity, ["begin native:p1", "begin native:p2", "finish native:p1"]);+ } finally {+ g.nativeViewApprove = false;+ stop();+ }+});++test("a download that finished while its prompt was open doesn't keep spinning", async () => {+ const stop = startNativeViews();+ const g = globalThis as {+ nativeViewListener?: (event: { payload: unknown }) => void;+ nativeViewSeen?: unknown;+ nativeViewActivity?: string[];+ nativeViewApprove?: boolean;+ nativeViewDecide?: () => void;+ };+ g.nativeViewApprove = true;+ try {+ useBrowserStore.getState().openUrl("https://example.org/", { newTab: true });+ await frame();+ const tabId = useBrowserStore.getState().activeTabId as string;+ const url = "https://example.org/big.zip";+ g.nativeViewSeen = [];+ g.nativeViewActivity = [];+ // Already in staging, so the app delivers it before the decide call returns.+ g.nativeViewDecide = () =>+ g.nativeViewListener?.({+ payload: {+ kind: "download", tabId, url, name: "big.zip", path: null, size: 3,+ done: true, success: true, downloadId: "d1", marked: true, promptId: "p1",+ },+ });+ g.nativeViewListener?.({+ payload: { kind: "downloadPrompt", tabId, url, site: "https://example.org/", name: "big.zip", id: "p1" },+ });+ await frame();+ assert.deepEqual(g.nativeViewActivity, ["begin native:p1", "finish native:p1"]);+ // No button on screen: it says it downloaded, and not then that it's downloading.+ assert.deepEqual(g.nativeViewSeen, [+ { level: "history", message: "d1" },+ { level: "success", message: "browser.native.downloaded" },+ ]);+ } finally {+ g.nativeViewApprove = false;+ g.nativeViewDecide = undefined;+ stop();+ }+});++test("with a Downloads button on screen, a download shows there, not as a toast", async () => {+ const stop = startNativeViews();+ const g = globalThis as {+ nativeViewListener?: (event: { payload: unknown }) => void;+ nativeViewSeen?: unknown;+ nativeViewDownloadsButton?: boolean;+ };+ g.nativeViewDownloadsButton = true;+ try {+ useBrowserStore.getState().openUrl("https://example.org/", { newTab: true });+ await frame();+ const tabId = useBrowserStore.getState().activeTabId as string;+ const seen: { level: string; message: string }[] = [];+ g.nativeViewSeen = seen;+ const event = { kind: "download", tabId, url: "https://example.com/b.zip", name: "b.zip", path: null, size: 3 };+ g.nativeViewListener?.({ payload: { ...event, done: false, success: false, downloadId: null } });+ g.nativeViewListener?.({ payload: { ...event, done: true, success: true, downloadId: "d1", marked: true } });+ g.nativeViewListener?.({ payload: { ...event, done: true, success: false, downloadId: null } });+ g.nativeViewListener?.({ payload: { ...event, done: true, success: true, downloadId: "d2", marked: false } });+ // The unmarked warning still toasts: the button only says the file finished.+ assert.deepEqual(seen, [+ { level: "history", message: "d1" },+ { level: "history", message: "d2" },+ { level: "warning", message: "browser.native.notMarked" },+ ]);+ } finally {+ g.nativeViewDownloadsButton = false;+ stop();+ }+});diff --git a/studio/frontend/tests/browser-settings.test.ts b/studio/frontend/tests/browser-settings.test.tsindex 6bab4c83655..ab2e911f66a 100644--- a/studio/frontend/tests/browser-settings.test.ts+++ b/studio/frontend/tests/browser-settings.test.ts@@ -43,11 +43,12 @@ test("with download history off, downloads are not listed", () => {const history = useBrowserHistoryStore.getState();history.clearDownloads();useBrowserPrefsStore.getState().setSaveDownloadHistory(false);- history.recordDownload(download);+ assert.equal(history.recordDownload(download), undefined);assert.equal(useBrowserHistoryStore.getState().downloads.length, 0);useBrowserPrefsStore.getState().setSaveDownloadHistory(true);- history.recordDownload(download);+ const id = history.recordDownload(download);assert.equal(useBrowserHistoryStore.getState().downloads.length, 1);+ assert.equal(useBrowserHistoryStore.getState().downloads[0].id, id);});test("shortening how long history is kept drops older visits at once", () => {@@ -545,6 +546,94 @@ test("a blocked site's blob: page can't download past the block", async () => {prefs.setAskBeforeDownloading(true);});+test("the download prompt offers Remember only for files a remembered answer can cover", async () => {+ const { readFileSync } = await import("node:fs");+ const source = readFileSync(new URL("../src/features/browser/download-approval.tsx", import.meta.url), "utf8");+ // A file that runs code asks whatever was remembered (approveDownload), so its prompt has no checkbox.+ assert.match(source, /\{request\?\.origin && !request\.dangerous \? \(\s*<label/);+});++test("a finished download links to its history row, and an unrecorded one drops its forgotten native id", async () => {+ const { finishDownload, keptDownloadFile, mountDownloadsButton, useDownloadActivity } = await import(+ "../src/features/browser/download-activity.ts"+ );+ const file = { blob: new Blob(["x"]), name: "x".repeat(300), contentType: "text/plain" };+ const result = { name: file.name, size: 1, contentType: "text/plain", url: null, failed: false };+ const unmount = mountDownloadsButton();+ try {+ // A name past the history row's limit still links: the row's id comes from recordDownload.+ finishDownload("save:1", { ...result, nativeId: "n1", historyId: "row1" }, file);+ assert.equal(useDownloadActivity.getState().finished?.historyId, "row1");+ assert.equal(useDownloadActivity.getState().finished?.nativeId, "n1");+ assert.equal(keptDownloadFile("row1"), file);+ // History off: the app forgot the native id, so Open and Show in folder can't use it.+ finishDownload("save:2", { ...result, nativeId: "n2" });+ assert.equal(useDownloadActivity.getState().finished?.nativeId, undefined);+ } finally {+ useDownloadActivity.getState().dismissFinished();+ unmount();+ }+ // No button on screen: the caller toasts it, so nothing holds the result.+ finishDownload("save:3", result);+ assert.equal(useDownloadActivity.getState().finished, null);+});++test("a long download name keeps its extension, and a kept copy goes with its history row", async () => {+ const { finishDownload, keptDownloadFile } = await import("../src/features/browser/download-activity.ts");+ const { isDangerousDownload } = await import("../src/features/browser/download-safety.ts");+ const history = useBrowserHistoryStore.getState();+ history.clearDownloads();+ const id = history.recordDownload({ ...download, name: `${"a".repeat(210)}.exe` });+ const row = useBrowserHistoryStore.getState().downloads[0];+ assert.equal(row.name.length, 200);+ assert.ok(row.name.endsWith(".exe"));+ assert.ok(isDangerousDownload(row.name));+ const file = { blob: new Blob(["x"]), name: row.name, contentType: "" };+ finishDownload("save:row", { name: row.name, size: 1, contentType: "", url: null, historyId: id, failed: false }, file);+ assert.equal(keptDownloadFile(id), file);+ useBrowserHistoryStore.getState().removeDownload(id as string);+ assert.equal(keptDownloadFile(id), null);+});++test("an unrecorded result's bytes go with its notice, and one replaced on screen is toasted", async () => {+ const { finishDownload, keptDownloadFile, mountDownloadsButton, useDownloadActivity } = await import(+ "../src/features/browser/download-activity.ts"+ );+ const file = { blob: new Blob(["x"]), name: "a.bin", contentType: "" };+ const result = { name: "a.bin", size: 1, contentType: "", url: null, failed: false };+ // No button on screen: an unrecorded copy has no way back, so it isn't kept; a recorded one is.+ finishDownload("save:z", result, file);+ assert.equal(keptDownloadFile("save:z"), null);+ finishDownload("save:y", { ...result, historyId: "row-y" }, file);+ assert.equal(keptDownloadFile("row-y"), file);+ const unmount = mountDownloadsButton();+ const toasts = ((globalThis as { __toasts?: { message: string; options?: { description?: string } }[] }).__toasts ??=+ []);+ toasts.length = 0;+ try {+ finishDownload("save:a", result, file);+ assert.equal(keptDownloadFile("save:a"), file);+ useDownloadActivity.getState().dismissFinished();+ assert.equal(keptDownloadFile("save:a"), null);+ // A failure the list never shows, replaced before it was dismissed: toasted, not lost.+ finishDownload("native:p1", { ...result, name: "lost.zip", failed: true });+ finishDownload("save:b", result, file);+ assert.deepEqual(+ toasts.map((item) => [item.message, item.options?.description]),+ [["browser.downloads.failed", "lost.zip"]],+ );+ assert.equal(keptDownloadFile("save:b"), file);+ // A recorded result replaced on screen stays in the list, so no toast.+ finishDownload("save:c", { ...result, historyId: "row-c" });+ finishDownload("save:d", { ...result, historyId: "row-d" });+ assert.equal(toasts.length, 2);+ assert.equal(keptDownloadFile("save:b"), null);+ } finally {+ useDownloadActivity.getState().dismissFinished();+ unmount();+ }+});+test("video and audio tabs don't zoom; pages, images and documents do", async () => {const { canZoom } = await import("../src/features/browser/zoom.ts");const tab = (entry: object) =>@@ -558,3 +647,35 @@ test("video and audio tabs don't zoom; pages, images and documents do", async ()assert.equal(canZoom(tab({ name: "clip.mp4", plainText: true })), true);assert.equal(canZoom({ id: "t", index: 0, history: [{ kind: "web", url: "https://a.b/" }], zoom: 1 } as never), true);});++test("closing the last Downloads button dismisses its result, but a button swapped in keeps it", async () => {+ const { finishDownload, keptDownloadFile, mountDownloadsButton, useDownloadActivity } = await import(+ "../src/features/browser/download-activity.ts"+ );+ const file = { blob: new Blob(["x"]), name: "a.bin", contentType: "" };+ const result = { name: "a.bin", size: 1, contentType: "", url: null, failed: false };+ // A tab change: one button goes and another comes in the same commit.+ const first = mountDownloadsButton();+ finishDownload("save:swap", result, file);+ first();+ const second = mountDownloadsButton();+ await Promise.resolve();+ assert.equal(useDownloadActivity.getState().finished?.key, "save:swap");+ assert.equal(keptDownloadFile("save:swap"), file);+ // The panel closes: no button is back, so the unrecorded copy goes.+ second();+ await Promise.resolve();+ assert.equal(useDownloadActivity.getState().finished, null);+ assert.equal(keptDownloadFile("save:swap"), null);+});++test("file toolbars keep a Downloads button registered, and a hidden panel closes its popover", async () => {+ const { readFileSync } = await import("node:fs");+ const read = (file: string) => readFileSync(new URL(`../src/features/browser/${file}`, import.meta.url), "utf8");+ // Mounted only once a save began, it would register after a quick save had already finished.+ const panel = read("browser-panel.tsx");+ assert.equal(panel.match(/<DownloadsButton [^>]*visible=\{visible\} idleHidden=\{true\} \/>/g)?.length, 3);+ assert.doesNotMatch(panel, /BusyDownloadsButton/);+ // The popover is portaled out of the panel, so it would stay up over the next page.+ assert.match(read("downloads-button.tsx"), /if \(!visible && mode !== "closed"\) \{\s*setMode\("closed"\);/);+});diff --git a/studio/frontend/tests/helpers/native-view-resolver.mjs b/studio/frontend/tests/helpers/native-view-resolver.mjsindex 6c12218bc15..cad37035f5a 100644--- a/studio/frontend/tests/helpers/native-view-resolver.mjs+++ b/studio/frontend/tests/helpers/native-view-resolver.mjs@@ -25,9 +25,22 @@ const STUBS = {export const clearNativeBrowsingData = async () => {};`),"./favicon": stub("export const proxiedFavicon = async () => null;"),- "./native-downloads": stub("export const decideNativeDownload = async () => {};"),+ // globalThis.nativeViewDownloadsButton puts a Downloads button on screen; calls land in nativeViewActivity.+ "./download-activity": stub(`+ const buttons = () => (globalThis.nativeViewDownloadsButton ? 1 : 0);+ const active = {};+ const log = (call, key) => void (globalThis.nativeViewActivity ??= []).push(call + " " + key);+ export const useDownloadActivity = { getState: () => ({ buttons: buttons(), active: { ...active } }) };+ export const beginDownload = (key, name) => (log("begin", key), (active[key] = name));+ export const abandonDownload = (key) => (log("abandon", key), delete active[key]);+ export const finishDownload = (key) => (log("finish", key), delete active[key], buttons() > 0);+ `),+ // globalThis.nativeViewDecide runs inside the decide call, as the app's events can.+ "./native-downloads": stub(+ "export const decideNativeDownload = async (...args) => { globalThis.nativeViewDecide?.(...args); };",+ ),"./download-approval-queue": stub(- "export const approveDownload = async () => false; export const downloadSiteOf = () => '';",+ "export const approveDownload = async () => Boolean(globalThis.nativeViewApprove); export const downloadSiteOf = () => '';",),"./history-store": stub("export const useBrowserHistoryStore = { getState: () => ({ recordVisit() {}," +diff --git a/studio/src-tauri/src/browser_downloads.rs b/studio/src-tauri/src/browser_downloads.rsindex 4dfb1cb36d5..56ce1c3aca0 100644--- a/studio/src-tauri/src/browser_downloads.rs+++ b/studio/src-tauri/src/browser_downloads.rs@@ -238,6 +238,53 @@ pub fn browser_download_reveal(crate::native_intents::reveal_in_file_manager(&path)}+/// Extensions that run code when opened, shared with download-safety.ts.+fn runs_code(path: &Path) -> bool {+ static EXTENSIONS: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();+ let extensions = EXTENSIONS.get_or_init(|| {+ #[derive(Deserialize)]+ struct Policy {+ extensions: Vec<String>,+ }+ serde_json::from_str::<Policy>(include_str!(+ "../../frontend/src/features/browser/dangerous-file-types.json"+ ))+ .map(|policy| policy.extensions)+ .unwrap_or_default()+ });+ // Windows drops trailing dots and spaces, so `setup.exe.` still runs.+ let name = path+ .file_name()+ .map(|name| name.to_string_lossy())+ .unwrap_or_default();+ let name = name.trim_end_matches(['.', ' ']);+ name.rsplit_once('.').is_some_and(|(_, ext)| {+ // Windows compares names upper-cased, so `.m\u{17f}i` (long s) is `.MSI`.+ let folded = [ext.to_lowercase(), ext.to_uppercase().to_lowercase()];+ extensions.iter().any(|known| folded.contains(known))+ })+}++/// Open a download with its default app. Programs and scripts are refused: they stay a reveal away.+#[tauri::command]+pub fn browser_download_open(+ webview: tauri::Webview,+ app: AppHandle,+ state: State<'_, BrowserDownloads>,+ id: String,+) -> Result<(), String> {+ crate::native_intents::ensure_main_window(&webview)?;+ let path = with_entries(&app, &state, |entries| (path_of(entries, &id), false))+ .ok_or_else(|| "Unknown download.".to_string())?;+ if !path.is_file() {+ return Err("The file was moved or deleted.".to_string());+ }+ if runs_code(&path) {+ return Err("Programs and scripts open from their folder.".to_string());+ }+ tauri_plugin_opener::open_path(&path, None::<&str>).map_err(|error| error.to_string())+}+/// Whether each download is still where it was saved, in the order asked.#[tauri::command]pub fn browser_download_exists(@@ -550,6 +597,7 @@ fn settle<R: Runtime>(app: &AppHandle<R>, id: &str) {return;};let app = app.clone();+ let id = id.to_string();tauri::async_runtime::spawn(async move {let staging = entry.staged.parent().map(Path::to_path_buf);let result = match (entry.decision, entry.finished) {@@ -568,13 +616,23 @@ fn settle<R: Runtime>(app: &AppHandle<R>, id: &str) {&path,Some(download_id),marked,+ &id,),+ Ok(None) if matches!(entry.decision, Some(Decision::Allow { .. })) => {+ crate::browser_webview::emit_download_cancelled(+ &app,+ &entry.tab_id,+ &entry.url,+ &id,+ )+ }Ok(None) => {}Err(_) => crate::browser_webview::emit_download_failed(&app,&entry.tab_id,&entry.url,&entry.name,+ Some(&id),),}});@@ -692,6 +750,31 @@ fn copy_into_place(from: &Path, to: &Path) -> Result<(), String> {mod tests {use super::*;+ #[test]+ fn programs_and_scripts_are_not_opened() {+ for name in [+ "setup.exe",+ "Install.CMD",+ "run.sh",+ "tool.command",+ "x.jar",+ "Foo.app",+ "a.exe. ",+ "installer.m\u{17f}i",+ ] {+ assert!(runs_code(Path::new(name)), "{name}");+ }+ for name in [+ "report.pdf",+ "data.csv",+ "clip.mp4",+ "noext",+ ".exe-notes.txt",+ ] {+ assert!(!runs_code(Path::new(name)), "{name}");+ }+ }+#[test]fn ids_are_random_hex_and_checked() {let id = new_id();diff --git a/studio/src-tauri/src/browser_webview.rs b/studio/src-tauri/src/browser_webview.rsindex 19a547142c5..0e870fb601f 100644--- a/studio/src-tauri/src/browser_webview.rs+++ b/studio/src-tauri/src/browser_webview.rs@@ -241,6 +241,14 @@ enum BrowserEvent {download_id: Option<String>,/// Marked as from the internet: false if that failed (the panel warns), None where nothing marks.marked: Option<bool>,+ /// The DownloadPrompt `id` it was asked under; None when refused before asking.+ prompt_id: Option<String>,+ },+ /// An approved download that left no file (its save dialog was cancelled).+ DownloadCancelled {+ tab_id: String,+ url: String,+ prompt_id: String,},DownloadPrompt {tab_id: String,@@ -540,6 +548,7 @@ pub(crate) fn emit_download_done<R: Runtime>(path: &Path,download_id: Option<String>,marked: Option<bool>,+ prompt_id: &str,) {emit(app,@@ -556,6 +565,23 @@ pub(crate) fn emit_download_done<R: Runtime>(success: true,download_id,marked,+ prompt_id: Some(prompt_id.to_string()),+ },+ );+}++pub(crate) fn emit_download_cancelled<R: Runtime>(+ app: &AppHandle<R>,+ tab_id: &str,+ url: &Url,+ prompt_id: &str,+) {+ emit(+ app,+ BrowserEvent::DownloadCancelled {+ tab_id: tab_id.to_string(),+ url: url.to_string(),+ prompt_id: prompt_id.to_string(),},);}@@ -565,6 +591,7 @@ pub(crate) fn emit_download_failed<R: Runtime>(tab_id: &str,url: &Url,name: &str,+ prompt_id: Option<&str>,) {emit(app,@@ -578,6 +605,7 @@ pub(crate) fn emit_download_failed<R: Runtime>(success: false,download_id: None,marked: None,+ prompt_id: prompt_id.map(str::to_string),},);}@@ -1044,7 +1072,7 @@ fn create_view<R: Runtime>(.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default();- emit_download_failed(app, &download_tab, &url, &name);+ emit_download_failed(app, &download_tab, &url, &name, None);return false;}let Some((id, staging)) = crate::browser_downloads::staging_dir(app) else {@@ -1070,7 +1098,7 @@ fn create_view<R: Runtime>(.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default();- emit_download_failed(app, &download_tab, &url, &name);+ emit_download_failed(app, &download_tab, &url, &name, None);}return false;}diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rsindex 83859118abd..844d6d30620 100644--- a/studio/src-tauri/src/main.rs+++ b/studio/src-tauri/src/main.rs@@ -2258,6 +2258,7 @@ fn main() {browser_capture::browser_capture,browser_downloads::browser_download_save,browser_downloads::browser_download_reveal,+ browser_downloads::browser_download_open,browser_downloads::browser_download_exists,browser_downloads::browser_download_forget,browser_downloads::browser_download_decide,