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: let the download transport be picked in Settings > General (#9272)
Michael Han1e06ca0514a4
diff --git a/studio/backend/hub/utils/download_registry.py b/studio/backend/hub/utils/download_registry.pyindex bdcb20e54b2..9943958e14f 100644--- a/studio/backend/hub/utils/download_registry.py+++ b/studio/backend/hub/utils/download_registry.py@@ -108,7 +108,16 @@ class DownloadTransportCapabilities:partials_resumable: bool = True-def get_download_transport_capabilities(*, probe: bool = False) -> DownloadTransportCapabilities:+def get_download_transport_capabilities(+ *, probe: bool = False, ram_gate: bool = False+) -> DownloadTransportCapabilities:+ """What this machine can do, and what Auto resolves to on it.++ ``probe`` runs the live Xet health check and is only for the frontend resolving Auto at+ download start. ``ram_gate`` applies the free-RAM half of that same verdict WITHOUT the+ network probe, for a surface that has to state what the next download will pick: the+ settings row said "Auto is using Xet" while the download path, which probes, chose HTTP.+ """xet_available = importlib.util.find_spec("hf_xet") is not Noneauto_transport = TRANSPORT_XET if xet_available else TRANSPORT_HTTPauto_reason: Optional[str] = None@@ -120,7 +129,10 @@ def get_download_transport_capabilities(*, probe: bool = False) -> DownloadTrans# Ordinary UI polls are read-only and must not load Zoo. `probe=True` is different:# the frontend sends it only while resolving Auto for a download, then submits the# concrete answer as xet/http, so this is the actual first-download decision.- health_fn = xet_health if probe else cached_xet_health+ # `ram_gate` loads it too, without probing: an empty cache reads as the optimistic+ # Xet, so the row promised Xet while the next download loaded an unhealthy verdict+ # and chose HTTP. Still `probe=probe`, so only a download start probes live.+ health_fn = xet_health if (probe or ram_gate) else cached_xet_healthhealth = health_fn(probe = probe)if health is not None:auto_transport = TRANSPORT_XET if health.use_xet else TRANSPORT_HTTP@@ -138,11 +150,16 @@ def get_download_transport_capabilities(*, probe: bool = False) -> DownloadTransexcept Exception:# No opinion: keep the optimistic default; the download-time ladder still recovers.pass- if xet_available and probe and auto_transport == TRANSPORT_XET and not auto_forced:+ if (+ xet_available+ and (probe or ram_gate)+ and auto_transport == TRANSPORT_XET+ and not auto_forced+ ):# Free RAM belongs in the same verdict: this IS the Auto decision, since the UI submits the# answer as an explicit xet/http. Read outside the health try, because a health module that- # is missing or raising says nothing about RAM. Probe-only, so an ordinary poll stays- # read-only and still does not load Zoo.+ # is missing or raising says nothing about RAM. Never on an ordinary poll, which stays+ # read-only and still does not load Zoo -- only for a probe or an explicit ram_gate.try:from utils.hf_xet_fallback import free_ram_pressure_reasonpressure = free_ram_pressure_reason()diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.pyindex 925e5924510..7e11cd5c217 100644--- a/studio/backend/routes/settings.py+++ b/studio/backend/routes/settings.py@@ -47,6 +47,10 @@ from utils.helper_precache_settings import (helper_model_disabled_by_env,set_helper_precache_enabled,)+from utils.download_transport_settings import (+ get_download_transport_mode,+ set_download_transport_mode,+)from picker.schemas import MAX_CHAT_TEMPLATE_BYTES, chat_template_byte_lengthfrom utils.coding_agents import CODING_AGENTS, detect_installed_coding_agentsfrom utils.model_memory_settings import (@@ -574,6 +578,19 @@ class HelperPrecacheResponse(BaseModel):disabled_by_env: bool+class DownloadTransportPayload(BaseModel):+ mode: Literal["auto", "xet", "http"]+++class DownloadTransportResponse(BaseModel):+ mode: str+ xet_available: bool+ xet_unavailable_reason: Optional[str] = None+ # What "auto" resolves to here right now, and why.+ auto_resolves_to: str+ auto_reason: Optional[str] = None++class XetNoticeReservePayload(BaseModel):# A legacy localStorage count from a client that has not reported one before.# Can only raise the stored count (see reserve_xet_notice), so a client cannot@@ -844,6 +861,20 @@ def _helper_precache_response(enabled: bool | None = None) -> HelperPrecacheResp)+def _download_transport_response(mode: str | None = None) -> DownloadTransportResponse:+ # No Xet probe: this renders a row, not a download start. The free-RAM gate is asked for+ # anyway, since the row states what the next download will use.+ from hub.utils.download_registry import get_download_transport_capabilities+ caps = get_download_transport_capabilities(ram_gate = True)+ return DownloadTransportResponse(+ mode = get_download_transport_mode() if mode is None else mode,+ xet_available = caps.xet.available,+ xet_unavailable_reason = caps.xet.reason,+ auto_resolves_to = caps.auto_resolves_to,+ auto_reason = caps.auto_reason,+ )++# Distinct from None, which is a real launch this policy does not govern._NO_LAUNCH = object()@@ -1085,6 +1116,30 @@ def update_helper_precache(return _helper_precache_response(enabled)[email protected]("/download-transport", response_model = DownloadTransportResponse)+def get_download_transport(+ current_subject: str = Depends(get_current_subject),+) -> DownloadTransportResponse:+ return _download_transport_response()++[email protected]("/download-transport", response_model = DownloadTransportResponse)+def update_download_transport(+ payload: DownloadTransportPayload, current_subject: str = Depends(get_current_subject)+) -> DownloadTransportResponse:+ try:+ mode = set_download_transport_mode(payload.mode)+ except ValueError as exc:+ raise log_and_http_error(+ exc,+ 400,+ safe_error_detail(exc, fallback = "Invalid download transport."),+ event = "settings.update_download_transport_failed",+ log = logger,+ ) from exc+ return _download_transport_response(mode)++@router.post("/xet-notice/reserve", response_model = XetNoticeResponse)def post_xet_notice_reserve(payload: XetNoticeReservePayload, current_subject: str = Depends(get_current_subject)diff --git a/studio/backend/tests/test_download_transport_setting.py b/studio/backend/tests/test_download_transport_setting.pynew file mode 100644index 00000000000..36dabbc345d--- /dev/null+++ b/studio/backend/tests/test_download_transport_setting.py@@ -0,0 +1,110 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The install's download transport setting.++A stored preference, nothing more: the transport an install runs on is unchanged until someone+picks one in Settings > General. These tests pin the default, the validation, and the routes the+settings row reads and writes.+"""++from __future__ import annotations++from pathlib import Path+import sys+import types as _types++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++_loggers_stub = _types.ModuleType("loggers")+_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)+sys.modules.setdefault("loggers", _loggers_stub)++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++import routes.settings as settings+import storage.studio_db as studio_db+import utils.download_transport_settings as transport_settings+++def store(monkeypatch):+ """An in-memory app_settings."""+ values: dict = {}+ monkeypatch.setattr(+ studio_db, "get_app_setting", lambda key, fallback = None: values.get(key, fallback)+ )+ monkeypatch.setattr(+ studio_db, "upsert_app_settings", lambda updates: values.update(updates) or values+ )+ return values+++def test_nothing_picked_means_auto(store):+ assert transport_settings.get_download_transport_mode() == "auto"+ # Read-only: seeding a value would be this setting deciding for an install that never+ # opened it.+ assert store == {}+++def test_a_stored_choice_is_returned(store):+ store[transport_settings.DOWNLOAD_TRANSPORT_SETTING_KEY] = "xet"+ assert transport_settings.get_download_transport_mode() == "xet"+++def test_junk_on_disk_reads_as_nothing_picked(store):+ store[transport_settings.DOWNLOAD_TRANSPORT_SETTING_KEY] = "carrier-pigeon"+ assert transport_settings.get_download_transport_mode() == "auto"+++def test_an_unreadable_db_reports_the_default(monkeypatch):+ """A settings row is not worth a 500, and the default is what the install already ran on."""++ def locked(*_args, **_kwargs):+ raise RuntimeError("database is locked")++ monkeypatch.setattr(studio_db, "get_app_setting", locked)+ assert transport_settings.get_download_transport_mode() == "auto"+++def test_set_validates_and_persists(store):+ assert transport_settings.set_download_transport_mode("XET ") == "xet"+ assert store[transport_settings.DOWNLOAD_TRANSPORT_SETTING_KEY] == "xet"+ for junk in ("ftp", "", None, 3, True):+ with pytest.raises(ValueError):+ transport_settings.set_download_transport_mode(junk)+++# ------------------------------------------------------------------------------------------+# Routes+# ------------------------------------------------------------------------------------------+++def client(store):+ app = FastAPI()+ app.include_router(settings.router)+ app.dependency_overrides[settings.get_current_subject] = lambda: "admin"+ return TestClient(app, raise_server_exceptions = False)+++def test_route_reports_the_mode_and_what_auto_would_do(client):+ body = client.get("/download-transport").json()+ assert body["mode"] == "auto"+ # The row shows this under Auto, so it has to be a transport a download can actually run on.+ assert body["auto_resolves_to"] in {"http", "xet"}+ assert isinstance(body["xet_available"], bool)+++def test_route_saves_a_choice(client, store):+ body = client.put("/download-transport", json = {"mode": "http"}).json()+ assert body["mode"] == "http"+ assert store[transport_settings.DOWNLOAD_TRANSPORT_SETTING_KEY] == "http"+++def test_route_rejects_an_unknown_transport(client):+ assert client.put("/download-transport", json = {"mode": "ftp"}).status_code == 422diff --git a/studio/backend/tests/test_hub_download_transport_auto.py b/studio/backend/tests/test_hub_download_transport_auto.pyindex f48a12fe373..643e27e38a8 100644--- a/studio/backend/tests/test_hub_download_transport_auto.py+++ b/studio/backend/tests/test_hub_download_transport_auto.py@@ -845,3 +845,55 @@ def test_the_capabilities_probe_agrees_about_a_forced_verdict(monkeypatch):caps = download_registry.get_download_transport_capabilities(probe = True)assert caps.auto_resolves_to == download_registry.TRANSPORT_HTTPassert "RAM free" in (caps.auto_reason or "")+++def test_the_ram_gate_can_be_asked_for_without_the_probe(monkeypatch):+ """The settings row states what the NEXT download will pick, and the download path probes.+ Without this it read the health cache but skipped the free-RAM half, so it said "Auto is+ using Xet" on a machine whose next download resolves to HTTP."""+ fake = _types.ModuleType("utils.hf_xet_fallback")+ fake.cached_xet_health = lambda **kw: _types.SimpleNamespace(use_xet = True, reason = "Xet")+ fake.xet_health = fake.cached_xet_health+ fake.free_ram_pressure_reason = lambda: "HTTP: only 2.0GB RAM free"+ monkeypatch.setitem(sys.modules, "utils.hf_xet_fallback", fake)+ monkeypatch.setattr(download_registry.importlib.util, "find_spec", lambda _name: object())++ caps = download_registry.get_download_transport_capabilities(ram_gate = True)+ assert caps.auto_resolves_to == download_registry.TRANSPORT_HTTP+ assert "2.0GB RAM free" in caps.auto_reason++ # And the default is unchanged: an ordinary poll still must not read free RAM.+ assert (+ download_registry.get_download_transport_capabilities().auto_resolves_to+ == download_registry.TRANSPORT_XET+ )+++def test_the_ram_gate_loads_health_instead_of_reading_an_empty_cache(monkeypatch):+ """A fresh backend has no cached verdict, so the cache reads as the optimistic Xet while the+ next download loads a persisted unhealthy one and picks HTTP. The settings row states what+ that download will do, so it has to load the same verdict -- without the live probe."""+ seen: list[tuple[str, bool]] = []++ class _Health:+ use_xet = False+ reason = "persisted: CAS unreachable"++ def _cached(*, probe = True):+ seen.append(("cached", probe))+ return None++ def _loading(*, probe = True):+ seen.append(("loading", probe))+ return _Health()++ stub = _types.ModuleType("utils.hf_xet_fallback")+ stub.cached_xet_health = _cached+ stub.xet_health = _loading+ monkeypatch.setitem(sys.modules, "utils.hf_xet_fallback", stub)+ monkeypatch.setattr(download_registry.importlib.util, "find_spec", lambda _name: object())++ caps = download_registry.get_download_transport_capabilities(ram_gate = True)+ assert caps.auto_resolves_to == download_registry.TRANSPORT_HTTP+ # Loaded, but NOT probed: the live check stays with a real download start.+ assert seen == [("loading", False)]diff --git a/studio/backend/utils/download_transport_settings.py b/studio/backend/utils/download_transport_settings.pynew file mode 100644index 00000000000..5dc75fca151--- /dev/null+++ b/studio/backend/utils/download_transport_settings.py@@ -0,0 +1,52 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The install's download transport preference: HTTPS, Xet, or Auto.++Stored so the choice follows the install rather than one browser's localStorage. Nothing picked+means Auto, which is what downloads ran on before this setting existed.+"""++from __future__ import annotations++from typing import Any, Optional++from hub.utils.hf_cache_state import TRANSPORT_AUTO, VALID_TRANSPORT_MODES+from loggers import get_logger++logger = get_logger(__name__)++DOWNLOAD_TRANSPORT_SETTING_KEY = "download_transport_mode"+# Unchanged by this setting: an install nobody has touched still lets the backend pick.+DEFAULT_DOWNLOAD_TRANSPORT = TRANSPORT_AUTO+++def normalize_transport_mode(value: Any) -> Optional[str]:+ """``value`` as one of http/xet/auto, or None when it is not a transport mode."""+ if not isinstance(value, str):+ return None+ mode = value.strip().lower()+ return mode if mode in VALID_TRANSPORT_MODES else None+++def get_download_transport_mode() -> str:+ """The install's stored transport, or Auto when nobody has picked one."""+ try:+ from storage.studio_db import get_app_setting+ stored = normalize_transport_mode(get_app_setting(DOWNLOAD_TRANSPORT_SETTING_KEY, None))+ except Exception as exc: # noqa: BLE001 - an unreadable db reports the default, not a 500+ logger.debug("download transport read failed (%s)", exc)+ stored = None+ return DEFAULT_DOWNLOAD_TRANSPORT if stored is None else stored+++def set_download_transport_mode(value: Any) -> str:+ """Persist the install's download transport. Raises ValueError on anything else."""+ mode = normalize_transport_mode(value)+ if mode is None:+ raise ValueError("Download transport must be one of: http, xet, auto.")++ from storage.studio_db import upsert_app_settings++ upsert_app_settings({DOWNLOAD_TRANSPORT_SETTING_KEY: mode})+ return modediff --git a/studio/frontend/src/features/hub/catalog/transport-toggle.tsx b/studio/frontend/src/features/hub/catalog/transport-toggle.tsxindex 1bb5dc0a7cd..08c8ff3e995 100644--- a/studio/frontend/src/features/hub/catalog/transport-toggle.tsx+++ b/studio/frontend/src/features/hub/catalog/transport-toggle.tsx@@ -34,16 +34,21 @@ const OPTIONS: { value: "auto" | "http" | "xet"; label: string; hint: string }[]export function TransportToggle() {const [mode, setMode] = useTransportMode();- const { capabilities } = useDownloadTransportCapabilities();- const xetUnavailable = capabilities?.xet.available === false;+ const { capabilities, isLoading } = useDownloadTransportCapabilities();+ // Two questions. Xet cannot be CHOSEN until we know it runs here; the fallback may only fire+ // once we know it does NOT, or a loading tab shows HTTP for a stored Xet that was fine.+ const xetKnownUnavailable = capabilities?.xet.available === false;+ const xetUnavailable = isLoading || xetKnownUnavailable;const autoResolvesTo = capabilities?.auto_resolves_to ?? "xet";const autoReason = capabilities?.auto_reason;useEffect(() => {- if (mode === "xet" && xetUnavailable) {- setMode("http");+ if (mode === "xet" && xetKnownUnavailable) {+ // Reflected, never stored: a fallback stored here would outrank the install setting and+ // survive hf_xet being installed later.+ setMode("http", { persist: false });}- }, [mode, setMode, xetUnavailable]);+ }, [mode, setMode, xetKnownUnavailable]);return (<fieldsetdiff --git a/studio/frontend/src/features/hub/download-manager/constants.ts b/studio/frontend/src/features/hub/download-manager/constants.tsindex eeadaee4427..683f24cccd3 100644--- a/studio/frontend/src/features/hub/download-manager/constants.ts+++ b/studio/frontend/src/features/hub/download-manager/constants.ts@@ -19,10 +19,25 @@ export const TRANSPORT_MODES = [TRANSPORT.XET,] as const;export type TransportMode = (typeof TRANSPORT_MODES)[number];-// Auto by default: the backend picks per machine (RAM, hf_xet build, recent Xet failures), and-// effectiveTransportMode() resolves that to a concrete transport before any download starts.+// Auto until someone picks otherwise: the backend chooses per machine (RAM, hf_xet build,+// recent Xet failures) and effectiveTransportMode() resolves it before any download starts.+// Only a floor, since the install's setting arrives from /api/settings/download-transport.export const DEFAULT_TRANSPORT_MODE: TransportMode = TRANSPORT.AUTO;+/** The preference in force: this browser's own choice, else the install's setting, else Auto. */+export function pickTransportMode(+ stored: unknown,+ installed: unknown,+): TransportMode {+ if (isTransportMode(stored)) {+ return stored;+ }+ if (isTransportMode(installed)) {+ return installed;+ }+ return DEFAULT_TRANSPORT_MODE;+}+export function isTransportMode(value: unknown): value is TransportMode {return (typeof value === "string" &&diff --git a/studio/frontend/src/features/hub/download-manager/index.ts b/studio/frontend/src/features/hub/download-manager/index.tsindex 60b0eeef050..e6ab9fccdf8 100644--- a/studio/frontend/src/features/hub/download-manager/index.ts+++ b/studio/frontend/src/features/hub/download-manager/index.ts@@ -51,7 +51,9 @@ export {export { scopedVariant } from "./download-manager-types";export { dismissStartToast, dismissStartToasts } from "./start-toast";export {+ TRANSPORT_MODE_STORAGE_KEY,getTransportMode,+ resolveTransportMode,useDownloadTransportCapabilities,useHttpPartialsResumable,useTransportMode,diff --git a/studio/frontend/src/features/hub/download-manager/poll-loop.ts b/studio/frontend/src/features/hub/download-manager/poll-loop.tsindex 8d00cf7bf4b..c8ebb4be1fd 100644--- a/studio/frontend/src/features/hub/download-manager/poll-loop.ts+++ b/studio/frontend/src/features/hub/download-manager/poll-loop.ts@@ -98,7 +98,7 @@ import {runtimeRegistry,teardownRuntime,} from "./runtime-registry";-import { getTransportMode } from "./transport-preference";+import { resolveTransportMode } from "./transport-preference";function notify(job: ManagedDownload,@@ -627,9 +627,14 @@ export async function startJob(// An explicit opts.useXet (a retry pinning a transport) wins; otherwise carry the stored// preference UNRESOLVED so "auto" survives to effectiveTransportMode(). Collapsing it to a// boolean here would read "auto" as "not xet" and send every download over HTTP.- const requestedMode: TransportMode =- opts.useXet === undefined- ? getTransportMode()+ // Never for an adopted job: that branch ignores requestedMode, and resolving it is now a+ // settings round trip. Suspending here left pollingStarted=false long enough for the other+ // concurrent adoptJob caller to replace this runtime, and both continuations then reached+ // beginPolling, leaving duplicate timers and a leaked visibility listener.+ const requestedMode: TransportMode = opts.adopt+ ? TRANSPORT.HTTP+ : opts.useXet === undefined+ ? await resolveTransportMode(): opts.useXet? TRANSPORT.XET: TRANSPORT.HTTP;diff --git a/studio/frontend/src/features/hub/download-manager/transport-conflict.ts b/studio/frontend/src/features/hub/download-manager/transport-conflict.tsindex 595ea02333a..b295988f37a 100644--- a/studio/frontend/src/features/hub/download-manager/transport-conflict.ts+++ b/studio/frontend/src/features/hub/download-manager/transport-conflict.ts@@ -24,7 +24,7 @@ import {import { startJob } from "./poll-loop";import { currentRoute, showCallerToast } from "./start-toast";import { runtimeRegistry } from "./runtime-registry";-import { getTransportMode } from "./transport-preference";+import { resolveTransportMode } from "./transport-preference";import { ACTIVE_STATES, TRANSPORT_STATUS_TIMEOUT_MS } from "./download-manager-config";function reportConflictStartError(error: unknown): void {@@ -155,7 +155,7 @@ export async function requestStart(// during; read after them it would name the page they moved to.const originRoute = currentRoute();return runWithPendingStartGuard(req, async () => {- let mode: TransportMode = getTransportMode();+ let mode: TransportMode = await resolveTransportMode();try {mode = await effectiveTransportMode(mode);} catch (err) {diff --git a/studio/frontend/src/features/hub/download-manager/transport-preference.ts b/studio/frontend/src/features/hub/download-manager/transport-preference.tsindex 624c6df72fe..14339739539 100644--- a/studio/frontend/src/features/hub/download-manager/transport-preference.ts+++ b/studio/frontend/src/features/hub/download-manager/transport-preference.ts@@ -1,20 +1,28 @@// 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 { useCallback, useEffect, useState } from "react";+import {+ loadDownloadTransportSettings,+ subscribeDownloadTransportSettings,+ updateDownloadTransportSettings,+} from "@/features/settings";import { toast } from "@/lib/toast";+import { useCallback, useEffect, useState } from "react";import {type DownloadTransportCapabilities,getDownloadTransportCapabilities,} from "./api";import {- DEFAULT_TRANSPORT_MODE,type TransportMode,isTransportMode,+ pickTransportMode,} from "./constants";export type { TransportMode } from "./constants";-const STORAGE_KEY = "unsloth.studio.transportMode";+/** This browser's own override. Exported because it outranks the install-wide setting, so+ * "Reset all local preferences" has to clear it. */+export const TRANSPORT_MODE_STORAGE_KEY = "unsloth.studio.transportMode";+const STORAGE_KEY = TRANSPORT_MODE_STORAGE_KEY;const CHANGE_EVENT = "unsloth:transport-preference-change";type TransportCapabilitiesState = {@@ -22,30 +30,78 @@ type TransportCapabilitiesState = {isLoading: boolean;};-function readStored(): TransportMode {+// The install's setting, cached because the download path reads it synchronously.+let installMode: TransportMode | null = null;+let installModeInFlight: Promise<TransportMode | null> | null = null;+let installModeInFlightIsRefresh = false;++/** This browser's own choice, or null when it has never made one. */+function readStored(): TransportMode | null {if (typeof window === "undefined") {- return DEFAULT_TRANSPORT_MODE;+ return null;}try {const raw = window.localStorage.getItem(STORAGE_KEY);- return isTransportMode(raw) ? raw : DEFAULT_TRANSPORT_MODE;+ return isTransportMode(raw) ? raw : null;} catch {- return DEFAULT_TRANSPORT_MODE;+ return null;+ }+}++function loadInstallMode(refresh: boolean): Promise<TransportMode | null> {+ return loadDownloadTransportSettings({ refresh }).then((settings) => {+ installMode = isTransportMode(settings.mode) ? settings.mode : null;+ return installMode;+ });+}++function hydrateInstallMode(refresh = false): Promise<TransportMode | null> {+ // Only the API layer decides what may be shared: riding on an ordinary hydration already in+ // flight would hand back the value this refresh went to replace.+ if (installModeInFlight && (!refresh || installModeInFlightIsRefresh)) {+ return installModeInFlight;}+ // Not shared, but not thrown away either: a download started before the first hydration+ // answers overtakes it with a refresh, and if that refresh fails there is still a request+ // coming with the install's real choice.+ const superseded = refresh ? installModeInFlight : null;+ const pending = loadInstallMode(refresh)+ // Keep what we loaded: discarding it on a transient failure sent the next download to Auto.+ .catch(() => (installMode === null && superseded ? superseded : installMode))+ .finally(() => {+ if (installModeInFlight === pending) {+ installModeInFlight = null;+ installModeInFlightIsRefresh = false;+ }+ });+ installModeInFlight = pending;+ installModeInFlightIsRefresh = refresh;+ return pending;}+/** The preference as currently known, without waiting on the install setting. */export function getTransportMode(): TransportMode {- return readStored();+ return pickTransportMode(readStored(), installMode);+}++/** The preference, waiting for the install setting when this browser has no choice of its own.+ * Re-read rather than cached, since another browser can change it mid-session. */+export async function resolveTransportMode(): Promise<TransportMode> {+ const stored = readStored();+ if (stored !== null) {+ return stored;+ }+ return pickTransportMode(null, await hydrateInstallMode(true));}export function useTransportMode(): [TransportMode,- (next: TransportMode) => void,+ (next: TransportMode, opts?: { persist?: boolean }) => void,] {- const [mode, setMode] = useState<TransportMode>(readStored);+ const [mode, setMode] = useState<TransportMode>(getTransportMode);useEffect(() => {- const handleLocal = () => setMode(readStored());+ const handleLocal = () => setMode(getTransportMode());const handleStorage = (event: StorageEvent) => {if (event.storageArea !== window.localStorage) {return;@@ -53,37 +109,71 @@ export function useTransportMode(): [if (event.key !== null && event.key !== STORAGE_KEY) {return;}- setMode(readStored());+ setMode(getTransportMode());};window.addEventListener(CHANGE_EVENT, handleLocal);window.addEventListener("storage", handleStorage);+ // Another surface saved it: adopt it unless this browser has its own choice.+ const unsubscribe = subscribeDownloadTransportSettings((settings) => {+ installMode = isTransportMode(settings.mode)+ ? settings.mode+ : installMode;+ setMode(getTransportMode());+ });+ // Refreshed, like the download path: reading the cache here showed the old mode in the+ // toggle while the next download already ran on the one another browser had set.+ void hydrateInstallMode(true).then(() => setMode(getTransportMode()));return () => {window.removeEventListener(CHANGE_EVENT, handleLocal);window.removeEventListener("storage", handleStorage);+ unsubscribe();};}, []);- const set = useCallback((next: TransportMode) => {- // Persist first, reflect after: the engine reads getTransportMode() fresh- // from localStorage at download time, so an optimistic setMode() before a- // failed write (private mode / quota) would show the new transport while- // downloads still used the old one. On failure leave everything untouched.+ const set = useCallback((+ next: TransportMode,+ opts: { persist?: boolean } = {},+ ) => {+ // A fallback this machine forced, not a choice: reflect it and write nothing. Stored, it+ // would outrank the install setting and survive hf_xet being repaired.+ if (opts.persist === false) {+ setMode(next);+ return;+ }+ // Persist first, reflect after: downloads re-read localStorage, so an optimistic setMode()+ // before a failed write would show a transport the downloads do not use.+ let savedLocally = true;try {window.localStorage.setItem(STORAGE_KEY, next);} catch {- toast.error("Couldn't save the download transport preference.");- return;+ savedLocally = false;+ }+ if (savedLocally) {+ setMode(next);+ window.dispatchEvent(new Event(CHANGE_EVENT));}- setMode(next);- window.dispatchEvent(new Event(CHANGE_EVENT));+ // And the install's setting, so other browsers follow. With storage blocked this is the+ // only store, and the subscription keeps the reflect-after rule holding through it.+ void updateDownloadTransportSettings(next).catch((error) => {+ console.warn(+ "Couldn't save the download transport for this install.",+ error,+ );+ // Said out loud either way: the row calls this setting install-wide, so a local-only+ // save is a mismatch and no save at all is a click that did nothing.+ toast.error(+ savedLocally+ ? "Saved for this browser, but not for this install."+ : "Couldn't save the download transport preference.",+ );+ });}, []);return [mode, set];}-/** Whether an interrupted HTTP transfer leaves resumable bytes on this backend.- * False until the capabilities land, so a card never flashes a resume promise- * it may have to take back. */+/** Whether an interrupted HTTP transfer leaves resumable bytes on this backend. False until+ * the capabilities land, so no card flashes a resume promise it may take back. */export function useHttpPartialsResumable(): boolean {const { capabilities } = useDownloadTransportCapabilities();return capabilities?.partials_resumable === true;diff --git a/studio/frontend/src/features/hub/index.ts b/studio/frontend/src/features/hub/index.tsindex f71d1662e12..3b137ec4190 100644--- a/studio/frontend/src/features/hub/index.ts+++ b/studio/frontend/src/features/hub/index.ts@@ -8,8 +8,12 @@ export {jobKeyOf,startExternalJob,subscribeJobListeners,+ type TransportMode,updateExternalJob,+ TRANSPORT_MODE_STORAGE_KEY,useDownloadManagerStore,+ useHttpPartialsResumable,+ useTransportMode,} from "./download-manager";export { HfTokenIndicator } from "./components/hf-token-indicator";export { useHubDatasetSearch } from "./hooks/use-hub-dataset-search";diff --git a/studio/frontend/src/features/settings/api/download-transport.ts b/studio/frontend/src/features/settings/api/download-transport.tsnew file mode 100644index 00000000000..ec8558b7658--- /dev/null+++ b/studio/frontend/src/features/settings/api/download-transport.ts@@ -0,0 +1,152 @@+// 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 { authFetch } from "@/features/auth";+import { readFastApiError } from "@/lib/format-fastapi-error";++const DOWNLOAD_TRANSPORT_EVENT = "unsloth-download-transport-change";++export type DownloadTransportMode = "auto" | "xet" | "http";++export type DownloadTransportSettings = {+ mode: DownloadTransportMode;+ xetAvailable: boolean;+ xetUnavailableReason: string | null;+ autoResolvesTo: "xet" | "http";+ autoReason: string | null;+};++type ApiDownloadTransportSettings = {+ mode: string;+ // biome-ignore lint/style/useNamingConvention: API schema+ xet_available: boolean;+ // biome-ignore lint/style/useNamingConvention: API schema+ xet_unavailable_reason: string | null;+ // biome-ignore lint/style/useNamingConvention: API schema+ auto_resolves_to: string;+ // biome-ignore lint/style/useNamingConvention: API schema+ auto_reason: string | null;+};++let cachedTransport: DownloadTransportSettings | null = null;+let inFlightTransport: Promise<DownloadTransportSettings> | null = null;+// A refreshing caller cannot ride on a GET answered before it asked: that response predates+// whatever change it is refreshing to find.+let inFlightIsRefresh = false;+// Newest request wins, or an older overlapping GET lands last and re-caches what it replaced.+let latestRequest = 0;++export function subscribeDownloadTransportSettings(+ listener: (settings: DownloadTransportSettings) => void,+) {+ const handleChange = (event: Event) => {+ listener((event as CustomEvent<DownloadTransportSettings>).detail);+ };+ window.addEventListener(DOWNLOAD_TRANSPORT_EVENT, handleChange);+ return () =>+ window.removeEventListener(DOWNLOAD_TRANSPORT_EVENT, handleChange);+}++function asMode(value: string, fallback: DownloadTransportMode) {+ return value === "auto" || value === "xet" || value === "http"+ ? value+ : fallback;+}++function fromApi(+ settings: ApiDownloadTransportSettings,+): DownloadTransportSettings {+ return {+ // Auto, as an install with nothing picked runs: a server that answers with something else+ // must not be read as a choice the user made.+ mode: asMode(settings.mode, "auto"),+ xetAvailable: settings.xet_available,+ xetUnavailableReason: settings.xet_unavailable_reason,+ autoResolvesTo: settings.auto_resolves_to === "xet" ? "xet" : "http",+ autoReason: settings.auto_reason,+ };+}++function cacheTransport(settings: DownloadTransportSettings) {+ cachedTransport = settings;+ window.dispatchEvent(+ new CustomEvent(DOWNLOAD_TRANSPORT_EVENT, { detail: settings }),+ );+ return settings;+}++async function fetchDownloadTransportSettings(): Promise<DownloadTransportSettings> {+ const res = await authFetch("/api/settings/download-transport");+ if (!res.ok) {+ throw new Error(+ await readFastApiError(res, "Failed to load download transport settings"),+ );+ }+ return fromApi(await res.json());+}++/** The install's setting. `refresh` skips the cache, for a caller that must not act on a value+ * another browser may since have changed. Refreshing callers share a GET with each other, never+ * with a plain hydration already in flight. */+export async function loadDownloadTransportSettings(+ opts: { refresh?: boolean } = {},+) {+ if (cachedTransport && !opts.refresh) {+ return cachedTransport;+ }+ if (inFlightTransport && (!opts.refresh || inFlightIsRefresh)) {+ return inFlightTransport;+ }+ const request = ++latestRequest;+ inFlightIsRefresh = Boolean(opts.refresh);+ const pending = fetchDownloadTransportSettings()+ .then((settings) => {+ if (request === latestRequest) {+ return cacheTransport(settings);+ }+ // Superseded. Callers read the resolved value straight into their own state, so handing+ // back the stale payload would revert the write that superseded it.+ return cachedTransport ?? settings;+ })+ .finally(() => {+ if (inFlightTransport === pending) {+ inFlightTransport = null;+ inFlightIsRefresh = false;+ }+ });+ inFlightTransport = pending;+ return pending;+}++// Writes run one at a time. Two quick selections used to race, and the earlier PUT landing+// last left the database on the mode the user did NOT pick while this browser showed the one+// they did. Chained rather than cancelled, so the last selection is also the last write.+let writeQueue: Promise<unknown> = Promise.resolve();++async function putDownloadTransport(+ mode: DownloadTransportMode,+): Promise<DownloadTransportSettings> {+ const res = await authFetch("/api/settings/download-transport", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ mode }),+ });+ if (!res.ok) {+ throw new Error(+ await readFastApiError(res, "Failed to update download transport"),+ );+ }+ // Advance the generation: a GET issued before this write is now stale, and letting its+ // response land afterwards republished the mode the user had just replaced.+ latestRequest += 1;+ return cacheTransport(fromApi(await res.json()));+}++export function updateDownloadTransportSettings(+ mode: DownloadTransportMode,+): Promise<DownloadTransportSettings> {+ // The queue must survive a rejected write, or one failure strands every later selection.+ const next = writeQueue.catch(() => undefined).then(() => putDownloadTransport(mode));+ writeQueue = next.catch(() => undefined);+ return next;+}diff --git a/studio/frontend/src/features/settings/components/download-transport-row.tsx b/studio/frontend/src/features/settings/components/download-transport-row.tsxnew file mode 100644index 00000000000..47a3aef4fff--- /dev/null+++ b/studio/frontend/src/features/settings/components/download-transport-row.tsx@@ -0,0 +1,181 @@+// 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 {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/components/ui/tooltip";+import {+ type TransportMode,+ useHttpPartialsResumable,+ useTransportMode,+} from "@/features/hub";+import { type TranslationKey, useT } from "@/i18n";+import { cn } from "@/lib/utils";+import { useEffect, useState } from "react";+import {+ type DownloadTransportSettings,+ loadDownloadTransportSettings,+ subscribeDownloadTransportSettings,+} from "../api/download-transport";+import { SettingsRow } from "./settings-row";++const OPTIONS: {+ value: TransportMode;+ labelKey: TranslationKey;+ hintKey: TranslationKey;+}[] = [+ {+ value: "http",+ labelKey: "settings.general.downloads.https",+ hintKey: "settings.general.downloads.httpsHint",+ },+ {+ value: "xet",+ labelKey: "settings.general.downloads.xet",+ hintKey: "settings.general.downloads.xetHint",+ },+ {+ value: "auto",+ labelKey: "settings.general.downloads.auto",+ hintKey: "settings.general.downloads.autoHint",+ },+];++export function DownloadTransportRow() {+ const t = useT();+ const [mode, setMode] = useTransportMode();+ // huggingface_hub 1.18 refetches an interrupted transfer from zero, so promising HTTPS+ // "resumes where it stopped" there is backwards.+ const partialsResumable = useHttpPartialsResumable();+ const [settings, setSettings] = useState<DownloadTransportSettings | null>(+ null,+ );+ // Distinct from "settings is null": a FAILED load must not disable Xet for good.+ const [capabilityPending, setCapabilityPending] = useState(true);++ useEffect(() => {+ // The only teardown: an in-flight load resolves into the cache, not into this setter.+ const unsubscribe = subscribeDownloadTransportSettings((next) => {+ setSettings(next);+ setCapabilityPending(false);+ });+ // Refreshed on mount: the cache can hold a mode another browser changed, or a stale+ // Auto verdict.+ loadDownloadTransportSettings({ refresh: true })+ .then(setSettings)+ .catch(() => undefined)+ .finally(() => setCapabilityPending(false));+ return unsubscribe;+ }, []);++ // Unknown counts as unavailable while the first load is in flight: clicking Xet there+ // stored a preference every later download silently ignored.+ const xetUnavailable = capabilityPending || settings?.xetAvailable === false;+ // The localized string first: the backend's one reason is English prose, and preferring it+ // showed English to every other locale. An unknown future reason still gets through.+ const serverReason = settings?.xetUnavailableReason;+ const xetReason =+ !serverReason || /hf_xet is not installed/i.test(serverReason)+ ? t("settings.general.downloads.xetMissing")+ : serverReason;++ // Xet selected but unable to run here: say so rather than silently using HTTPS. Only once+ // known, since while pending we have not been told hf_xet is missing.+ const status =+ !capabilityPending && xetUnavailable && mode === "xet"+ ? xetReason+ : mode === "auto" && settings+ ? t("settings.general.downloads.autoCurrently", {+ transport:+ settings.autoResolvesTo === "xet"+ ? t("settings.general.downloads.xet")+ : t("settings.general.downloads.https"),+ })+ : null;++ // The health check's own words, on their own line: free-form English, so folding it into a+ // translated sentence produced half a sentence in each language. Auto is the only branch+ // with a reason to explain.+ const statusReason = mode === "auto" ? (settings?.autoReason ?? null) : null;++ return (+ <SettingsRow+ alignTop={true}+ label={t("settings.general.downloads.transport")}+ description={t(+ partialsResumable+ ? "settings.general.downloads.transportDescription"+ : "settings.general.downloads.transportDescriptionNoResume",+ )}+ hint={t("settings.general.downloads.transportHint")}+ >+ <div className="flex flex-col items-end gap-1.5">+ <div+ role="radiogroup"+ aria-label={t("settings.general.downloads.transport")}+ className="hub-tab-toggle inline-flex h-8 items-center rounded-full"+ >+ {OPTIONS.map((opt) => {+ const active = mode === opt.value;+ const disabled = opt.value === "xet" && xetUnavailable;+ return (+ <Tooltip key={opt.value}>+ <TooltipTrigger asChild={true}>+ <button+ type="button"+ role="radio"+ // Indexed for settings search, so the result has somewhere to scroll to.+ data-settings-label={t(opt.labelKey)}+ aria-checked={active}+ aria-disabled={disabled || undefined}+ onClick={() => {+ if (!disabled) setMode(opt.value);+ }}+ className={cn(+ "relative flex h-8 items-center rounded-full px-3 text-xs font-medium transition-colors",+ disabled+ ? "cursor-not-allowed text-muted-foreground/45"+ : active+ ? "hub-tab-toggle-pill text-foreground"+ : "text-muted-foreground hover:text-foreground",+ )}+ >+ <span className="relative z-10">{t(opt.labelKey)}</span>+ </button>+ </TooltipTrigger>+ <TooltipContent+ side="bottom"+ sideOffset={6}+ className="max-w-[260px]"+ >+ {disabled && !capabilityPending+ ? xetReason+ : t(+ opt.value === "http" && !partialsResumable+ ? "settings.general.downloads.httpsHintNoResume"+ : opt.hintKey,+ )}+ </TooltipContent>+ </Tooltip>+ );+ })}+ </div>+ {status ? (+ <span className="max-w-[280px] text-right text-xs text-muted-foreground">+ {status}+ </span>+ ) : null}+ {statusReason ? (+ <span+ lang="en"+ className="max-w-[280px] text-right text-xs text-muted-foreground/70"+ >+ {statusReason}+ </span>+ ) : null}+ </div>+ </SettingsRow>+ );+}diff --git a/studio/frontend/src/features/settings/index.ts b/studio/frontend/src/features/settings/index.tsindex 168139eb0c5..ae0cbe88925 100644--- a/studio/frontend/src/features/settings/index.ts+++ b/studio/frontend/src/features/settings/index.ts@@ -2,6 +2,13 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0export { SettingsDialog } from "./settings-dialog";+export {+ type DownloadTransportMode,+ type DownloadTransportSettings,+ loadDownloadTransportSettings,+ subscribeDownloadTransportSettings,+ updateDownloadTransportSettings,+} from "./api/download-transport";export { loadEmbeddingModelSettings } from "./api/embedding-model";export { loadOpenAIAutoSwitchSettings } from "./api/openai-auto-switch";export {diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.tsindex 1668d49b513..54dd503285b 100644--- a/studio/frontend/src/features/settings/settings-search.ts+++ b/studio/frontend/src/features/settings/settings-search.ts@@ -25,6 +25,11 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {"settings.general.rag.embeddingModel","settings.general.helperLlm.sectionTitle","settings.general.helperLlm.preloadOnStartup",+ "settings.general.downloads.sectionTitle",+ "settings.general.downloads.transport",+ "settings.general.downloads.https",+ "settings.general.downloads.xet",+ "settings.general.downloads.auto","settings.general.uploads.sectionTitle","settings.general.uploads.maxUploadSize","settings.general.resetPreferences.sectionTitle",diff --git a/studio/frontend/src/features/settings/tabs/general-tab.tsx b/studio/frontend/src/features/settings/tabs/general-tab.tsxindex 1b655e66709..7bb60219a3f 100644--- a/studio/frontend/src/features/settings/tabs/general-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/general-tab.tsx@@ -65,6 +65,8 @@ 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 { DownloadTransportRow } from "../components/download-transport-row";import { SettingsRow } from "../components/settings-row";import { SettingsSection } from "../components/settings-section";import { StudioVersionSection } from "../components/studio-version-section";@@ -95,6 +97,9 @@ const PREFS_KEYS: string[] = [// asked to throw away, and a chord bound to something unusable has no// escape hatch from this button.KEYBOARD_SHORTCUTS_STORAGE_KEY,+ // Outranks the install-wide setting, so a reset that left it behind would keep ignoring+ // transport changes made elsewhere.+ TRANSPORT_MODE_STORAGE_KEY,// Chat runtime prefsCHAT_PROJECT_ATTACHMENT_TARGET_KEY,"unsloth_chat_auto_title",@@ -631,6 +636,10 @@ export function GeneralTab() {<DocumentsRagSection />+ <SettingsSection title={t("settings.general.downloads.sectionTitle")}>+ <DownloadTransportRow />+ </SettingsSection>+<SettingsSection title={t("settings.general.uploads.sectionTitle")}><SettingsRowlabel={t("settings.general.uploads.maxUploadSize")}diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex af4ee8b5315..9b635177ec1 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -573,6 +573,29 @@ export const ar = {loadError: "تعذر تحميل إعداد التشغيل عند تسجيل الدخول.",saveError: "تعذر تحديث إعداد التشغيل عند تسجيل الدخول.",},+ downloads: {+ sectionTitle: "التنزيلات",+ transport: "طريقة نقل التنزيل",+ transportDescription:+ "كيف تصل ملفات النماذج ومجموعات البيانات من Hugging Face. يتابع HTTPS من حيث توقف، أما Xet فغالبًا أسرع في التنزيل الأول لكنه يبدأ الملف من جديد إذا ألغيت.",+ transportHint:+ "HTTPS هو TLS عادي: تسمح به كل الشبكات والوكلاء وشبكات VPN، ويتابع النقل الملغى أو المنقطع من البايتات الموجودة على القرص، ويبقى استخدام الذاكرة ثابتًا. يجلب Xet كتلاً منزوعة التكرار، فيمكن أن يصل مستودع يشترك في بيانات مع مستودع لديك أسرع بكثير، لكنه يحتاج hf_xet ويستهلك ذاكرة أكبر، والإلغاء يتخلص من الملف الجاري. يقرر Auto حسب هذا الجهاز: يوازن الذاكرة وما إذا كان Xet قد تعطل هنا، ويعود إلى HTTPS عند الحاجة.",+ https: "HTTPS",+ xet: "Xet",+ auto: "Auto",+ httpsHint:+ "TLS قياسي. يتابع بعد الإلغاء، ويعمل على أي شبكة، واستخدام ذاكرة ثابت.",+ transportDescriptionNoResume:+ "كيفية تنزيل ملفات النماذج ومجموعات البيانات من Hugging Face. لا يمكن لأي من وسيلتي النقل الاستئناف في هذا التثبيت، لذا يبدأ التنزيل الملغى من جديد؛ وغالبًا ما يكون Xet أسرع في التنزيل الأول.",+ httpsHintNoResume:+ "TLS قياسي. يعمل على أي شبكة مع استخدام ثابت للذاكرة. لا يمكن لهذا التثبيت استئناف تنزيل ملغى.",+ xetHint:+ "نقل بكتل منزوعة التكرار. أسرع غالبًا في التنزيل الجديد، ويبدأ الملف من جديد عند الإلغاء، ويحتاج ذاكرة أكبر.",+ autoHint:+ "يختار حسب الجهاز وينتقل إلى HTTPS إذا تعطل Xet أو فشل هنا.",+ autoCurrently: "يستخدم Auto على هذا الجهاز {transport}.",+ xetMissing: "Xet غير متاح لأن hf_xet غير مثبت.",+ },uploads: {sectionTitle: "عمليات الرفع",maxUploadSize: "الحد الأقصى لحجم رفع مجموعة بيانات التدريب",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex 516a3831dd6..e37d2c505f6 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -594,6 +594,29 @@ export const de = {saveError:"Die Autostart-Einstellung konnte nicht aktualisiert werden.",},+ downloads: {+ sectionTitle: "Downloads",+ transport: "Download-Transport",+ transportDescription:+ "Wie Modell- und Datensatzdateien von Hugging Face geladen werden. HTTPS setzt an der Abbruchstelle fort; Xet ist beim ersten Download oft schneller, beginnt die Datei nach einem Abbruch aber neu.",+ transportHint:+ "HTTPS ist einfaches TLS: jedes Netzwerk, jeder Proxy und jedes VPN erlaubt es, ein abgebrochener Transfer setzt bei den bereits gespeicherten Bytes fort und der Speicherbedarf bleibt konstant. Xet lädt deduplizierte Blöcke, wodurch ein Repo mit bereits vorhandenen Daten viel schneller ankommt, benötigt aber hf_xet, mehr RAM, und ein Abbruch verwirft die laufende Datei. Auto entscheidet pro Rechner: es bewertet RAM und ob Xet hier ins Stocken gerät, und fällt auf HTTPS zurück.",+ https: "HTTPS",+ xet: "Xet",+ auto: "Auto",+ httpsHint:+ "Standard-TLS. Setzt nach einem Abbruch fort, funktioniert in jedem Netzwerk, gleichmäßiger Speicherbedarf.",+ transportDescriptionNoResume:+ "Wie Modell- und Datensatzdateien von Hugging Face geladen werden. Auf dieser Installation kann kein Transport fortsetzen, ein abgebrochener Download beginnt also neu; Xet ist beim ersten Download oft schneller.",+ httpsHintNoResume:+ "Standard-TLS. Funktioniert in jedem Netzwerk, gleichmäßiger Speicherbedarf. Diese Installation kann einen abgebrochenen Download nicht fortsetzen.",+ xetHint:+ "Deduplizierte Blockübertragung. Beim ersten Download oft schneller, beginnt die Datei nach einem Abbruch neu, braucht mehr Speicher.",+ autoHint:+ "Wählt pro Rechner und wechselt zu HTTPS, wenn Xet hier stockt oder fehlschlägt.",+ autoCurrently: "Auto verwendet auf diesem Rechner {transport}.",+ xetMissing: "Xet ist nicht verfügbar, da hf_xet nicht installiert ist.",+ },uploads: {sectionTitle: "Uploads",maxUploadSize: "Upload-Limit für Trainingsdatensätze",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 3c883dba2d1..cfefe32ec83 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -574,6 +574,29 @@ export const en = {loadError: "Failed to load the launch at login setting.",saveError: "Failed to update the launch at login setting.",},+ downloads: {+ sectionTitle: "Downloads",+ transport: "Download transport",+ transportDescription:+ "How model and dataset files come down from Hugging Face. HTTPS resumes where it stopped; Xet is often faster on a first download but starts the file again if you cancel.",+ transportHint:+ "HTTPS is plain TLS: every network, proxy and VPN allows it, a cancelled or dropped transfer resumes from the bytes already on disk, and memory use stays flat. Xet fetches deduplicated chunks, so a repo sharing data with one you already have can arrive much faster, but it needs hf_xet, uses more RAM, and a cancel discards the file in flight. Auto asks this machine: it weighs RAM and whether Xet has been stalling here, and falls back to HTTPS.",+ https: "HTTPS",+ xet: "Xet",+ auto: "Auto",+ httpsHint:+ "Standard TLS. Resumes after a cancel, works on any network, steady memory use.",+ transportDescriptionNoResume:+ "How model and dataset files come down from Hugging Face. Neither transport can resume on this install, so a cancelled download starts again; Xet is often faster on a first download.",+ httpsHintNoResume:+ "Standard TLS. Works on any network, steady memory use. This install cannot resume a cancelled download.",+ xetHint:+ "Deduplicated chunk transfer. Often faster on a fresh download, restarts the file if you cancel, needs more memory.",+ autoHint:+ "Picks per machine and switches to HTTPS if Xet stalls or fails here.",+ autoCurrently: "Auto is using {transport} on this machine.",+ xetMissing: "Xet is unavailable because hf_xet is not installed.",+ },uploads: {sectionTitle: "Uploads",maxUploadSize: "Training dataset upload cap",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex aa110dfe5ad..8a502cf05e3 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -589,6 +589,29 @@ export const es = {loadError: "No se pudo cargar el ajuste de inicio automático.",saveError: "No se pudo actualizar el ajuste de inicio automático.",},+ downloads: {+ sectionTitle: "Descargas",+ transport: "Transporte de descarga",+ transportDescription:+ "Cómo llegan los archivos de modelos y conjuntos de datos desde Hugging Face. HTTPS retoma donde se detuvo; Xet suele ser más rápido en la primera descarga, pero reinicia el archivo si cancelas.",+ transportHint:+ "HTTPS es TLS normal: cualquier red, proxy o VPN lo permite, una transferencia cancelada o cortada continúa desde los bytes ya guardados y el uso de memoria se mantiene estable. Xet descarga bloques deduplicados, así que un repositorio que comparte datos con otro que ya tienes puede llegar mucho más rápido, pero necesita hf_xet, usa más RAM y una cancelación descarta el archivo en curso. Auto decide según la máquina: valora la RAM y si Xet se ha estado atascando aquí, y recurre a HTTPS.",+ https: "HTTPS",+ xet: "Xet",+ auto: "Auto",+ httpsHint:+ "TLS estándar. Retoma tras una cancelación, funciona en cualquier red, uso de memoria estable.",+ transportDescriptionNoResume:+ "Cómo se descargan los archivos de modelos y conjuntos de datos desde Hugging Face. En esta instalación ningún transporte puede reanudarse, así que una descarga cancelada vuelve a empezar; Xet suele ser más rápido en la primera descarga.",+ httpsHintNoResume:+ "TLS estándar. Funciona en cualquier red, uso de memoria estable. Esta instalación no puede reanudar una descarga cancelada.",+ xetHint:+ "Transferencia por bloques deduplicados. Suele ser más rápida en una descarga nueva, reinicia el archivo si cancelas y necesita más memoria.",+ autoHint:+ "Elige según la máquina y cambia a HTTPS si Xet se atasca o falla aquí.",+ autoCurrently: "Auto está usando {transport} en esta máquina.",+ xetMissing: "Xet no está disponible porque hf_xet no está instalado.",+ },uploads: {sectionTitle: "Subidas",maxUploadSize: "Límite de subida del conjunto de datos de entrenamiento",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex 9e0d48e42bb..e92dd658a5d 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -593,6 +593,29 @@ export const fr = {saveError:"Impossible de mettre à jour le réglage de lancement à la connexion.",},+ downloads: {+ sectionTitle: "Téléchargements",+ transport: "Transport de téléchargement",+ transportDescription:+ "Comment les fichiers de modèles et de jeux de données arrivent depuis Hugging Face. HTTPS reprend là où il s'est arrêté ; Xet est souvent plus rapide au premier téléchargement mais recommence le fichier en cas d'annulation.",+ transportHint:+ "HTTPS, c'est du TLS classique : tous les réseaux, proxys et VPN l'autorisent, un transfert annulé ou coupé reprend à partir des octets déjà écrits et la mémoire reste stable. Xet récupère des blocs dédupliqués, donc un dépôt partageant des données avec un autre déjà présent peut arriver bien plus vite, mais il exige hf_xet, consomme plus de RAM, et une annulation jette le fichier en cours. Auto décide selon la machine : il pèse la RAM et les blocages récents de Xet ici, puis se rabat sur HTTPS.",+ https: "HTTPS",+ xet: "Xet",+ auto: "Auto",+ httpsHint:+ "TLS standard. Reprend après une annulation, fonctionne sur tous les réseaux, mémoire stable.",+ transportDescriptionNoResume:+ "Comment les fichiers de modèles et de jeux de données sont téléchargés depuis Hugging Face. Sur cette installation, aucun transport ne peut reprendre : un téléchargement annulé recommence ; Xet est souvent plus rapide au premier téléchargement.",+ httpsHintNoResume:+ "TLS standard. Fonctionne sur tous les réseaux, consommation mémoire stable. Cette installation ne peut pas reprendre un téléchargement annulé.",+ xetHint:+ "Transfert par blocs dédupliqués. Souvent plus rapide sur un premier téléchargement, recommence le fichier si vous annulez, demande plus de mémoire.",+ autoHint:+ "Choisit selon la machine et passe à HTTPS si Xet se bloque ou échoue ici.",+ autoCurrently: "Auto utilise {transport} sur cette machine.",+ xetMissing: "Xet est indisponible car hf_xet n'est pas installé.",+ },uploads: {sectionTitle: "Téléversements",maxUploadSize: "Limite de téléversement du jeu de données d'entraînement",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 2ee6330a5fc..9a56c62f43e 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -576,6 +576,29 @@ export const hi = {loadError: "लॉगिन पर चलाने की सेटिंग लोड नहीं हो सकी।",saveError: "लॉगिन पर चलाने की सेटिंग अपडेट नहीं हो सकी।",},+ downloads: {+ sectionTitle: "डाउनलोड",+ transport: "डाउनलोड ट्रांसपोर्ट",+ transportDescription:+ "Hugging Face से मॉडल और डेटासेट फ़ाइलें कैसे आती हैं। HTTPS वहीं से जारी रहता है जहाँ रुका था; Xet पहली बार डाउनलोड में अक्सर तेज़ होता है, लेकिन रद्द करने पर फ़ाइल फिर से शुरू करता है।",+ transportHint:+ "HTTPS सामान्य TLS है: हर नेटवर्क, प्रॉक्सी और VPN इसे चलने देता है, रद्द या टूटा ट्रांसफ़र डिस्क पर मौजूद बाइट्स से जारी रहता है, और मेमोरी उपयोग स्थिर रहता है। Xet डीडुप्लिकेट किए गए चंक लाता है, इसलिए जिस रिपॉज़िटरी का डेटा आपके पास पहले से है वह बहुत तेज़ आ सकती है, पर इसके लिए hf_xet चाहिए, RAM ज़्यादा लगती है, और रद्द करने पर चल रही फ़ाइल छूट जाती है। Auto इस मशीन के हिसाब से तय करता है: यह RAM और यहाँ Xet के अटकने को देखता है, और ज़रूरत पर HTTPS पर लौट आता है।",+ https: "HTTPS",+ xet: "Xet",+ auto: "Auto",+ httpsHint:+ "मानक TLS। रद्द करने के बाद जारी रहता है, हर नेटवर्क पर चलता है, मेमोरी उपयोग स्थिर।",+ transportDescriptionNoResume:+ "मॉडल और डेटासेट फ़ाइलें Hugging Face से कैसे आती हैं। इस इंस्टॉलेशन में कोई भी ट्रांसपोर्ट डाउनलोड फिर से शुरू नहीं कर सकता, इसलिए रद्द किया गया डाउनलोड शुरू से चलता है; पहली बार डाउनलोड करने में Xet अक्सर तेज़ होता है।",+ httpsHintNoResume:+ "मानक TLS। किसी भी नेटवर्क पर काम करता है, मेमोरी का उपयोग स्थिर रहता है। यह इंस्टॉलेशन रद्द किए गए डाउनलोड को फिर से शुरू नहीं कर सकता।",+ xetHint:+ "डीडुप्लिकेट चंक ट्रांसफ़र। नए डाउनलोड में अक्सर तेज़, रद्द करने पर फ़ाइल फिर से शुरू, ज़्यादा मेमोरी चाहिए।",+ autoHint:+ "मशीन के अनुसार चुनता है और यहाँ Xet अटकने या विफल होने पर HTTPS पर चला जाता है।",+ autoCurrently: "इस मशीन पर Auto {transport} उपयोग कर रहा है।",+ xetMissing: "hf_xet इंस्टॉल नहीं है, इसलिए Xet उपलब्ध नहीं है।",+ },uploads: {sectionTitle: "अपलोड",maxUploadSize: "ट्रेनिंग डेटासेट अपलोड सीमा",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex 073f679b05b..e66a273a485 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -565,6 +565,29 @@ export const it = {saveError:"Impossibile aggiornare l'impostazione di avvio all'accesso.",},+ downloads: {+ sectionTitle: "Download",+ transport: "Trasporto di download",+ transportDescription:+ "Come arrivano i file di modelli e dataset da Hugging Face. HTTPS riprende da dove si è fermato; Xet è spesso più veloce al primo download ma ricomincia il file se annulli.",+ transportHint:+ "HTTPS è normale TLS: ogni rete, proxy e VPN lo consente, un trasferimento annullato o interrotto riprende dai byte già su disco e l'uso di memoria resta costante. Xet scarica blocchi deduplicati, quindi un repository che condivide dati con uno che hai già può arrivare molto più rapidamente, ma richiede hf_xet, usa più RAM e un annullamento scarta il file in corso. Auto decide per macchina: valuta la RAM e se Xet si è bloccato qui, e ripiega su HTTPS.",+ https: "HTTPS",+ xet: "Xet",+ auto: "Auto",+ httpsHint:+ "TLS standard. Riprende dopo un annullamento, funziona su qualsiasi rete, memoria costante.",+ transportDescriptionNoResume:+ "Come i file di modelli e dataset vengono scaricati da Hugging Face. In questa installazione nessun trasporto può riprendere, quindi un download annullato ricomincia; Xet è spesso più veloce al primo download.",+ httpsHintNoResume:+ "TLS standard. Funziona con qualsiasi rete, uso di memoria costante. Questa installazione non può riprendere un download annullato.",+ xetHint:+ "Trasferimento a blocchi deduplicati. Spesso più veloce su un download nuovo, ricomincia il file se annulli, richiede più memoria.",+ autoHint:+ "Sceglie in base alla macchina e passa a HTTPS se Xet si blocca o fallisce qui.",+ autoCurrently: "Auto sta usando {transport} su questa macchina.",+ xetMissing: "Xet non è disponibile perché hf_xet non è installato.",+ },uploads: {sectionTitle: "Caricamenti",maxUploadSize: "Limite di caricamento del dataset di addestramento",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex 74b8c42df8a..2319f446bd3 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -563,6 +563,29 @@ export const ja = {loadError: "ログイン時起動の設定を読み込めませんでした。",saveError: "ログイン時起動の設定を更新できませんでした。",},+ downloads: {+ sectionTitle: "ダウンロード",+ transport: "ダウンロード方式",+ transportDescription:+ "Hugging Face からモデルやデータセットのファイルを取得する方法です。HTTPS は中断した位置から再開します。Xet は初回ダウンロードでは速いことが多い一方、キャンセルするとそのファイルを最初からやり直します。",+ transportHint:+ "HTTPS は通常の TLS です。あらゆるネットワーク、プロキシ、VPN が許可し、キャンセルや切断があってもディスク上のバイト列から再開でき、メモリ使用量も一定です。Xet は重複排除されたチャンクを取得するため、既に持っているリポジトリとデータを共有する場合は大幅に速く届きますが、hf_xet が必要で RAM を多く使い、キャンセルすると転送中のファイルは破棄されます。Auto はこのマシンに合わせて判断し、RAM や Xet がここで停滞していないかを見て、必要なら HTTPS に切り替えます。",+ https: "HTTPS",+ xet: "Xet",+ auto: "Auto",+ httpsHint:+ "標準の TLS。キャンセル後も再開でき、どのネットワークでも動作し、メモリ使用量が安定します。",+ transportDescriptionNoResume:+ "モデルやデータセットのファイルを Hugging Face から取得する方法です。このインストールではどちらの転送方式も再開できないため、キャンセルしたダウンロードは最初からやり直しになります。Xet は初回のダウンロードが速いことが多いです。",+ httpsHintNoResume:+ "標準の TLS。どのネットワークでも動作し、メモリ使用量は安定しています。このインストールではキャンセルしたダウンロードを再開できません。",+ xetHint:+ "重複排除チャンク転送。新規ダウンロードでは速いことが多く、キャンセルするとファイルをやり直し、メモリを多く使います。",+ autoHint:+ "マシンごとに選び、ここで Xet が停滞または失敗した場合は HTTPS に切り替えます。",+ autoCurrently: "このマシンでは Auto は {transport} を使用しています。",+ xetMissing: "hf_xet がインストールされていないため Xet は利用できません。",+ },uploads: {sectionTitle: "アップロード",maxUploadSize: "トレーニングデータセットのアップロード容量制限",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex 2556b70a6f3..c6c1100c712 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -570,6 +570,29 @@ export const ko = {loadError: "로그인 시 실행 설정을 불러오지 못했습니다.",saveError: "로그인 시 실행 설정을 업데이트하지 못했습니다.",},+ downloads: {+ sectionTitle: "다운로드",+ transport: "다운로드 전송 방식",+ transportDescription:+ "Hugging Face에서 모델과 데이터셋 파일을 받아오는 방식입니다. HTTPS는 멈춘 지점부터 이어받고, Xet은 첫 다운로드에서 더 빠른 편이지만 취소하면 해당 파일을 처음부터 다시 받습니다.",+ transportHint:+ "HTTPS는 일반 TLS입니다. 모든 네트워크와 프록시, VPN이 허용하며 취소되거나 끊긴 전송도 디스크에 남은 바이트부터 이어받고 메모리 사용량이 일정합니다. Xet은 중복 제거된 청크를 받아오므로 이미 가진 저장소와 데이터를 공유하면 훨씬 빠르게 도착하지만 hf_xet이 필요하고 RAM을 더 쓰며, 취소하면 진행 중인 파일이 버려집니다. Auto는 이 머신에 맞춰 판단해 RAM과 Xet이 여기서 멈춘 적이 있는지를 따지고 필요하면 HTTPS로 물러납니다.",+ https: "HTTPS",+ xet: "Xet",+ auto: "Auto",+ httpsHint:+ "표준 TLS. 취소 후에도 이어받고 어떤 네트워크에서도 동작하며 메모리 사용이 안정적입니다.",+ transportDescriptionNoResume:+ "모델과 데이터셋 파일을 Hugging Face에서 내려받는 방식입니다. 이 설치에서는 두 전송 방식 모두 이어받기를 할 수 없어 취소한 다운로드는 처음부터 다시 시작합니다. Xet은 첫 다운로드에서 더 빠른 경우가 많습니다.",+ httpsHintNoResume:+ "표준 TLS. 모든 네트워크에서 동작하며 메모리 사용량이 일정합니다. 이 설치에서는 취소한 다운로드를 이어받을 수 없습니다.",+ xetHint:+ "중복 제거 청크 전송. 새 다운로드에서 더 빠른 편이지만 취소하면 파일을 다시 받고 메모리를 더 씁니다.",+ autoHint:+ "머신에 맞춰 고르고, 여기서 Xet이 멈추거나 실패하면 HTTPS로 바꿉니다.",+ autoCurrently: "이 머신에서 Auto는 {transport}을 사용합니다.",+ xetMissing: "hf_xet이 설치되지 않아 Xet을 사용할 수 없습니다.",+ },uploads: {sectionTitle: "업로드",maxUploadSize: "학습 데이터셋 업로드 상한",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex f353439a241..f34e85f4838 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -582,6 +582,29 @@ export const ptBR = {saveError:"Não foi possível atualizar a configuração de inicialização no login.",},+ downloads: {+ sectionTitle: "Downloads",+ transport: "Transporte de download",+ transportDescription:+ "Como os arquivos de modelos e datasets chegam do Hugging Face. HTTPS continua de onde parou; Xet costuma ser mais rápido no primeiro download, mas reinicia o arquivo se você cancelar.",+ transportHint:+ "HTTPS é TLS comum: qualquer rede, proxy e VPN permite, uma transferência cancelada ou interrompida continua dos bytes já gravados e o uso de memória fica estável. O Xet busca blocos deduplicados, então um repositório que compartilha dados com outro que você já tem pode chegar muito mais rápido, mas ele exige hf_xet, usa mais RAM e um cancelamento descarta o arquivo em andamento. Auto decide por máquina: pesa a RAM e se o Xet tem travado aqui, e recorre ao HTTPS.",+ https: "HTTPS",+ xet: "Xet",+ auto: "Auto",+ httpsHint:+ "TLS padrão. Continua após um cancelamento, funciona em qualquer rede, memória estável.",+ transportDescriptionNoResume:+ "Como os arquivos de modelos e conjuntos de dados são baixados do Hugging Face. Nesta instalação nenhum transporte pode retomar, então um download cancelado recomeça; o Xet costuma ser mais rápido no primeiro download.",+ httpsHintNoResume:+ "TLS padrão. Funciona em qualquer rede, uso de memória estável. Esta instalação não consegue retomar um download cancelado.",+ xetHint:+ "Transferência por blocos deduplicados. Costuma ser mais rápida num download novo, reinicia o arquivo se você cancelar, precisa de mais memória.",+ autoHint:+ "Escolhe por máquina e muda para HTTPS se o Xet travar ou falhar aqui.",+ autoCurrently: "O Auto está usando {transport} nesta máquina.",+ xetMissing: "O Xet está indisponível porque o hf_xet não está instalado.",+ },uploads: {sectionTitle: "Uploads",maxUploadSize: "Limite de upload do dataset de treino",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 428ae670b34..c545d354d7c 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -577,6 +577,29 @@ export const ru = {loadError: "Не удалось загрузить настройку автозапуска.",saveError: "Не удалось обновить настройку автозапуска.",},+ downloads: {+ sectionTitle: "Загрузки",+ transport: "Транспорт загрузки",+ transportDescription:+ "Как файлы моделей и наборов данных приходят с Hugging Face. HTTPS продолжает с места остановки; Xet часто быстрее при первой загрузке, но начинает файл заново после отмены.",+ transportHint:+ "HTTPS - это обычный TLS: его пропускают любые сети, прокси и VPN, отменённая или оборванная передача продолжается с уже сохранённых байтов, а расход памяти остаётся ровным. Xet скачивает дедуплицированные блоки, поэтому репозиторий, у которого есть общие данные с уже скачанным, может прийти намного быстрее, но ему нужен hf_xet и больше ОЗУ, а отмена отбрасывает текущий файл. Auto решает для конкретной машины: учитывает ОЗУ и то, зависал ли здесь Xet, и переходит на HTTPS.",+ https: "HTTPS",+ xet: "Xet",+ auto: "Auto",+ httpsHint:+ "Стандартный TLS. Продолжает после отмены, работает в любой сети, ровный расход памяти.",+ transportDescriptionNoResume:+ "Как файлы моделей и наборов данных загружаются с Hugging Face. В этой установке ни один транспорт не может продолжить загрузку, поэтому отменённая загрузка начинается заново; Xet обычно быстрее при первой загрузке.",+ httpsHintNoResume:+ "Обычный TLS. Работает в любой сети, стабильное использование памяти. Эта установка не может продолжить отменённую загрузку.",+ xetHint:+ "Передача дедуплицированными блоками. Обычно быстрее при первой загрузке, начинает файл заново после отмены, требует больше памяти.",+ autoHint:+ "Выбирает для этой машины и переключается на HTTPS, если Xet зависает или падает.",+ autoCurrently: "Auto использует {transport} на этой машине.",+ xetMissing: "Xet недоступен, так как hf_xet не установлен.",+ },uploads: {sectionTitle: "Загрузки",maxUploadSize: "Лимит загрузки датасета для обучения",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex f2fe139ef1f..d088b29db0c 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -555,6 +555,27 @@ export const zhCN = {loadError: "无法加载登录时启动设置。",saveError: "无法更新登录时启动设置。",},+ downloads: {+ sectionTitle: "下载",+ transport: "下载传输方式",+ transportDescription:+ "模型和数据集文件从 Hugging Face 下载的方式。HTTPS 会从中断处续传;Xet 首次下载通常更快,但取消后该文件会重新开始。",+ transportHint:+ "HTTPS 就是普通 TLS:任何网络、代理和 VPN 都允许,取消或断开的传输会从磁盘上已有的字节续传,内存占用也很平稳。Xet 获取去重后的数据块,因此与已有仓库共享数据时可以快得多,但它需要 hf_xet、占用更多内存,取消时会丢弃正在传输的文件。Auto 会针对本机判断:它会权衡内存以及 Xet 在这里是否曾经卡住,并在必要时退回 HTTPS。",+ https: "HTTPS",+ xet: "Xet",+ auto: "Auto",+ httpsHint: "标准 TLS。取消后可续传,适用于任何网络,内存占用稳定。",+ transportDescriptionNoResume:+ "模型和数据集文件从 Hugging Face 下载的方式。此安装的两种传输方式都无法续传,取消后的下载会重新开始;Xet 在首次下载时通常更快。",+ httpsHintNoResume:+ "标准 TLS。可在任何网络下使用,内存占用平稳。此安装无法续传已取消的下载。",+ xetHint:+ "去重数据块传输。首次下载通常更快,取消后文件重新开始,需要更多内存。",+ autoHint: "按本机情况选择,若 Xet 在这里卡住或失败则切换到 HTTPS。",+ autoCurrently: "本机上 Auto 正在使用 {transport}。",+ xetMissing: "未安装 hf_xet,因此无法使用 Xet。",+ },uploads: {sectionTitle: "上传",maxUploadSize: "训练数据集上传上限",diff --git a/studio/frontend/tests/download-transport-setting.test.ts b/studio/frontend/tests/download-transport-setting.test.tsnew file mode 100644index 00000000000..1087511da38--- /dev/null+++ b/studio/frontend/tests/download-transport-setting.test.ts@@ -0,0 +1,285 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// The transport choice was a Hub-page toggle living in one browser; it is a Settings > General+// row saved for the install now. Pinned here: this browser's own choice wins, the install's+// setting is next, the default is still Auto, and the row spells out the difference.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";++import { registerBundlerResolver } from "./helpers/kit.ts";++registerBundlerResolver();++const { DEFAULT_TRANSPORT_MODE, TRANSPORT, pickTransportMode } = await import(+ "../src/features/hub/download-manager/constants.ts"+);++function read(path: string): string {+ return readFileSync(new URL(`../src/${path}`, import.meta.url), "utf8");+}++const ROW = read("features/settings/components/download-transport-row.tsx");+const PREFERENCE = read(+ "features/hub/download-manager/transport-preference.ts",+);+const GENERAL_TAB = read("features/settings/tabs/general-tab.tsx");+const TOGGLE = read("features/hub/catalog/transport-toggle.tsx");+const API = read("features/settings/api/download-transport.ts");+const POLL_LOOP = read("features/hub/download-manager/poll-loop.ts");+const SEARCH = read("features/settings/settings-search.ts");+const GENERAL_TAB_SRC = read("features/settings/tabs/general-tab.tsx");+const EN = read("i18n/locales/en.ts");++test("this browser's own choice beats the install setting", () => {+ assert.equal(pickTransportMode("xet", "http"), TRANSPORT.XET);+ assert.equal(pickTransportMode("http", "auto"), TRANSPORT.HTTP);+ assert.equal(pickTransportMode("auto", "http"), TRANSPORT.AUTO);+});++test("with no choice of its own the install setting decides", () => {+ // Someone who picked a transport in Settings gets it in a browser that has never chosen.+ assert.equal(pickTransportMode(null, "auto"), TRANSPORT.AUTO);+ assert.equal(pickTransportMode(null, "xet"), TRANSPORT.XET);+ assert.equal(pickTransportMode(undefined, "http"), TRANSPORT.HTTP);+});++test("junk on either side leaves the default alone", () => {+ // Auto, as before this row existed: a new setting must not move an untouched install.+ assert.equal(pickTransportMode("ftp", "torrent"), TRANSPORT.AUTO);+ assert.equal(pickTransportMode(null, null), DEFAULT_TRANSPORT_MODE);+ assert.equal(DEFAULT_TRANSPORT_MODE, TRANSPORT.AUTO);+});++test("a download waits for the install setting before picking a transport", () => {+ // getTransportMode() answers from what is known, so reading it before the settings fetch+ // landed missed a transport picked in another browser.+ for (const source of [+ read("features/hub/download-manager/poll-loop.ts"),+ read("features/hub/download-manager/transport-conflict.ts"),+ ]) {+ assert.match(source, /await resolveTransportMode\(\)/);+ assert.ok(+ !/[^a-zA-Z]getTransportMode\(\)/.test(source),+ "a download start reads the preference without waiting for it",+ );+ }+});++test("choosing a transport saves it for the install too", () => {+ // Otherwise the same install in another browser keeps the old transport.+ assert.match(PREFERENCE, /updateDownloadTransportSettings\(next\)/);+ // The local write still comes first: it is what this browser's downloads read.+ assert.ok(+ PREFERENCE.indexOf("localStorage.setItem") <+ PREFERENCE.indexOf("updateDownloadTransportSettings(next)"),+ );+});++test("the General tab carries the transport row", () => {+ assert.match(GENERAL_TAB, /<DownloadTransportRow \/>/);+ assert.match(GENERAL_TAB, /settings\.general\.downloads\.sectionTitle/);+});++test("the row offers HTTPS and Xet, and says which one is in force", () => {+ for (const key of ["downloads.https", "downloads.xet", "downloads.auto"]) {+ assert.ok(ROW.includes(key), `${key} is missing from the row`);+ }+ // Xet with no hf_xet is shown as unavailable rather than silently downloading over HTTPS.+ assert.match(ROW, /xetAvailable === false/);+ assert.match(ROW, /autoResolvesTo/);+});++test("the copy explains the difference, not just the names", () => {+ const downloads = EN.slice(+ EN.indexOf(" downloads: {"),+ EN.indexOf(" uploads: {"),+ );+ assert.ok(downloads.length > 0, "the downloads copy moved");+ // Resuming and the cancel behaviour are the practical difference between the two.+ assert.match(downloads, /resumes/i);+ assert.match(downloads, /cancel/i);+ assert.match(downloads, /hf_xet/);+});+++// The four below are source assertions, in this file's idiom: they pin the shape of a fix+// rather than its behaviour, so each names the failure it exists for.++test("the Hub's automatic fallback is not stored at all", () => {+ // TransportToggle drops a stored "xet" to "http" when hf_xet is missing. Written install-wide+ // that replaced everyone's choice; written locally it outranked the install setting and+ // survived hf_xet being repaired.+ assert.match(TOGGLE, /setMode\("http",\s*\{\s*persist:\s*false\s*\}\)/);+ assert.match(PREFERENCE, /opts\.persist === false/);+ // Reflected and returned BEFORE either write.+ const setter = PREFERENCE.slice(PREFERENCE.indexOf("const set = useCallback"));+ assert.ok(+ setter.indexOf("opts.persist === false") < setter.indexOf("localStorage.setItem"),+ "the persist opt-out must be checked before the local write",+ );+});++test("a download re-reads the install setting instead of trusting the cache", () => {+ // Another browser can change it, and a value cached for the life of the tab kept downloading+ // on the old transport until a reload.+ assert.match(PREFERENCE, /hydrateInstallMode\(true\)/);+ assert.match(API, /opts\.refresh/);+});++test("install-wide writes are serialized", () => {+ // Two quick selections raced: the earlier PUT landing last left the database on the mode the+ // user did not pick while this browser showed the one they did.+ assert.match(API, /writeQueue/);+ assert.match(API, /writeQueue\s*=\s*next\.catch/);+});++test("the copy stops promising a resume the install cannot do", () => {+ // huggingface_hub 1.18 refetches an interrupted transfer from zero, so someone picking HTTPS+ // to keep their progress was told the opposite.+ assert.match(ROW, /useHttpPartialsResumable\(\)/);+ assert.match(ROW, /transportDescriptionNoResume/);+ assert.match(ROW, /httpsHintNoResume/);+ assert.match(EN, /transportDescriptionNoResume/);+ assert.match(EN, /httpsHintNoResume/);+});++test("the Xet-missing reason is the translated one", () => {+ // The backend's one reason is English prose, and preferring it made the translated key+ // unreachable for every other locale.+ assert.match(ROW, /hf_xet is not installed/);+ assert.match(ROW, /t\("settings\.general\.downloads\.xetMissing"\)/);+});++test("a blocked localStorage still saves the setting for the install", () => {+ // Private mode, disabled storage and over quota used to return before the server write, so+ // those browsers could not change the transport at all.+ assert.match(PREFERENCE, /savedLocally/);+ assert.doesNotMatch(+ PREFERENCE,+ /catch \{\s*toast\.error\("Couldn't save the download transport preference\."\);\s*return;/,+ );+});++test("the untranslated health reason is not folded into a translated sentence", () => {+ // settings.autoReason is free-form English, and interpolating it gave other locales half a+ // sentence in each language. It has its own line now, and the key that folded it in is gone.+ assert.match(ROW, /statusReason/);+ assert.doesNotMatch(ROW, /autoCurrentlyReason/);+ assert.doesNotMatch(EN, /autoCurrentlyReason/);+});++test("a failed refresh keeps the install mode already loaded", () => {+ // Falling back to null sent the next download to Auto even though the install's choice was+ // still known here, so a blip on the settings route silently changed transport.+ assert.match(PREFERENCE, /installMode === null && superseded \? superseded : installMode/);+});++test("a failed refresh waits for the hydration it overtook", () => {+ // A download started before the first hydration answers overtakes it, and answering null+ // when the refresh fails ran on Auto while the install's real choice was still on its way.+ assert.match(PREFERENCE, /const superseded = refresh \? installModeInFlight : null;/);+});++test("adopting an existing job does not wait on the settings route", () => {+ // The adopt branch ignores requestedMode, and suspending there let the two concurrent+ // adoptJob callers replace each other's runtime and leave duplicate poll timers.+ assert.match(POLL_LOOP, /opts\.adopt\s*\n?\s*\? TRANSPORT\.HTTP/);+});++test("Xet cannot be chosen before its availability is known", () => {+ // Clicking it in that window stored a Xet preference every later download silently ignored.+ assert.match(ROW, /capabilityPending \|\| settings\?\.xetAvailable === false/);+ // But a load that FAILED must not disable it for good, so pending is its own state.+ assert.match(ROW, /setCapabilityPending\(false\)/);+});++test("a failed install-wide write is reported, not just logged", () => {+ // The row calls this setting install-wide, so a local-only save is a mismatch nobody can+ // otherwise see.+ assert.match(PREFERENCE, /Saved for this browser, but not for this install\./);+});++test("the transport row is reachable from Settings search", () => {+ // It moved here because nobody found it on the Hub, so an unindexed row leaves searches for+ // "transport", "Xet" or "HTTPS" finding nothing.+ for (const key of [+ "settings.general.downloads.sectionTitle",+ "settings.general.downloads.transport",+ "settings.general.downloads.https",+ "settings.general.downloads.xet",+ ]) {+ assert.ok(SEARCH.includes(key), `search index is missing ${key}`);+ }+});++test("a refresh does not ride on a request that predates it", () => {+ // A hydration GET still pending here may already have been answered with the old mode, so+ // sharing it hands back exactly the value the refresh went to replace.+ assert.match(API, /inFlightIsRefresh/);+ assert.match(API, /!opts\.refresh \|\| inFlightIsRefresh/);+ // And the older of two overlapping responses must not land last and re-cache the old value.+ assert.match(API, /request === latestRequest/);+});++test("the Hub toggle also waits to know whether Xet can run", () => {+ // Same window as the settings row: clicking Xet before the capability lands stored it on a+ // machine that cannot run it.+ assert.match(TOGGLE, /const xetUnavailable = isLoading \|\| xetKnownUnavailable/);+});++test("each indexed option has somewhere for search to scroll to", () => {+ // An indexed label with no data-settings-label produces a result that opens General and+ // then fails to find anything.+ assert.match(ROW, /data-settings-label=\{t\(opt\.labelKey\)\}/);+});++test("the display only falls back once Xet is known unavailable", () => {+ // Disabling on unknown and falling back on unknown are different rules: conflating them+ // showed HTTP for a stored Xet that turned out to be fine, with nothing to restore it.+ assert.match(TOGGLE, /xetKnownUnavailable = capabilities\?\.xet\.available === false/);+ assert.match(TOGGLE, /mode === "xet" && xetKnownUnavailable/);+ assert.match(TOGGLE, /isLoading \|\| xetKnownUnavailable/);+});++test("a refresh is not swallowed by the hydration wrapper", () => {+ // The API layer decides what may share a request; memoizing above it hid the refresh flag.+ assert.match(PREFERENCE, /installModeInFlightIsRefresh/);+ assert.match(+ PREFERENCE,+ /installModeInFlight && \(!refresh \|\| installModeInFlightIsRefresh\)/,+ );+});++test("resetting local preferences clears the transport override", () => {+ // It outranks the install setting, so a reset that left it behind would keep ignoring+ // transport changes made elsewhere.+ assert.match(PREFERENCE, /export const TRANSPORT_MODE_STORAGE_KEY/);+ assert.match(GENERAL_TAB_SRC, /TRANSPORT_MODE_STORAGE_KEY/);+});++test("a completed write outranks a read issued before it", () => {+ // Ordering GETs against each other is not enough: one taken before the PUT could still land+ // after it and republish the mode just replaced.+ assert.match(API, /latestRequest \+= 1;/);+});++test("the settings row re-reads the install setting when it opens", () => {+ // Otherwise reopening Settings shows whatever is cached: a mode another browser changed, or+ // a stale Auto verdict.+ assert.match(ROW, /loadDownloadTransportSettings\(\{ refresh: true \}\)/);+});++test("a superseded read answers with the current value, not its own", () => {+ // Keeping the stale payload out of the cache only protects later readers: the caller writes+ // the resolved value into its own state, undoing the write that superseded it.+ assert.match(API, /return cachedTransport \?\? settings;/);+});++test("the transport controls mount on a refreshed install mode", () => {+ // Hydrating from the cache here showed the old mode in the toggle while the download path,+ // which refreshes, already ran on the one another browser had set.+ assert.match(PREFERENCE, /hydrateInstallMode\(true\)\.then\(\(\) => setMode/);+});diff --git a/studio/frontend/tests/transport-mode-auto.test.ts b/studio/frontend/tests/transport-mode-auto.test.tsindex 52d4b5eb263..24d740ab5c5 100644--- a/studio/frontend/tests/transport-mode-auto.test.ts+++ b/studio/frontend/tests/transport-mode-auto.test.ts@@ -8,9 +8,8 @@ import { registerBundlerResolver } from "./helpers/kit.ts";registerBundlerResolver();-// constants.ts only: transport-preference.ts reaches lib/toast -> a .tsx barrel node's type-// stripping cannot load. It adds no decision logic (readStored() is exactly-// `isTransportMode(raw) ? raw : DEFAULT_TRANSPORT_MODE`), so these two exports pin the contract.+// constants.ts only: transport-preference.ts reaches lib/toast, a .tsx barrel node's type+// stripping cannot load. Its decision logic is pinned in download-transport-setting.test.ts.const {DEFAULT_TRANSPORT_MODE,RESOLVED_TRANSPORTS,@@ -21,14 +20,14 @@ const {} = await import("../src/features/hub/download-manager/constants.ts");test("auto is the default transport preference", () => {- // The backend picks per machine (RAM, hf_xet build, recent Xet failures), and a user who never- // touches this control is the one who most needs that.+ // The backend picks per machine (RAM, hf_xet build, recent Xet failures), which is what a+ // user who never touches this control most needs. A floor now that the install has a setting,+ // but an untouched install still runs on what it always did.assert.equal(DEFAULT_TRANSPORT_MODE, TRANSPORT.AUTO);});test("auto is a preference, not a transport a download can run on", () => {- // Only "xet"/"http" reach a .transport marker: it records which writer produced a partial, and- // a resume picks its strategy from it.+ // Only "xet"/"http" reach a .transport marker, which records the writer a resume must match.assert.ok(TRANSPORT_MODES.includes(TRANSPORT.AUTO));assert.ok(!RESOLVED_TRANSPORTS.includes(TRANSPORT.AUTO as never));assert.ok(isResolvedTransport("xet"));@@ -36,15 +35,19 @@ test("auto is a preference, not a transport a download can run on", () => {assert.ok(!isResolvedTransport("auto"));});-test("a previously stored explicit preference is still valid", () => {- // Someone who pinned HTTP (or Xet) before this change must not be moved onto Auto:- // isTransportMode() accepting the old values is what keeps readStored() returning them.+test("every previously stored preference is still valid", () => {+ // A transport pinned before this change is kept: only an unset value falls through to the+ // install setting.assert.ok(isTransportMode("http"));assert.ok(isTransportMode("xet"));+ assert.ok(isTransportMode("auto"));});-test("an unrecognised stored value is rejected, so readStored falls back to auto", () => {+test("an unrecognised stored value is rejected, so readStored reports no choice", () => {for (const junk of ["ftp", "", "AUTO", null, undefined, 3]) {- assert.ok(!isTransportMode(junk), `${String(junk)} should not be a transport mode`);+ assert.ok(+ !isTransportMode(junk),+ `${String(junk)} should not be a transport mode`,+ );}});