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: add a Download to folder for model downloads (#13557)
Daniel Han280c4569552a
diff --git a/studio/backend/hub/schemas/downloads.py b/studio/backend/hub/schemas/downloads.pyindex bf73ed444d1..5d0b7feb4cd 100644--- a/studio/backend/hub/schemas/downloads.py+++ b/studio/backend/hub/schemas/downloads.py@@ -45,6 +45,13 @@ class DownloadModelRequest(BaseModel):default_factory = list,description = "Exact files to fetch. Required with scope_id, ignored without it.",)+ download_dir: Optional[str] = Field(+ None,+ max_length = 4096,+ description = "Folder to download into instead of the Models folder. It is used like a "+ "Models folder (files land under its hub/ subfolder) and is added to Custom Folders. "+ "Omitted -> the Models folder.",+ )class CancelDownloadRequest(BaseModel):diff --git a/studio/backend/hub/services/models/downloads.py b/studio/backend/hub/services/models/downloads.pyindex 6ac72ebc3d1..1e756f1df7b 100644--- a/studio/backend/hub/services/models/downloads.py+++ b/studio/backend/hub/services/models/downloads.py@@ -186,6 +186,35 @@ def _spawn_download_worker()+def _download_cache_paths(download_dir: Optional[str]):+ """The Models folder, or the chosen Download to folder registered as a known cache and a Custom Folder."""+ from utils.hf_cache_settings import (+ download_cache_paths,+ get_hf_cache_paths,+ remember_cache_home,+ )++ if not (download_dir or "").strip():+ return get_hf_cache_paths()+ if account_access.managed_account():+ raise HTTPException(status_code = 403, detail = "Only the owner can choose a download folder.")+ try:+ paths = download_cache_paths(download_dir)+ except ValueError as e:+ raise HTTPException(status_code = 400, detail = str(e)) from e+ if paths.cache_home == get_hf_cache_paths().cache_home:+ return paths+ remember_cache_home(paths.cache_home)+ from hub.services.models.local_inventory import add_scan_folder_response++ try:+ add_scan_folder_response(str(paths.cache_home))+ except HTTPException as e:+ # Still listed through the known caches; Custom Folders only makes it visible there.+ logger.warning("Download folder not added to Custom Folders: %s", e.detail)+ return paths++async def _audio_cpp_target(repo_id: str,variant: Optional[str],@@ -291,9 +320,9 @@ async def download_model_response()transport = download_lifecycle.resolve_transport(use_xet, largest_file_bytes = largest_file_bytes)logger.info("Download transport for %s: %s (%s)", repo_id, transport, transport_reason)- from utils.hf_cache_settings import get_hf_cache_paths-- cache_paths = get_hf_cache_paths()+ cache_paths = await asyncio.to_thread(+ _download_cache_paths, getattr(body, "download_dir", None)+ )cache_env = cache_paths.child_env({})variant_blob_hashes = frozenset()variant_progress_blob_hashes = frozenset()@@ -331,8 +360,13 @@ async def download_model_response(download_registry.scrub_secrets(str(e), hf_token = hf_token),)has_variant_resume_state = (- download_manifest.has_cancel_marker("model", repo_id, variant)- or download_manifest.read_manifest("model", repo_id, variant) is not None+ download_manifest.has_cancel_marker(+ "model", repo_id, variant, hub_cache = cache_paths.hub_cache+ )+ or download_manifest.read_manifest(+ "model", repo_id, variant, hub_cache = cache_paths.hub_cache+ )+ is not None)if variant_progress_blob_hashes and not has_variant_resume_state:completed_baseline_bytes = await asyncio.to_thread(@@ -340,6 +374,7 @@ async def download_model_response("model",repo_id,variant_progress_blob_hashes,+ root = cache_paths.hub_cache,)def claim_and_launch():diff --git a/studio/backend/hub/tests/test_download_to_folder.py b/studio/backend/hub/tests/test_download_to_folder.pynew file mode 100644index 00000000000..42855eb033c--- /dev/null+++ b/studio/backend/hub/tests/test_download_to_folder.py@@ -0,0 +1,203 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Download to: a model download aimed at a chosen folder instead of the Models folder (#10872)."""++from __future__ import annotations++import asyncio+from types import SimpleNamespace++import pytest+from fastapi import HTTPException++from hub.services.models import downloads+from hub.services.models import local_inventory+from utils import hf_cache_settings+++def settings_store(monkeypatch, tmp_path):+ store = {}+ monkeypatch.setattr(hf_cache_settings, "_EXPLICIT_CACHE_ENV", {})+ monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path / "xdg"))+ # macOS tmp_path sits under /private/var, which the system-folder guard refuses.+ monkeypatch.setattr("hub.storage.scan_folders.is_denied_system_path", lambda _path: False)+ monkeypatch.setattr(+ "storage.studio_db.get_app_setting",+ lambda key, fallback = None: store.get(key, fallback),+ )+ monkeypatch.setattr(+ "storage.studio_db.upsert_app_settings",+ lambda values: store.update(values) or values,+ )+ return store+++def test_no_download_dir_is_the_models_folder(settings_store):+ active = hf_cache_settings.get_hf_cache_paths()+ assert hf_cache_settings.download_cache_paths(None) == active+ assert hf_cache_settings.download_cache_paths(" ") == active+++def test_download_dir_is_laid_out_like_a_models_folder(settings_store, tmp_path):+ target = tmp_path / "drive-e" / "models"+ target.parent.mkdir()++ paths = hf_cache_settings.download_cache_paths(str(target))++ assert paths.cache_home == target.resolve()+ assert paths.hub_cache == target.resolve() / "hub"+ assert paths.xet_cache == target.resolve() / "xet"+ assert (target / "hub").is_dir()+ assert hf_cache_settings.get_hf_cache_paths().source == "default"+++def test_download_dir_equal_to_models_folder_is_the_default(settings_store, tmp_path):+ models = tmp_path / "models"+ models.mkdir()+ hf_cache_settings.set_hf_cache_home(str(models))++ assert hf_cache_settings.download_cache_paths(str(models)) == (+ hf_cache_settings.get_hf_cache_paths()+ )+++def test_download_dir_is_validated_like_the_models_folder(settings_store, tmp_path):+ with pytest.raises(ValueError, match = "absolute"):+ hf_cache_settings.download_cache_paths("relative/models")+ with pytest.raises(ValueError, match = "parent folder"):+ hf_cache_settings.download_cache_paths(str(tmp_path / "missing" / "models"))+++def test_remember_cache_home_is_idempotent_and_scanned(settings_store, tmp_path):+ target = tmp_path / "drive-d"+ target.mkdir()++ hf_cache_settings.remember_cache_home(target)+ hf_cache_settings.remember_cache_home(target)++ assert settings_store[hf_cache_settings.DOWNLOAD_HOMES_SETTING_KEY] == [str(target.resolve())]+ assert target.resolve() / "hub" in hf_cache_settings.known_hf_hub_caches()+++def test_download_folder_is_known_even_with_a_full_models_folder_history(settings_store, tmp_path):+ full = [str(tmp_path / f"old-{i}") for i in range(hf_cache_settings.MAX_CACHE_HISTORY)]+ settings_store[hf_cache_settings.CACHE_HISTORY_SETTING_KEY] = list(full)+ target = tmp_path / "new"+ target.mkdir()++ hf_cache_settings.remember_cache_home(target)++ assert settings_store[hf_cache_settings.CACHE_HISTORY_SETTING_KEY] == full+ assert target.resolve() / "hub" in hf_cache_settings.known_hf_hub_caches()+++def _start(monkeypatch, body):+ calls = {"claim": [], "spawn": [], "scan_folders": []}++ class _Registry:+ def claim(self, key, transport, **kwargs):+ calls["claim"].append(kwargs)+ return True, "running"++ def current_generation(self, _key):+ return 1++ def peer_blob_hashes(self, _key):+ return frozenset()++ def get_job_metadata(self, _key):+ return None++ monkeypatch.setattr(downloads, "_registry", _Registry())+ monkeypatch.setattr(downloads, "resolve_cached_repo_id_case", lambda repo_id, **_k: repo_id)+ monkeypatch.setattr(downloads, "_load_in_flight", lambda _repo_id: False)+ monkeypatch.setattr(+ downloads.download_lifecycle, "largest_download_file_bytes", lambda *a, **k: None+ )+ monkeypatch.setattr(+ downloads.download_lifecycle,+ "resolve_requested_use_xet",+ lambda *a, **k: (False, "test"),+ )+ for name in ("record_download_account", "require_live_account"):+ monkeypatch.setattr(downloads.download_lifecycle, name, lambda *a, **k: None)++ def _launch(_registry, _key, *, spawn, **_kwargs):+ spawn()+ return "running"++ monkeypatch.setattr(downloads.download_lifecycle, "launch_worker", _launch)+ monkeypatch.setattr(+ downloads,+ "_spawn_download_worker",+ lambda *a, **kwargs: calls["spawn"].append(kwargs["cache_env"]),+ )+ monkeypatch.setattr(+ local_inventory,+ "add_scan_folder_response",+ lambda path, recursive = None: calls["scan_folders"].append(path) or {"path": path},+ )+ result = asyncio.run(downloads.download_model_response(body))+ return result, calls+++def _body(**over):+ body = {+ "repo_id": "Org/Model",+ "gguf_variant": None,+ "use_xet": False,+ "scope_id": None,+ "files": None,+ "download_dir": None,+ }+ body.update(over)+ return SimpleNamespace(**body)+++def test_download_without_download_dir_keeps_the_models_folder(settings_store, monkeypatch):+ active = hf_cache_settings.get_hf_cache_paths()++ result, calls = _start(monkeypatch, _body())++ assert result["accepted"] is True+ assert calls["claim"][0]["hub_cache"] == str(active.hub_cache)+ assert calls["spawn"][0]["HF_HUB_CACHE"] == str(active.hub_cache)+ assert calls["scan_folders"] == []+ assert hf_cache_settings.DOWNLOAD_HOMES_SETTING_KEY not in settings_store+++def test_download_to_folder_routes_worker_and_registers_folder(+ settings_store, monkeypatch, tmp_path+):+ target = tmp_path / "drive-e"+ target.mkdir()+ hub = target.resolve() / "hub"++ for _ in range(2):+ result, calls = _start(monkeypatch, _body(download_dir = str(target)))+ assert result["accepted"] is True+ assert calls["claim"][0]["hub_cache"] == str(hub)+ assert calls["claim"][0]["xet_cache"] == str(target.resolve() / "xet")+ assert calls["spawn"][0]["HF_HUB_CACHE"] == str(hub)+ assert calls["scan_folders"] == [str(target.resolve())]++ assert settings_store[hf_cache_settings.DOWNLOAD_HOMES_SETTING_KEY] == [str(target.resolve())]+ assert hub in hf_cache_settings.known_hf_hub_caches()+ assert hf_cache_settings.get_hf_cache_paths().source == "default"+++def test_bad_download_dir_is_a_400_and_starts_nothing(settings_store, monkeypatch, tmp_path):+ with pytest.raises(HTTPException) as exc:+ _start(monkeypatch, _body(download_dir = str(tmp_path / "missing" / "models")))+ assert exc.value.status_code == 400+++def test_managed_account_cannot_choose_a_download_folder(settings_store, monkeypatch, tmp_path):+ monkeypatch.setattr(downloads.account_access, "managed_account", lambda: True)+ monkeypatch.setattr(downloads.account_access, "account_hf_token", lambda token: token)+ monkeypatch.setattr(downloads.account_access, "authorize_download", lambda *a, **k: None)+ with pytest.raises(HTTPException) as exc:+ downloads._download_cache_paths(str(tmp_path))+ assert exc.value.status_code == 403diff --git a/studio/backend/utils/hf_cache_settings.py b/studio/backend/utils/hf_cache_settings.pyindex 1a8b953642f..cadcf6599ea 100644--- a/studio/backend/utils/hf_cache_settings.py+++ b/studio/backend/utils/hf_cache_settings.py@@ -25,6 +25,9 @@ from typing import Iterator, Literal, Mapping, OptionalCACHE_HOME_SETTING_KEY = "hugging_face_cache_home"CACHE_HISTORY_SETTING_KEY = "hugging_face_cache_history"MAX_CACHE_HISTORY = 16+# Download to folders, kept apart from the Models folder history so neither list evicts the other.+DOWNLOAD_HOMES_SETTING_KEY = "hugging_face_download_homes"+MAX_DOWNLOAD_HOMES = 64CacheSource = Literal["default", "studio", "environment"]@@ -354,10 +357,18 @@ def _validate_cache_home(raw_path: str) -> Path:def _stored_history() -> list[Path]:+ return _stored_paths(CACHE_HISTORY_SETTING_KEY, MAX_CACHE_HISTORY)+++def _stored_download_homes() -> list[Path]:+ return _stored_paths(DOWNLOAD_HOMES_SETTING_KEY, MAX_DOWNLOAD_HOMES)+++def _stored_paths(setting_key: str, limit: int) -> list[Path]:try:from storage.studio_db import get_app_settingfrom utils.account_context import OWNER, run_as- raw = run_as(OWNER, get_app_setting, CACHE_HISTORY_SETTING_KEY, [])+ raw = run_as(OWNER, get_app_setting, setting_key, [])except Exception:raw = []if not isinstance(raw, list):@@ -376,7 +387,7 @@ def _stored_history() -> list[Path]:continueseen.add(key)out.append(path)- return out[:MAX_CACHE_HISTORY]+ return out[:limit]def set_hf_cache_home(cache_home: Optional[str]) -> HuggingFaceCachePaths:@@ -406,6 +417,55 @@ def set_hf_cache_home(cache_home: Optional[str]) -> HuggingFaceCachePaths:CACHE_HISTORY_SETTING_KEY: deduped,})+ _invalidate_cache_views()+ return get_hf_cache_paths()+++def download_cache_paths(download_dir: Optional[str]) -> HuggingFaceCachePaths:+ """Cache paths for one download: the Models folder, or a chosen folder laid out the same way.++ Raises ValueError for a folder the Models folder setting would also refuse.+ """+ active = get_hf_cache_paths()+ if download_dir is None or not download_dir.strip():+ return active+ home = _validate_cache_home(download_dir)+ if os.path.normcase(str(home)) == os.path.normcase(str(_canonical(active.cache_home))):+ return active+ xet = _EXPLICIT_CACHE_ENV.get("HF_XET_CACHE")+ return HuggingFaceCachePaths(+ home,+ home / "hub",+ _canonical(xet) if xet else home / "xet",+ "studio",+ )+++def remember_cache_home(cache_home: Path) -> None:+ """Keep a download folder among the known caches, like a previous Models folder.++ Progress, resume, delete and the cached-model checks read only known caches. Idempotent.+ """+ home = _canonical(cache_home)+ key = os.path.normcase(str(home))+ with _settings_lock:+ homes = _stored_download_homes()+ if len(homes) >= MAX_DOWNLOAD_HOMES or any(+ os.path.normcase(str(path)) == key for path in homes+ ):+ return+ from storage.studio_db import upsert_app_settings+ from utils.account_context import OWNER, run_as++ run_as(+ OWNER,+ upsert_app_settings,+ {DOWNLOAD_HOMES_SETTING_KEY: [*(str(path) for path in homes), str(home)]},+ )+ _invalidate_cache_views()+++def _invalidate_cache_views() -> None:# Inventory scans are cached independently from settings. Invalidate after# persistence so the next request sees both the new active root and history.from hub.utils.inventory_scan import invalidate_hf_cache_scans@@ -420,7 +480,6 @@ def set_hf_cache_home(cache_home: Optional[str]) -> HuggingFaceCachePaths:from utils.cache_inventory import invalidate_hf_rooted_sizesinvalidate_hf_rooted_sizes()- return get_hf_cache_paths()def effective_cache_home() -> Path:@@ -448,7 +507,7 @@ def known_hf_cache_homes() -> list[Path]:candidates.append(_canonical(explicit_home))if stored is not None:candidates.append(stored)- candidates.extend([*_stored_history(), _default_cache_home()])+ candidates.extend([*_stored_history(), *_stored_download_homes(), _default_cache_home()])out: list[Path] = []seen: set[str] = set()for candidate in candidates:diff --git a/studio/frontend/src/features/hub/catalog/download-location-picker.tsx b/studio/frontend/src/features/hub/catalog/download-location-picker.tsxnew file mode 100644index 00000000000..8091e27e26c--- /dev/null+++ b/studio/frontend/src/features/hub/catalog/download-location-picker.tsx@@ -0,0 +1,131 @@+// 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,+ DropdownMenuLabel,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { useIsAccountOwner } from "@/features/auth";+import { FolderBrowser } from "@/features/model-picker";+import { pickHuggingFaceCacheDir } from "@/features/native-intents";+import { isTauri } from "@/lib/api-base";+import { toast } from "@/lib/toast";+import { Folder02Icon } from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import { useState } from "react";+import { setDownloadDir, useDownloadDir } from "../download-manager";+import { type ScanFolderInfo, listScanFolders } from "../inventory/api";++const MODELS_FOLDER = "";+const PATH_SEPARATORS = /[\\/]+/;++function folderName(path: string): string {+ const parts = path.split(PATH_SEPARATORS).filter(Boolean);+ return parts[parts.length - 1] ?? path;+}++export function DownloadLocationPicker() {+ const isOwner = useIsAccountOwner();+ const dir = useDownloadDir();+ const [folders, setFolders] = useState<ScanFolderInfo[]>([]);+ const [browserOpen, setBrowserOpen] = useState(false);++ if (!isOwner) {+ return null;+ }++ const choose = async () => {+ if (!isTauri) {+ setBrowserOpen(true);+ return;+ }+ try {+ const path = await pickHuggingFaceCacheDir();+ if (path) {+ setDownloadDir(path);+ }+ } catch (error) {+ toast.error("Couldn't open the folder picker.", {+ description: error instanceof Error ? error.message : undefined,+ });+ }+ };++ const options = folders.map((f) => f.path);+ if (dir && !options.includes(dir)) {+ options.unshift(dir);+ }+ const label = dir ? folderName(dir) : null;++ return (+ <>+ <DropdownMenu+ onOpenChange={(open) => {+ if (open) {+ listScanFolders()+ .then(setFolders)+ .catch(() => undefined);+ }+ }}+ >+ <DropdownMenuTrigger asChild={true}>+ <button+ type="button"+ aria-label={`Download to: ${dir ?? "Models folder"}`}+ title={`Download to: ${dir ?? "Models folder"}`}+ className="hub-tag-soft inline-flex h-[calc(26px*var(--ui-space-scale,1))] max-w-[calc(160px*var(--ui-space-scale,1))] min-w-0 cursor-pointer items-center gap-1 rounded-full border-0 px-2 text-ui-11 font-medium text-muted-foreground transition-colors hover:text-foreground"+ >+ <HugeiconsIcon+ icon={Folder02Icon}+ strokeWidth={1.75}+ className="size-3.5 shrink-0"+ />+ {dir ? <span className="truncate">{label}</span> : null}+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="end"+ className="max-w-[calc(360px*var(--ui-space-scale,1))]"+ >+ <DropdownMenuLabel>Download to</DropdownMenuLabel>+ <DropdownMenuRadioGroup+ value={dir ?? MODELS_FOLDER}+ onValueChange={(value) => setDownloadDir(value || null)}+ >+ <DropdownMenuRadioItem value={MODELS_FOLDER}>+ Models folder+ </DropdownMenuRadioItem>+ {options.map((path) => (+ <DropdownMenuRadioItem key={path} value={path} title={path}>+ <span className="truncate font-mono text-xs">{path}</span>+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onSelect={() => {+ choose().catch(() => undefined);+ }}+ >+ Choose folder...+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ <FolderBrowser+ open={!isTauri && browserOpen}+ onOpenChange={setBrowserOpen}+ onSelect={(path) => setDownloadDir(path)}+ initialPath={dir ?? undefined}+ title="Choose download folder"+ confirmLabel="Download here"+ showModelHints={false}+ />+ </>+ );+}diff --git a/studio/frontend/src/features/hub/catalog/models-header.tsx b/studio/frontend/src/features/hub/catalog/models-header.tsxindex 384160e3f24..a3b10868f6a 100644--- a/studio/frontend/src/features/hub/catalog/models-header.tsx+++ b/studio/frontend/src/features/hub/catalog/models-header.tsx@@ -13,6 +13,7 @@ import type { IconSvgElement } from "@hugeicons/react";import { HugeiconsIcon } from "@hugeicons/react";import { HfTokenIndicator } from "../components/hf-token-indicator";import { PageHeading } from "../components/page-heading";+import { DownloadLocationPicker } from "./download-location-picker";import { TransportToggle } from "./transport-toggle";function StatPill({@@ -74,6 +75,7 @@ export function ModelsHeader({><HfTokenIndicator onOpenSettings={() => openSettings("general")} /><TransportToggle />+ {isDataset ? null : <DownloadLocationPicker />}<StatPillicon={PackageIcon}label="Cache"diff --git a/studio/frontend/src/features/hub/download-manager/api.ts b/studio/frontend/src/features/hub/download-manager/api.tsindex 2576dbe6a92..4b27104eb82 100644--- a/studio/frontend/src/features/hub/download-manager/api.ts+++ b/studio/frontend/src/features/hub/download-manager/api.ts@@ -226,6 +226,7 @@ export async function startModelDownload(payload: {scope_id?: string | null;files?: string[];transport_mode?: "auto" | "xet" | "http";+ download_dir?: string;}): Promise<DownloadStartResult & { job_key: string }> {const { hf_token, ...body } = payload;const headers = {diff --git a/studio/frontend/src/features/hub/download-manager/download-api-adapter.ts b/studio/frontend/src/features/hub/download-manager/download-api-adapter.tsindex 9947c5e7fe2..4514142a88b 100644--- a/studio/frontend/src/features/hub/download-manager/download-api-adapter.ts+++ b/studio/frontend/src/features/hub/download-manager/download-api-adapter.ts@@ -35,6 +35,7 @@ import type {ManagedDownload,ProgressLike,} from "./download-manager-types";+import { downloadDirForRequest } from "./download-location";import {type PollSignal,disposableTimeoutSignal,@@ -114,6 +115,7 @@ export function apiStart(hf_token: hfToken,use_xet: useXet,transport_mode,+ download_dir: downloadDirForRequest(req.downloadDir),});}diff --git a/studio/frontend/src/features/hub/download-manager/download-location.ts b/studio/frontend/src/features/hub/download-manager/download-location.tsnew file mode 100644index 00000000000..8edb14c5634--- /dev/null+++ b/studio/frontend/src/features/hub/download-manager/download-location.ts@@ -0,0 +1,65 @@+// 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 { isAccountOwner } from "@/features/auth";+import { useEffect, useState } from "react";++/** Folder new model downloads go to. Absent means the Models folder. */+export const DOWNLOAD_DIR_STORAGE_KEY = "unsloth.studio.downloadDir";+const CHANGE_EVENT = "unsloth:download-dir-change";++export function getDownloadDir(): string | null {+ if (typeof window === "undefined") {+ return null;+ }+ try {+ const raw = window.localStorage.getItem(DOWNLOAD_DIR_STORAGE_KEY);+ return raw?.trim() ? raw : null;+ } catch {+ return null;+ }+}++/** What a model download sends: the folder pinned on the request, else the current choice. Only+ * the owner may pick a folder, and this browser may hold an owner's choice while another account+ * is signed in. */+export function downloadDirForRequest(+ pinned?: string | null,+): string | undefined {+ if (!isAccountOwner()) {+ return undefined;+ }+ return (pinned === undefined ? getDownloadDir() : pinned) ?? undefined;+}++export function setDownloadDir(path: string | null): void {+ try {+ if (path?.trim()) {+ window.localStorage.setItem(DOWNLOAD_DIR_STORAGE_KEY, path);+ } else {+ window.localStorage.removeItem(DOWNLOAD_DIR_STORAGE_KEY);+ }+ } catch {+ return;+ }+ window.dispatchEvent(new Event(CHANGE_EVENT));+}++export function useDownloadDir(): string | null {+ const [dir, setDir] = useState<string | null>(getDownloadDir);+ useEffect(() => {+ const sync = () => setDir(getDownloadDir());+ const handleStorage = (event: StorageEvent) => {+ if (event.key === null || event.key === DOWNLOAD_DIR_STORAGE_KEY) {+ sync();+ }+ };+ window.addEventListener(CHANGE_EVENT, sync);+ window.addEventListener("storage", handleStorage);+ return () => {+ window.removeEventListener(CHANGE_EVENT, sync);+ window.removeEventListener("storage", handleStorage);+ };+ }, []);+ return dir;+}diff --git a/studio/frontend/src/features/hub/download-manager/download-manager-state.ts b/studio/frontend/src/features/hub/download-manager/download-manager-state.tsindex fe933f3220e..29806cd6f11 100644--- a/studio/frontend/src/features/hub/download-manager/download-manager-state.ts+++ b/studio/frontend/src/features/hub/download-manager/download-manager-state.ts@@ -168,6 +168,9 @@ function sanitizePersistedJob(...(isResolvedTransport(value.cancelTransport)? { cancelTransport: value.cancelTransport }: {}),+ ...(typeof value.downloadDir === "string" || value.downloadDir === null+ ? { downloadDir: value.downloadDir }+ : {}),};}@@ -226,6 +229,7 @@ function toPersistedJob(...(job.cancelTransport !== undefined? { cancelTransport: job.cancelTransport }: {}),+ ...(job.downloadDir !== undefined ? { downloadDir: job.downloadDir } : {}),};}diff --git a/studio/frontend/src/features/hub/download-manager/download-manager-types.ts b/studio/frontend/src/features/hub/download-manager/download-manager-types.tsindex d44564cb5e5..ee01d319dc9 100644--- a/studio/frontend/src/features/hub/download-manager/download-manager-types.ts+++ b/studio/frontend/src/features/hub/download-manager/download-manager-types.ts@@ -44,6 +44,8 @@ export interface ManagedDownload {external?: boolean;activity?: string;details?: string[];+ /** Folder this job downloads into; null means the Models folder. */+ downloadDir?: string | null;}export interface DownloadRequest {@@ -59,6 +61,8 @@ export interface DownloadRequest {callerToast?: CallerToast;/** Skip repeat Xet notices for later entries in a staged plan. */skipXetNotice?: boolean;+ /** Download to folder captured when the start was requested; null means the Models folder. */+ downloadDir?: string | null;}export interface DownloadPresentation {diff --git a/studio/frontend/src/features/hub/download-manager/index.ts b/studio/frontend/src/features/hub/download-manager/index.tsindex 9319046eb5f..96ce6ef886e 100644--- a/studio/frontend/src/features/hub/download-manager/index.ts+++ b/studio/frontend/src/features/hub/download-manager/index.ts@@ -71,4 +71,9 @@ export {useHttpPartialsResumable,useTransportMode,} from "./transport-preference";+export {+ DOWNLOAD_DIR_STORAGE_KEY,+ setDownloadDir,+ useDownloadDir,+} from "./download-location";export type { TransportConflictInfo } from "./types";diff --git a/studio/frontend/src/features/hub/download-manager/poll-loop.ts b/studio/frontend/src/features/hub/download-manager/poll-loop.tsindex 54c348fe6dc..5fe2ea97286 100644--- a/studio/frontend/src/features/hub/download-manager/poll-loop.ts+++ b/studio/frontend/src/features/hub/download-manager/poll-loop.ts@@ -794,6 +794,11 @@ export async function startJob(: opts.adopt && existing?.checkpoint !== undefined? { checkpoint: existing.checkpoint }: {}),+ ...(req.downloadDir !== undefined+ ? { downloadDir: req.downloadDir }+ : opts.adopt && existing?.downloadDir !== undefined+ ? { downloadDir: existing.downloadDir }+ : {}),...(inventoryKind !== undefined? { inventoryKind }: opts.adopt && existing?.inventoryKind !== undefineddiff --git a/studio/frontend/src/features/hub/download-manager/transport-conflict.ts b/studio/frontend/src/features/hub/download-manager/transport-conflict.tsindex 600f57724cf..1164576bb62 100644--- a/studio/frontend/src/features/hub/download-manager/transport-conflict.ts+++ b/studio/frontend/src/features/hub/download-manager/transport-conflict.ts@@ -6,6 +6,7 @@ import { toast } from "@/lib/toast";import { disposableTimeoutSignal } from "../lib/abort-signals";import { getActiveModelDownloads } from "./api";import {+ DOWNLOAD_KIND,mismatchStartAction,TRANSPORT,type ResolvedTransport,@@ -27,6 +28,7 @@ import {repoKeyOf,setConflict,} from "./download-manager-state";+import { downloadDirForRequest } from "./download-location";import { startJob } from "./poll-loop";import {currentRoute,@@ -156,9 +158,26 @@ async function runWithPendingStartGuard(}}+/** Pin the destination before the preflight awaits, and resume a stopped job where it started. */+export function withDownloadDir(req: DownloadRequest): DownloadRequest {+ if (req.kind !== DOWNLOAD_KIND.MODEL || req.downloadDir !== undefined) {+ return req;+ }+ const previous = getState().jobs[jobKeyOf(req.kind, req.repoId, req.variant)];+ // Only a cancel leaves a partial worth resuming; a failed start may have been the folder itself.+ return {+ ...req,+ downloadDir:+ previous?.state === "cancelled" && previous.downloadDir !== undefined+ ? previous.downloadDir+ : (downloadDirForRequest() ?? null),+ };+}+export async function requestStart(- req: DownloadRequest,+ request: DownloadRequest,): Promise<DownloadStartOutcome> {+ const req = withDownloadDir(request);// Before the preflight below, which is two round trips the user can navigate// during; read after them it would name the page they moved to.const originRoute = currentRoute();diff --git a/studio/frontend/src/features/hub/download-manager/use-staged-download.ts b/studio/frontend/src/features/hub/download-manager/use-staged-download.tsindex 6e65cb6ac61..176474c61c3 100644--- a/studio/frontend/src/features/hub/download-manager/use-staged-download.ts+++ b/studio/frontend/src/features/hub/download-manager/use-staged-download.ts@@ -6,6 +6,7 @@ import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react"import { toast } from "@/lib/toast";import { DOWNLOAD_KIND } from "./constants";+import { downloadDirForRequest } from "./download-location";import { downloadManager } from "./download-manager-controller";import {scopedDownloadInventoryKind,@@ -30,6 +31,8 @@ export interface StagedDownloadEntry {/** A GGUF quant fetched as the standard variant download, as Chat does: the backend's variant* plan brings its companion files, and the row reads "<repo> · <quant>". `files` is unused. */ggufVariant?: string | null;+ /** Download to folder pinned when the plan was staged, so one model never spans two folders. */+ downloadDir?: string | null;}function entryKey(entry: StagedDownloadEntry): string {@@ -133,6 +136,7 @@ export function useStagedDownload({variant: current.ggufVariant,expectedBytes: current.bytes,skipXetNotice: laterEntry,+ downloadDir: current.downloadDir,}: {kind: DOWNLOAD_KIND.MODEL,@@ -144,6 +148,7 @@ export function useStagedDownload({files: current.files,checkpoint: current.checkpoint,skipXetNotice: laterEntry,+ downloadDir: current.downloadDir,},);if (!active) return;@@ -176,7 +181,12 @@ export function useStagedDownload({const stage = useCallback((entries: StagedDownloadEntry[]): number => {generation.current += 1;inFlight.current = null;- setQueue(entries.length > 0 ? entries : null);+ const downloadDir = downloadDirForRequest() ?? null;+ setQueue(+ entries.length > 0+ ? entries.map((entry) => ({ downloadDir, ...entry }))+ : null,+ );setStaged({bytes: entries.reduce((sum, entry) => sum + Math.max(0, entry.bytes), 0),plan: generation.current,diff --git a/studio/frontend/src/features/hub/index.ts b/studio/frontend/src/features/hub/index.tsindex 06b64df215c..ee20438f27e 100644--- a/studio/frontend/src/features/hub/index.ts+++ b/studio/frontend/src/features/hub/index.ts@@ -15,6 +15,7 @@ export {type TransportMode,updateExternalJob,TRANSPORT_MODE_STORAGE_KEY,+ DOWNLOAD_DIR_STORAGE_KEY,useDownloadManagerStore,useHttpPartialsResumable,useRepoDownload,diff --git a/studio/frontend/src/features/settings/tabs/general-tab.tsx b/studio/frontend/src/features/settings/tabs/general-tab.tsxindex 38b0ae2cb3c..5e0b152f140 100644--- a/studio/frontend/src/features/settings/tabs/general-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/general-tab.tsx@@ -74,7 +74,10 @@ import {} from "../components/desktop-update-control";import { DocumentsRagSection } from "../components/documents-rag-section";import { LanguageSelect } from "../components/language-select";-import { TRANSPORT_MODE_STORAGE_KEY } from "@/features/hub";+import {+ DOWNLOAD_DIR_STORAGE_KEY,+ TRANSPORT_MODE_STORAGE_KEY,+} from "@/features/hub";import { DownloadTransportRow } from "../components/download-transport-row";import { HubSettingsSection } from "../components/hub-settings-section";import { NotificationFrequencySelect } from "../components/notification-frequency-select";@@ -116,6 +119,7 @@ const PREFS_KEYS: string[] = [// Outranks the install-wide setting, so a reset that left it behind would keep ignoring// transport changes made elsewhere.TRANSPORT_MODE_STORAGE_KEY,+ DOWNLOAD_DIR_STORAGE_KEY,// Chat runtime prefsCHAT_PROJECT_ATTACHMENT_TARGET_KEY,"unsloth_chat_auto_title",diff --git a/studio/frontend/tests/download-location.test.ts b/studio/frontend/tests/download-location.test.tsnew file mode 100644index 00000000000..95dca286d4b--- /dev/null+++ b/studio/frontend/tests/download-location.test.ts@@ -0,0 +1,105 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Download to (#10872): a model download carries the chosen folder, and nothing when none is chosen.++import assert from "node:assert/strict";+import test, { after } from "node:test";+import { register } from "node:module";+import { installLocalStorageFake } from "./helpers/kit.ts";++register("./helpers/download-lifecycle-resolver.mjs", import.meta.url);++const { storage } = installLocalStorageFake();+const originalFetch = globalThis.fetch;+after(() => {+ globalThis.fetch = originalFetch;+});++const bodies: Record<string, unknown>[] = [];+globalThis.fetch = (async (_input: string, init?: RequestInit) => {+ bodies.push(JSON.parse(String(init?.body)));+ return new Response(JSON.stringify({ job_key: "k", state: "running" }), {+ status: 202,+ headers: { "Content-Type": "application/json" },+ });+}) as typeof fetch;++const { apiStart } =+ await import("../src/features/hub/download-manager/download-api-adapter.ts");+const { DOWNLOAD_DIR_STORAGE_KEY } =+ await import("../src/features/hub/download-manager/download-location.ts");++const model = {+ kind: "model" as const,+ repoId: "Org/Model-GGUF",+ variant: "Q4_K_M",+ expectedBytes: 0,+};++test("no folder chosen sends the same body as before", async () => {+ storage.removeItem(DOWNLOAD_DIR_STORAGE_KEY);+ bodies.length = 0;+ await apiStart(model, false, null);+ assert.equal(bodies.length, 1);+ assert.equal("download_dir" in bodies[0], false);+});++test("a chosen folder rides on the model download", async () => {+ storage.setItem(DOWNLOAD_DIR_STORAGE_KEY, "/mnt/e/AI/Models");+ bodies.length = 0;+ await apiStart(model, false, null);+ assert.equal(bodies[0].download_dir, "/mnt/e/AI/Models");+});++test("datasets never carry the folder", async () => {+ storage.setItem(DOWNLOAD_DIR_STORAGE_KEY, "/mnt/e/AI/Models");+ bodies.length = 0;+ await apiStart(+ { ...model, kind: "dataset" as const, variant: null },+ false,+ null,+ );+ assert.equal("download_dir" in bodies[0], false);+});++test("a folder pinned on the request wins over a later choice", async () => {+ storage.setItem(DOWNLOAD_DIR_STORAGE_KEY, "/mnt/b/Models");+ bodies.length = 0;+ await apiStart({ ...model, downloadDir: "/mnt/a/Models" }, false, null);+ await apiStart({ ...model, downloadDir: null }, false, null);+ assert.equal(bodies[0].download_dir, "/mnt/a/Models");+ assert.equal("download_dir" in bodies[1], false);+});++test("Resume after a cancel keeps the folder; a failed start takes the new choice", async () => {+ const { withDownloadDir } =+ await import("../src/features/hub/download-manager/transport-conflict.ts");+ const { putJob, jobKeyOf } =+ await import("../src/features/hub/download-manager/download-manager-state.ts");+ storage.setItem(DOWNLOAD_DIR_STORAGE_KEY, "/mnt/b/Models");+ const base = {+ key: jobKeyOf("model", model.repoId, model.variant),+ kind: "model" as const,+ repoId: model.repoId,+ variant: model.variant,+ downloadedBytes: 0,+ completedBytes: 0,+ completeOnDisk: false,+ expectedBytes: 0,+ fraction: 0,+ bytesPerSec: 0,+ etaSeconds: 0,+ error: null,+ startedAt: 1,+ downloadDir: "/mnt/a/Models",+ };+ putJob({ ...base, state: "cancelled" });+ assert.equal(withDownloadDir(model).downloadDir, "/mnt/a/Models");+ putJob({+ ...base,+ state: "error",+ error: "The parent folder does not exist.",+ });+ assert.equal(withDownloadDir(model).downloadDir, "/mnt/b/Models");+});diff --git a/studio/frontend/tests/download-transport-persistence.test.ts b/studio/frontend/tests/download-transport-persistence.test.tsindex af88c9aaba1..9e771c687dd 100644--- a/studio/frontend/tests/download-transport-persistence.test.ts+++ b/studio/frontend/tests/download-transport-persistence.test.ts@@ -52,6 +52,10 @@ store.set(invalid: persistedJob("org/auto-model", "auto"),fallback: persistedJob("org/fallback-model", "http", "xet"),badMarker: persistedJob("org/bad-marker-model", "http", "auto"),+ pinned: {+ ...persistedJob("org/pinned-model", "http"),+ downloadDir: "/mnt/e/AI/Models",+ },presented: {...persistedJob("org/presented-model", "http"),presentation: {@@ -322,3 +326,14 @@ test("an external job counts too, since a quit kills its transfer as well", () =false,);});++test("a Download to folder survives the reload and is written back", () => {+ // Lost, a cancel after the reload would resume into whatever folder is picked now.+ const key = jobKeyOf("model", "org/pinned-model", null);+ assert.equal(getState().jobs[key]?.downloadDir, "/mnt/e/AI/Models");+ putJob({ ...getState().jobs[key], downloadedBytes: 30 });+ assert.ok(flushPersistedState);+ flushPersistedState();+ const persisted = JSON.parse(store.get(PERSIST_KEY) ?? "null");+ assert.equal(persisted.state.jobs[key].downloadDir, "/mnt/e/AI/Models");+});diff --git a/studio/frontend/tests/helpers/download-lifecycle-auth-stub.mjs b/studio/frontend/tests/helpers/download-lifecycle-auth-stub.mjsindex 42b26c3a0d1..1a70b5af2ce 100644--- a/studio/frontend/tests/helpers/download-lifecycle-auth-stub.mjs+++ b/studio/frontend/tests/helpers/download-lifecycle-auth-stub.mjs@@ -9,3 +9,7 @@ export const AUTH_TOKEN_KEY = "unsloth_auth_token";export function authFetch(input, init) {return globalThis.fetch(input, init);}++export function isAccountOwner() {+ return true;+}diff --git a/studio/frontend/tests/helpers/store-stubs/auth.ts b/studio/frontend/tests/helpers/store-stubs/auth.tsindex b1720755a5a..d52a64136a1 100644--- a/studio/frontend/tests/helpers/store-stubs/auth.ts+++ b/studio/frontend/tests/helpers/store-stubs/auth.ts@@ -27,3 +27,7 @@ export async function prepareHfTokenForUse(): Promise<null> {export function useIsAccountOwner(): boolean {return true;}++export function isAccountOwner(): boolean {+ return true;+}