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
feat(studio): default the model source to ModelScope where Hugging Face is restricted (#12197)
Long Yixing53b36ea78e7f
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.pyindex bcb9c860a97..a61587f4195 100644--- a/studio/backend/routes/settings.py+++ b/studio/backend/routes/settings.py@@ -85,6 +85,7 @@ from utils.download_transport_settings import (from utils.hub_settings import (HubSettings,active_source,+ claim_automatic_source,get_hub_settings,set_hub_settings,set_hub_source,@@ -702,6 +703,10 @@ class HubSettingsResponse(BaseModel):active_source: Literal["huggingface", "modelscope"]+class HubSourceNoticeResponse(BaseModel):+ granted: bool++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 talk its own way back under the limit.@@ -1566,6 +1571,16 @@ def update_hub_source(return _hub_settings_response(set_hub_source(payload.source))+@_owner_settings_router.post("/hub/source-notice", response_model = HubSourceNoticeResponse)+def claim_hub_source_notice(+ current_subject: str = Depends(get_current_subject),+ via_api_key: bool = Depends(authenticated_via_api_key),+) -> HubSourceNoticeResponse:+ """Keep the automatic ModelScope default; granted once, to the UI that tells the owner."""+ require_ui_session(via_api_key)+ return HubSourceNoticeResponse(granted = claim_automatic_source())++@_owner_settings_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/storage/studio_db.py b/studio/backend/storage/studio_db.pyindex 4d2953c6711..0a46d7b49e1 100644--- a/studio/backend/storage/studio_db.py+++ b/studio/backend/storage/studio_db.py@@ -4894,17 +4894,30 @@ def get_app_settings(keys: list[str]) -> dict[str, Any]:conn.close()-def compare_and_set_app_setting(key: str, expected: Any, value: Any) -> bool:- """Write ``value`` to ``key`` only while it still holds ``expected``. A read-then-upsert cannot- express "clear this flag": another save committing in the gap is silently reverted by the write- that follows it. Comparing inside one immediate transaction makes a losing update a no-op- instead. Returns whether the write happened."""+def compare_and_set_app_setting(+ key: str,+ expected: Any,+ value: Any,+ *,+ absent: tuple[str, ...] = (),+) -> bool:+ """Write ``value`` to ``key`` only while it still holds ``expected`` and no key in ``absent``+ is set. A read-then-upsert cannot express "clear this flag": another save committing in the+ gap is silently reverted by the write that follows it. Comparing inside one immediate+ transaction makes a losing update a no-op instead. Returns whether the write happened."""conn = get_connection()try:conn.execute("BEGIN IMMEDIATE")row = conn.execute("SELECT value_json FROM app_settings WHERE key = ?", (key,)).fetchone()current = _json_loads(row["value_json"], None) if row is not None else None- if current != expected:+ present = (+ absent+ and conn.execute(+ f"SELECT 1 FROM app_settings WHERE key IN ({', '.join('?' * len(absent))}) LIMIT 1",+ absent,+ ).fetchone()+ )+ if current != expected or present:conn.rollback()return Falseconn.execute(diff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.pyindex 3248b9bcce4..dfe71d3f720 100644--- a/studio/backend/tests/conftest.py+++ b/studio/backend/tests/conftest.py@@ -126,6 +126,12 @@ def _no_real_mxc_drive_aliases(monkeypatch):monkeypatch.setenv("UNSLOTH_MXC_DRIVE_ALIAS", "0")[email protected](autouse = True)+def _no_restricted_region_defaults(monkeypatch):+ # A host where Hugging Face is restricted would otherwise default the model source to ModelScope.+ monkeypatch.setenv("UNSLOTH_MIRROR_FALLBACK", "0")++@pytest.fixture(autouse = True)def _isolate_agent_skills(_skills_home_root, monkeypatch):# A developer's own ~/.agents or ~/.claude skills must not leak into tool-selection tests.diff --git a/studio/backend/tests/test_hub_settings.py b/studio/backend/tests/test_hub_settings.pyindex e44271736d6..6fb3ce2bd19 100644--- a/studio/backend/tests/test_hub_settings.py+++ b/studio/backend/tests/test_hub_settings.py@@ -45,6 +45,19 @@ def store(monkeypatch):monkeypatch.setattr(studio_db, "upsert_app_settings", lambda updates, **_: values.update(updates) or values)++ def compare_and_set(+ key,+ expected,+ value,+ absent = (),+ ):+ if values.get(key) != expected or any(k in values for k in absent):+ return False+ values[key] = value+ return True++ monkeypatch.setattr(studio_db, "compare_and_set_app_setting", compare_and_set)monkeypatch.setattr(hub_settings, "_operator_env", None)monkeypatch.setattr(hub_settings, "_operator_endpoints", None, raising = False)monkeypatch.setattr(hub_settings, "_saved_only_endpoints", frozenset(), raising = False)@@ -118,6 +131,170 @@ def test_the_startup_read_leaves_studio_db_as_it_found_it(tmp_path, monkeypatch)assert not db.exists()+ "flag, configured, automatic",+ [+ ("1", {}, True),+ ("0", {}, False),+ ("1", {hub_settings.SOURCE_KEY: "huggingface"}, False),+ ("1", {hub_settings.HF_ENDPOINT_KEY: ""}, False),+ ("1", {"HF_ENDPOINT": MIRROR}, False),+ ],+)+def test_restricted_region_defaults_to_modelscope_until_the_hub_is_configured(+ store, monkeypatch, flag, configured, automatic+):+ import hub.modelscope.router as modelscope++ monkeypatch.setattr(modelscope, "internal_endpoint", lambda: "http://127.0.0.1:1234")+ monkeypatch.delenv("HF_ENDPOINT")+ monkeypatch.setenv("UNSLOTH_MIRROR_FALLBACK", flag)+ for key, value in configured.items():+ if key == "HF_ENDPOINT":+ monkeypatch.setenv(key, value)+ else:+ store[key] = value+ hub_settings.apply_hub_settings()+ settings = hub_settings.get_hub_settings()+ expected = hub_settings.MODELSCOPE if automatic else hub_settings.HUGGINGFACE+ assert (settings.source, settings.source_automatic) == (expected, automatic)+ assert hub_settings.active_source() == expected+ assert store == {k: v for k, v in configured.items() if k != "HF_ENDPOINT"}+++def test_rejected_operator_endpoint_still_disables_the_automatic_source(store, monkeypatch):+ monkeypatch.setenv("HF_ENDPOINT", "http://mirror.lan")+ monkeypatch.setenv("UNSLOTH_MIRROR_FALLBACK", "1")+ hub_settings.apply_hub_settings()+ current = hub_settings.get_hub_settings()+ assert (current.source, current.source_automatic) == (hub_settings.HUGGINGFACE, False)+ assert "HF_ENDPOINT" not in os.environ+ assert hub_settings.operator_hf_endpoint() == "https://huggingface.co"+++ "zone, resolvers, platform, expected",+ [+ ("Asia/Shanghai", "", "linux", True),+ (":/usr/share/zoneinfo/Asia/Urumqi", "", "darwin", True),+ ("Asia/Singapore", "", "linux", False),+ ("Asia/Singapore", "nameserver 192.168.1.1\nnameserver 223.5.5.5\n", "linux", True),+ ("Asia/Singapore", "nameserver 223.5.5.50\n", "linux", False),+ ],+)+def test_restricted_region_follows_the_installer_rules(+ tmp_path, monkeypatch, zone, resolvers, platform, expected+):+ from utils import region++ conf = tmp_path / "resolv.conf"+ conf.write_text(resolvers)+ monkeypatch.setattr(region, "_RESOLV_CONFS", (str(tmp_path / "missing"), str(conf)))+ monkeypatch.setattr(region.sys, "platform", platform)+ monkeypatch.setenv("TZ", zone)+ monkeypatch.delenv("UNSLOTH_MIRROR_FALLBACK")+ region.in_restricted_region.cache_clear()+ try:+ assert region.mirror_fallback_enabled() is expected+ finally:+ region.in_restricted_region.cache_clear()+++ "zone, resolvers, expected",+ [+ ("China Standard Time", [], True),+ ("Singapore Standard Time", [], False),+ ("Singapore Standard Time", ["192.168.1.1", "223.5.5.5"], True),+ ("Singapore Standard Time", ["223.5.5.50", "8.8.8.8"], False),+ ],+)+def test_windows_reads_the_registry_time_zone_and_adapter_resolvers(+ monkeypatch, zone, resolvers, expected+):+ from utils import region++ class _Key:+ def __enter__(self):+ return self++ def __exit__(self, *_):+ return False++ registry = _types.SimpleNamespace(+ HKEY_LOCAL_MACHINE = None,+ OpenKey = lambda *_: _Key(),+ QueryValueEx = lambda _key, name: (zone, 1),+ )+ monkeypatch.setattr(region, "_windows_resolvers", lambda: resolvers)+ monkeypatch.setitem(sys.modules, "winreg", registry)+ monkeypatch.setattr(region.sys, "platform", "win32")+ monkeypatch.delenv("TZ", raising = False)+ region.in_restricted_region.cache_clear()+ try:+ assert region.in_restricted_region() is expected+ finally:+ region.in_restricted_region.cache_clear()+++ "database, automatic", [(None, True), ("garbage", False), ("malformed row", False)]+)+def test_only_a_missing_database_reads_as_unconfigured(monkeypatch, database, automatic):+ import sqlite3++ from utils.account_context import OWNER, run_as+ from utils.paths.storage_roots import studio_db_path++ monkeypatch.delitem(sys.modules, "storage.studio_db")+ monkeypatch.delenv("HF_ENDPOINT", raising = False)+ monkeypatch.setenv("UNSLOTH_MIRROR_FALLBACK", "1")+ monkeypatch.setattr(hub_settings, "_operator_env", None)+ path = run_as(OWNER, studio_db_path)+ path.parent.mkdir(parents = True, exist_ok = True)+ if database == "garbage":+ path.write_bytes(b"not a database" * 100)+ elif database == "malformed row":+ with sqlite3.connect(path) as conn:+ conn.execute("CREATE TABLE app_settings (key TEXT PRIMARY KEY, value_json TEXT)")+ conn.execute("INSERT INTO app_settings VALUES (?, ?)", (hub_settings.SOURCE_KEY, "{"))+ assert hub_settings.get_hub_settings().source_automatic is automatic+++def test_windows_resolvers_come_from_adapters_that_are_up():+ import ctypes++ from utils import region++ keep = []++ def servers(*addresses):+ head = ctypes.POINTER(region._Server)()+ for address in reversed(addresses):+ family, octets = (2, address.split(".")) if "." in address else (23, ["0"] * 4)+ raw = (ctypes.c_ubyte * 16)(family, 0, 0, 0, *map(int, octets))+ node = region._Server(+ next = head,+ address = region._Address(ctypes.cast(raw, ctypes.POINTER(ctypes.c_ubyte)), 16),+ )+ keep.extend([raw, node])+ head = ctypes.pointer(node)+ return head++ head = ctypes.POINTER(region._Adapter)()+ for status, dns in reversed(+ [+ (1, servers("::1", "192.168.1.1")),+ (2, servers("223.5.5.5")),+ (1, servers("119.29.29.29")),+ ]+ ):+ adapter = region._Adapter(next = head, dns = dns, oper_status = status)+ keep.append(adapter)+ head = ctypes.pointer(adapter)+ assert region._up_adapter_resolvers(head) == ["192.168.1.1", "119.29.29.29"]++@pytest.fixturedef client(store):app = FastAPI()@@ -166,10 +343,55 @@ def test_an_api_key_cannot_move_the_endpoint_or_source(client, store):== 403)assert client.put("/hub/source", json = {"source": "modelscope"}).status_code == 403+ assert client.post("/hub/source-notice").status_code == 403client.app.dependency_overrides[settings.authenticated_via_api_key] = lambda: Falseassert client.get("/hub").json() == before+def test_the_owner_is_told_once_and_the_automatic_source_is_kept(client, store, monkeypatch):+ import hub.modelscope.router as modelscope++ def no_adapter():+ raise RuntimeError("port exhausted")++ monkeypatch.delenv("HF_ENDPOINT")+ monkeypatch.setenv("UNSLOTH_MIRROR_FALLBACK", "1")+ monkeypatch.setattr(modelscope, "internal_endpoint", no_adapter)+ hub_settings.apply_hub_settings()+ assert client.post("/hub/source-notice").json() == {"granted": False}+ assert store == {}++ monkeypatch.setattr(modelscope, "internal_endpoint", lambda: "http://127.0.0.1:1234")+ hub_settings.apply_hub_settings()+ grants = [client.post("/hub/source-notice").json()["granted"] for _ in range(2)]+ assert grants == [True, False]+ assert store == {hub_settings.SOURCE_KEY: "modelscope"}+ store.clear()+ claim = studio_db.compare_and_set_app_setting++ def endpoint_saved_meanwhile(*args, **kwargs):+ # Another tab saves an endpoint between this claim's read and its insert.+ store[hub_settings.HF_ENDPOINT_KEY] = MIRROR+ return claim(*args, **kwargs)++ monkeypatch.setattr(studio_db, "compare_and_set_app_setting", endpoint_saved_meanwhile)+ assert client.post("/hub/source-notice").json() == {"granted": False}+ assert store == {hub_settings.HF_ENDPOINT_KEY: MIRROR}+ store.clear()+ store[hub_settings.SOURCE_KEY] = "modelscope"+ monkeypatch.setenv("UNSLOTH_MIRROR_FALLBACK", "0")+ assert client.get("/hub").json()["source"] == "modelscope"+++def test_the_claim_insert_requires_the_endpoint_to_stay_unsaved():+ source, endpoint = hub_settings.SOURCE_KEY, hub_settings.HF_ENDPOINT_KEY+ studio_db.upsert_app_settings({endpoint: MIRROR})+ assert not studio_db.compare_and_set_app_setting(source, None, "modelscope", absent = (endpoint,))+ assert studio_db.get_app_setting(source, None) is None+ assert studio_db.compare_and_set_app_setting(source, None, "modelscope", absent = ("unset",))+ assert studio_db.get_app_setting(source, None) == "modelscope"++@pytest.mark.parametrize("raw, canonical",[("", ""), (" hf-mirror.com/ ", MIRROR), ("http://localhost:8080", "http://localhost:8080")],diff --git a/studio/backend/utils/hub_settings.py b/studio/backend/utils/hub_settings.pyindex 166309043cd..5a945e715e4 100644--- a/studio/backend/utils/hub_settings.py+++ b/studio/backend/utils/hub_settings.py@@ -6,8 +6,10 @@The saved values are applied as ``HF_ENDPOINT`` / ``HF_DATASETS_SERVER``, whicheverything in Unsloth -- huggingface_hub, datasets, the browser via /api/health,and every worker process spawned afterwards -- already follows. Until the owner-saves, whatever the operator exported stays in effect. ModelScope as the source-points ``HF_ENDPOINT`` at the loopback adapter in ``hub.modelscope``.+saves, whatever the operator exported stays in effect; where Hugging Face is+restricted, with nothing saved or exported, the source defaults to ModelScope.+ModelScope as the source points ``HF_ENDPOINT`` at the loopback adapter in+``hub.modelscope``."""from __future__ import annotations@@ -53,6 +55,7 @@ class HubSettings:datasets_server_follows_endpoint: boolsaved: boolsource: str = HUGGINGFACE+ source_automatic: bool = Falsedef _capture_operator_env() -> dict[str, str | None]:@@ -75,7 +78,8 @@ def operator_hf_endpoint() -> str:return _operator_endpoint() or DEFAULTS_BY_HEALTH_KEY["hf_endpoint"]-def _read_stored() -> dict:+def _read_stored() -> dict | None:+ """The saved hub settings: ``{}`` before the database exists, None when it cannot be read."""keys = [HF_ENDPOINT_KEY, DATASETS_SERVER_FOLLOWS_KEY, SOURCE_KEY]try:from utils.account_context import OWNER, run_as@@ -85,6 +89,8 @@ def _read_stored() -> dict:from utils.paths.storage_roots import studio_db_pathpath = run_as(OWNER, studio_db_path)+ if not path.exists():+ return {}with closing(sqlite3.connect(f"{path.resolve().as_uri()}?mode=ro", uri = True)) as conn:rows = conn.execute("SELECT key, value_json FROM app_settings WHERE key IN (?, ?, ?)", keys@@ -95,15 +101,34 @@ def _read_stored() -> dict:return run_as(OWNER, get_app_settings, keys)except Exception as exc: # noqa: BLE001 - a missing or unreadable db keeps the environment's valueslogger.debug("hub settings read failed (%s)", exc)- return {}+ return None+++def _automatic_modelscope(stored: dict) -> bool:+ """ModelScope by default where Hugging Face is restricted, until a source or an endpoint is saved or exported."""+ from utils.region import mirror_fallback_enabled+ return (+ SOURCE_KEY not in stored+ and HF_ENDPOINT_KEY not in stored+ and not (_capture_operator_env()["HF_ENDPOINT"] or "").strip()+ and mirror_fallback_enabled()+ )def get_hub_settings() -> HubSettings:stored = _read_stored()- source = stored.get(SOURCE_KEY) if stored.get(SOURCE_KEY) in SOURCES else HUGGINGFACE+ # A failed read may hide a saved choice, so it never selects the automatic default.+ automatic = stored is not None and _automatic_modelscope(stored)+ stored = stored or {}+ if automatic:+ source = MODELSCOPE+ else:+ source = stored.get(SOURCE_KEY) if stored.get(SOURCE_KEY) in SOURCES else HUGGINGFACEendpoint = stored.get(HF_ENDPOINT_KEY)if not isinstance(endpoint, str):- return HubSettings(_operator_endpoint(), False, saved = False, source = source)+ return HubSettings(+ _operator_endpoint(), False, saved = False, source = source, source_automatic = automatic+ )try:endpoint = validate_hub_endpoint(endpoint)except ValueError:@@ -133,6 +158,16 @@ def set_hub_source(source: str) -> HubSettings:return get_hub_settings()+def claim_automatic_source() -> bool:+ """Save the automatic ModelScope default. True only for the call that saved it, whose client tells the owner."""+ if not get_hub_settings().source_automatic or active_source() != MODELSCOPE:+ return False+ from storage.studio_db import compare_and_set_app_setting++ # An endpoint saved since the read above is a choice too: the claim must not override it.+ return compare_and_set_app_setting(SOURCE_KEY, None, MODELSCOPE, absent = (HF_ENDPOINT_KEY,))++def set_hub_settings(hf_endpoint: str, datasets_server_follows_endpoint: bool) -> HubSettings:"""Validate, persist and apply. Raises ValueError on an unusable endpoint."""endpoint = validate_hub_endpoint(hf_endpoint)diff --git a/studio/backend/utils/region.py b/studio/backend/utils/region.pynew file mode 100644index 00000000000..35f974cb82c--- /dev/null+++ b/studio/backend/utils/region.py@@ -0,0 +1,167 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Whether this host is in a region where Hugging Face is restricted, decided as install.sh /+install.ps1 decide it: no network call. Mainland China is the one such region today."""++from __future__ import annotations++import ctypes+import functools+import os+import re+import sys+from pathlib import Path++_RESTRICTED_ZONES = (+ "Asia/Shanghai",+ "Asia/Chongqing",+ "Asia/Chungking",+ "Asia/Harbin",+ "Asia/Urumqi",+ "Asia/Kashgar",+ "PRC",+)+_RESTRICTED_WINDOWS_ZONES = ("China Standard Time",)+# Public DNS and cloud resolvers of mainland China.+_RESTRICTED_RESOLVER = re.compile(+ r"223\.5\.5\.5|223\.6\.6\.6|119\.29\.29\.29|114\.114\.11[45]\.11[0459]"+ r"|182\.254\.116\.116|119\.28\.28\.28|180\.76\.76\.76|1\.2\.4\.8|210\.2\.4\.8"+ r"|100\.100\.2\.13[68]|183\.60\.8[23]\.(19|98)"+)+_NAMESERVER = re.compile(r"^[ \t]*nameserver[ \t]+(\S+)[ \t]*$", re.MULTILINE)+_RESOLV_CONFS = ("/etc/resolv.conf", "/run/systemd/resolve/resolv.conf")+++def _time_zone() -> str:+ zone = os.environ.get("TZ", "").lstrip(":")+ if zone:+ return zone+ if sys.platform == "win32":+ try:+ import winreg+ with winreg.OpenKey(+ winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Control\TimeZoneInformation"+ ) as key:+ return str(winreg.QueryValueEx(key, "TimeZoneKeyName")[0])+ except OSError:+ return ""+ try:+ zone = Path("/etc/timezone").read_text(encoding = "utf-8").strip()+ except (OSError, UnicodeDecodeError):+ zone = ""+ if zone:+ return zone+ try:+ return os.readlink("/etc/localtime")+ except OSError:+ return ""+++class _Address(ctypes.Structure):+ _fields_ = [("sockaddr", ctypes.POINTER(ctypes.c_ubyte)), ("length", ctypes.c_int)]+++class _Server(ctypes.Structure):+ pass+++_Server._fields_ = [+ ("header", ctypes.c_ulonglong),+ ("next", ctypes.POINTER(_Server)),+ ("address", _Address),+]+++# The leading fields of IP_ADAPTER_ADDRESSES, through OperStatus.+class _Adapter(ctypes.Structure):+ pass+++_Adapter._fields_ = [+ ("header", ctypes.c_ulonglong),+ ("next", ctypes.POINTER(_Adapter)),+ ("name", ctypes.c_char_p),+ ("unicast", ctypes.c_void_p),+ ("anycast", ctypes.c_void_p),+ ("multicast", ctypes.c_void_p),+ ("dns", ctypes.POINTER(_Server)),+ ("suffix", ctypes.c_wchar_p),+ ("description", ctypes.c_wchar_p),+ ("friendly_name", ctypes.c_wchar_p),+ ("physical_address", ctypes.c_ubyte * 8),+ ("physical_address_length", ctypes.c_ulong),+ ("flags", ctypes.c_ulong),+ ("mtu", ctypes.c_ulong),+ ("if_type", ctypes.c_ulong),+ ("oper_status", ctypes.c_int),+]+_OPER_STATUS_UP = 1+_AF_INET = 2+++def _up_adapter_resolvers(adapter) -> list[str]:+ """IPv4 DNS servers of the adapters that are up, from a GetAdaptersAddresses list."""+ servers: list[str] = []+ while adapter:+ if adapter.contents.oper_status == _OPER_STATUS_UP:+ server = adapter.contents.dns+ while server:+ raw = server.contents.address+ if raw.length >= 8 and raw.sockaddr[0] | raw.sockaddr[1] << 8 == _AF_INET:+ servers.append(".".join(str(raw.sockaddr[i]) for i in range(4, 8)))+ server = server.contents.next+ adapter = adapter.contents.next+ return servers+++def _windows_resolvers() -> list[str]:+ """What the installer's .NET query lists: DNS servers of the adapters that are up."""+ skip_unicast_anycast_multicast, buffer_overflow = 0x7, 111+ try:+ get_adapters = ctypes.WinDLL("iphlpapi").GetAdaptersAddresses+ size = ctypes.c_ulong(16 * 1024)+ for _ in range(3):+ buffer = ctypes.create_string_buffer(size.value)+ result = get_adapters(+ 0, skip_unicast_anycast_multicast, None, buffer, ctypes.byref(size)+ )+ if result != buffer_overflow:+ break+ except OSError:+ return []+ if result != 0:+ return []+ return _up_adapter_resolvers(ctypes.cast(buffer, ctypes.POINTER(_Adapter)))+++def _resolvers() -> list[str]:+ if sys.platform == "win32":+ return _windows_resolvers()+ servers: list[str] = []+ for path in _RESOLV_CONFS:+ try:+ servers += _NAMESERVER.findall(Path(path).read_text(encoding = "utf-8", errors = "replace"))+ except OSError:+ continue+ return servers++[email protected]_cache(maxsize = 1)+def in_restricted_region() -> bool:+ zone = _time_zone()+ if zone in _RESTRICTED_WINDOWS_ZONES or any(+ zone == z or zone.endswith("/" + z) for z in _RESTRICTED_ZONES+ ):+ return True+ return any(_RESTRICTED_RESOLVER.fullmatch(server) for server in _resolvers())+++def mirror_fallback_enabled() -> bool:+ """Region detection, overridden by UNSLOTH_MIRROR_FALLBACK: 0 turns it off and 1 on, as for the installer."""+ flag = os.environ.get("UNSLOTH_MIRROR_FALLBACK", "").strip().lower()+ if flag in ("0", "false", "no", "off"):+ return False+ if flag in ("1", "true", "yes", "on"):+ return True+ return in_restricted_region()diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsxindex 561f1419307..e0d7838d8d8 100644--- a/studio/frontend/src/app/routes/__root.tsx+++ b/studio/frontend/src/app/routes/__root.tsx@@ -40,6 +40,7 @@ import {stepInterfaceScale,triggerShortcut,useInterfaceScaleStore,+ useHubSourceNotice,useSettingsDialogStore,useShortcut,useShortcutAvailable,@@ -186,6 +187,11 @@ function LowDiskNoticeMount() {return null;}+function HubSourceNoticeMount() {+ useHubSourceNotice();+ return null;+}+// The chat settings are the installation's, and the Models page and the model// picker read them too, so hydration cannot wait for ChatPage to mount.function ChatSettingsHydrationMount() {@@ -800,6 +806,8 @@ function RootLayout() {</SidebarInset></SidebarProvider>)}+ {/* This side-effect-only mount stays last so it cannot shift existing React useId paths. */}+ {!isAuthFlowRoute && <HubSourceNoticeMount />}</>);diff --git a/studio/frontend/src/features/hub/catalog/catalog-states.tsx b/studio/frontend/src/features/hub/catalog/catalog-states.tsxindex aadff5e8456..31640e1d0bf 100644--- a/studio/frontend/src/features/hub/catalog/catalog-states.tsx+++ b/studio/frontend/src/features/hub/catalog/catalog-states.tsx@@ -32,6 +32,7 @@ function describeFailure(online: boolean,resourceLabel: "models" | "datasets",hub: string,+ offersModelScope: boolean,): {title: string;body: string;@@ -55,7 +56,10 @@ function describeFailure(case "unknown":return {title: `Can't reach ${hub}`,- body: failure.message,+ body:+ failure.kind === "network-opaque" && offersModelScope+ ? `Unable to reach ${hub}. Check your network connection or try ModelScope instead.`+ : failure.message,offlineLike: false,};// Reached and refused: the fix is the token, not the connection or the hub.@@ -82,13 +86,18 @@ function describeFailure(};}-function UseModelScopeButton() {- const t = useT();+function useOffersModelScope(): boolean {const isOwner = useIsAccountOwner();const source = useHubSource();+ return isOwner && source === "huggingface";+}++function UseModelScopeButton() {+ const t = useT();+ const offersModelScope = useOffersModelScope();const [switching, setSwitching] = useState(false);const [failed, setFailed] = useState(false);- if (!isOwner || source !== "huggingface") return null;+ if (!offersModelScope) return null;return (<span className="inline-flex items-center gap-2"><Button@@ -152,6 +161,7 @@ export function NetworkErrorState({online,resourceLabel,useHubName(),+ useOffersModelScope(),);const icon = offlineLike ? WifiDisconnected02Icon : CloudOffIcon;@@ -215,6 +225,7 @@ export function HubFailureHint({phase === "available","models",useHubName(),+ useOffersModelScope(),);return (<div className="flex flex-col gap-2 px-2.5 py-2">diff --git a/studio/frontend/src/features/hub/lib/network.ts b/studio/frontend/src/features/hub/lib/network.tsindex 22890baa800..af92d7ac8f2 100644--- a/studio/frontend/src/features/hub/lib/network.ts+++ b/studio/frontend/src/features/hub/lib/network.ts@@ -315,7 +315,7 @@ export function classifyFetchFailure(}return {kind: "network-opaque",- message: `The browser could not reach ${host}. A DNS or content filter, TLS-inspecting antivirus, a browser extension, or a CORS policy can all cause this, and the browser does not say which.`,+ message: `Unable to reach ${host}. Check your network connection.`,origin,retryable: true,};diff --git a/studio/frontend/src/features/settings/api/hub-settings.ts b/studio/frontend/src/features/settings/api/hub-settings.tsindex d7985877022..4d9b5a171b5 100644--- a/studio/frontend/src/features/settings/api/hub-settings.ts+++ b/studio/frontend/src/features/settings/api/hub-settings.ts@@ -63,6 +63,24 @@ export async function updateHubSource(source: HubSource): Promise<HubSettings> {return saved;}+/** Whether this client should tell the owner that ModelScope was chosen for them. Granted once+ * per install, and it saves that choice. Fails closed. */+export async function claimHubSourceNotice(): Promise<boolean> {+ try {+ const res = await authFetch(+ "/api/settings/hub/source-notice",+ { method: "POST" },+ // A retried claim whose first attempt landed would come back denied, hiding the notice.+ { retryNetworkErrors: false },+ );+ if (!res.ok) return false;+ const body = (await res.json()) as { granted?: unknown };+ return body.granted === true;+ } catch {+ return false;+ }+}+export type HubEndpointSettings = Pick<HubSettings,"hfEndpoint" | "datasetsServerFollowsEndpoint"diff --git a/studio/frontend/src/features/settings/components/hub-settings-section.tsx b/studio/frontend/src/features/settings/components/hub-settings-section.tsxindex 8780f43774e..26deb9696ca 100644--- a/studio/frontend/src/features/settings/components/hub-settings-section.tsx+++ b/studio/frontend/src/features/settings/components/hub-settings-section.tsx@@ -8,7 +8,7 @@ import { useIsAccountOwner } from "@/features/auth";import { useT } from "@/i18n";import { DEFAULT_HF_ENDPOINT, type HubSource } from "@/lib/hf-endpoint";import { cn } from "@/lib/utils";-import { useEffect, useState } from "react";+import { useEffect, useRef, useState } from "react";import {type HubEndpointSettings,type HubSettings,@@ -17,6 +17,7 @@ import {updateHubSettings,updateHubSource,} from "../api/hub-settings";+import { useSettingsDialogStore } from "../stores/settings-dialog-store";import { SettingsRow } from "./settings-row";import { SettingsSection } from "./settings-section";@@ -32,6 +33,20 @@ export function HubSettingsSection() {const [draftEndpoint, setDraftEndpoint] = useState("");const [saving, setSaving] = useState(false);const [error, setError] = useState<string | null>(null);+ const sectionRef = useRef<HTMLElement | null>(null);+ const scrollTarget = useSettingsDialogStore((s) => s.scrollTarget);+ const consumeScrollTarget = useSettingsDialogStore(+ (s) => s.consumeScrollTarget,+ );++ useEffect(() => {+ if (scrollTarget !== "general-hub") return;+ const frame = window.requestAnimationFrame(() => {+ sectionRef.current?.scrollIntoView({ block: "start", behavior: "smooth" });+ consumeScrollTarget("general-hub");+ });+ return () => window.cancelAnimationFrame(frame);+ }, [consumeScrollTarget, scrollTarget]);useEffect(() => {let cancelled = false;@@ -104,7 +119,7 @@ export function HubSettingsSection() {});return (- <SettingsSection title={t("settings.general.hub.sectionTitle")}>+ <SettingsSection ref={sectionRef} title={t("settings.general.hub.sectionTitle")}><SettingsRowalignTop={true}label={t("settings.general.hub.source")}diff --git a/studio/frontend/src/features/settings/hooks/use-hub-source-notice.ts b/studio/frontend/src/features/settings/hooks/use-hub-source-notice.tsnew file mode 100644index 00000000000..c7a47946455--- /dev/null+++ b/studio/frontend/src/features/settings/hooks/use-hub-source-notice.ts@@ -0,0 +1,32 @@+// 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 { useIsAccountOwner } from "@/features/auth";+import { useT } from "@/i18n";+import { toast } from "@/lib/toast";+import { useEffect } from "react";+import { claimHubSourceNotice } from "../api/hub-settings";+import { useSettingsDialogStore } from "../stores/settings-dialog-store";++/** Tell the owner, once per install, that the model source was set to ModelScope for them. */+export function useHubSourceNotice(): void {+ const t = useT();+ const isOwner = useIsAccountOwner();+ const openDialog = useSettingsDialogStore((state) => state.openDialog);++ useEffect(() => {+ if (!isOwner) return;+ // Not cancelled on cleanup: the grant is spent once claimed, so dropping it would lose the notice.+ void claimHubSourceNotice().then((granted) => {+ if (!granted) return;+ toast.info(t("settings.general.hub.autoSourceTitle"), {+ description: t("settings.general.hub.autoSourceDescription"),+ duration: Number.POSITIVE_INFINITY,+ action: {+ label: t("settings.general.hub.autoSourceAction"),+ onClick: () => openDialog("general", { scrollTarget: "general-hub" }),+ },+ });+ });+ }, [isOwner, openDialog, t]);+}diff --git a/studio/frontend/src/features/settings/index.ts b/studio/frontend/src/features/settings/index.tsindex 1c26c353aa2..9da154e4237 100644--- a/studio/frontend/src/features/settings/index.ts+++ b/studio/frontend/src/features/settings/index.ts@@ -87,6 +87,7 @@ export {useShortcutLabels,useShortcutAvailable,} from "./hooks/use-shortcut";+export { useHubSourceNotice } from "./hooks/use-hub-source-notice";export { Shortcut } from "./components/shortcut";export {currentBinding,diff --git a/studio/frontend/src/features/settings/stores/settings-dialog-store.ts b/studio/frontend/src/features/settings/stores/settings-dialog-store.tsindex eb8ad65a27e..91df1519193 100644--- a/studio/frontend/src/features/settings/stores/settings-dialog-store.ts+++ b/studio/frontend/src/features/settings/stores/settings-dialog-store.ts@@ -33,6 +33,7 @@ export type SettingsScrollTarget =| "appearance-sidebar-nav"| "chat-composer"| "chat-canvas-network"+ | "general-hub"| "library-storage"| "resources-caches";@@ -127,6 +128,7 @@ const SCROLL_TARGET_TAB: Record<SettingsScrollTarget, SettingsTab> = {"about-updates": "about","appearance-sidebar-nav": "appearance","chat-canvas-network": "chat",+ "general-hub": "general","library-storage": "library","resources-caches": "resources",};diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex 9211c1b7578..cd068358ac7 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -1086,6 +1086,9 @@ export const ar = {source: "مصدر النماذج",sourceDescription: "المكان الذي يبحث فيه مركز النماذج ويُنزّل منه. اختر ModelScope إذا كان Hugging Face محظورًا أو بطيئًا على شبكتك.",sourceFallback: "تعذّر تشغيل ModelScope، لذلك يُستخدم Hugging Face. راجع سجلات Unsloth.",+ autoSourceTitle: "تم تبديل مصدر النماذج إلى ModelScope",+ autoSourceDescription: "غالبًا ما يكون Hugging Face بطيئًا أو محجوبًا في منطقتك، لذلك يقوم Unsloth الآن بتنزيل النماذج من ModelScope.",+ autoSourceAction: "فتح إعدادات مصدر النماذج",sectionTitle: "مركز النماذج",endpoint: "نقطة نهاية Hugging Face",endpointDescription: "المصدر الذي تُنزَّل منه النماذج ومجموعات البيانات. اتركه فارغًا لاستخدام huggingface.co، أو أدخل مرآة مثل https://hf-mirror.com.",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex 36fb761497f..0122201580d 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -1109,6 +1109,9 @@ export const de = {source: "Modellquelle",sourceDescription: "Wo der Model-Hub sucht und herunterlädt. Wählen Sie ModelScope, wenn Hugging Face in Ihrem Netzwerk blockiert oder langsam ist.",sourceFallback: "ModelScope konnte nicht gestartet werden, daher wird Hugging Face verwendet. Prüfen Sie die Unsloth-Logs.",+ autoSourceTitle: "Modellquelle auf ModelScope umgestellt",+ autoSourceDescription: "Hugging Face ist in Ihrer Region oft langsam oder gesperrt, daher lädt Unsloth Modelle jetzt von ModelScope.",+ autoSourceAction: "Einstellungen für die Modellquelle öffnen",sectionTitle: "Modell-Hub",endpoint: "Hugging-Face-Endpunkt",endpointDescription: "Von hier werden Modelle und Datensätze geladen. Leer lassen für huggingface.co oder einen Mirror wie https://hf-mirror.com eintragen.",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex cba74d80e92..c94050fa6ba 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -1093,6 +1093,9 @@ export const en = {source: "Model source",sourceDescription: "Where the model hub searches and downloads. Choose ModelScope if Hugging Face is blocked or slow on your network.",sourceFallback: "ModelScope couldn't be started, so Hugging Face is in use. Check the Unsloth logs.",+ autoSourceTitle: "Model source switched to ModelScope",+ autoSourceDescription: "Hugging Face is often slow or blocked in your region, so Unsloth now downloads models from ModelScope.",+ autoSourceAction: "Open Model source settings",sectionTitle: "Model hub",endpoint: "Hugging Face endpoint",endpointDescription: "Where models and datasets are downloaded from. Leave empty for huggingface.co, or enter a mirror such as https://hf-mirror.com.",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex 119440b0437..d2b13fb6f31 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -1104,6 +1104,9 @@ export const es = {source: "Origen de los modelos",sourceDescription: "Dónde busca y descarga el hub de modelos. Elige ModelScope si Hugging Face está bloqueado o es lento en tu red.",sourceFallback: "No se pudo iniciar ModelScope, así que se usa Hugging Face. Revisa los registros de Unsloth.",+ autoSourceTitle: "Origen de modelos cambiado a ModelScope",+ autoSourceDescription: "Hugging Face suele ser lento o estar bloqueado en tu región, así que Unsloth ahora descarga los modelos de ModelScope.",+ autoSourceAction: "Abrir la configuración del origen de los modelos",sectionTitle: "Hub de modelos",endpoint: "Endpoint de Hugging Face",endpointDescription: "De dónde se descargan los modelos y conjuntos de datos. Déjalo vacío para usar huggingface.co o escribe un espejo como https://hf-mirror.com.",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex 673f7931960..b7cd657e18b 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -1108,6 +1108,9 @@ export const fr = {source: "Source des modèles",sourceDescription: "Où le hub de modèles recherche et télécharge. Choisissez ModelScope si Hugging Face est bloqué ou lent sur votre réseau.",sourceFallback: "ModelScope n'a pas pu démarrer, Hugging Face est donc utilisé. Consultez les journaux d'Unsloth.",+ autoSourceTitle: "Source des modèles basculée sur ModelScope",+ autoSourceDescription: "Hugging Face est souvent lent ou bloqué dans votre région ; Unsloth télécharge donc désormais les modèles depuis ModelScope.",+ autoSourceAction: "Ouvrir les paramètres de source des modèles",sectionTitle: "Hub de modèles",endpoint: "Point de terminaison Hugging Face",endpointDescription: "Source de téléchargement des modèles et jeux de données. Laissez vide pour huggingface.co, ou saisissez un miroir comme https://hf-mirror.com.",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 87b4da83a44..1045086904f 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -1089,6 +1089,9 @@ export const hi = {source: "मॉडल स्रोत",sourceDescription: "मॉडल हब कहाँ खोजता और डाउनलोड करता है। अगर आपके नेटवर्क पर Hugging Face ब्लॉक या धीमा है तो ModelScope चुनें।",sourceFallback: "ModelScope शुरू नहीं हो सका, इसलिए Hugging Face इस्तेमाल हो रहा है। Unsloth के लॉग देखें।",+ autoSourceTitle: "मॉडल स्रोत ModelScope पर बदल दिया गया",+ autoSourceDescription: "आपके क्षेत्र में Hugging Face अक्सर धीमा या ब्लॉक रहता है, इसलिए Unsloth अब ModelScope से मॉडल डाउनलोड करता है।",+ autoSourceAction: "मॉडल स्रोत सेटिंग्स खोलें",sectionTitle: "मॉडल हब",endpoint: "Hugging Face एंडपॉइंट",endpointDescription: "मॉडल और डेटासेट यहीं से डाउनलोड होते हैं। huggingface.co के लिए खाली छोड़ें, या https://hf-mirror.com जैसा कोई मिरर डालें।",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex 9480c0941d1..f4ef4228b51 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -1075,6 +1075,9 @@ export const it = {source: "Origine dei modelli",sourceDescription: "Dove l'hub dei modelli cerca e scarica. Scegli ModelScope se Hugging Face è bloccato o lento sulla tua rete.",sourceFallback: "Non è stato possibile avviare ModelScope, quindi viene usato Hugging Face. Controlla i log di Unsloth.",+ autoSourceTitle: "Origine dei modelli impostata su ModelScope",+ autoSourceDescription: "Nella tua zona Hugging Face è spesso lento o bloccato, quindi Unsloth ora scarica i modelli da ModelScope.",+ autoSourceAction: "Apri le impostazioni dell'origine dei modelli",sectionTitle: "Hub dei modelli",endpoint: "Endpoint Hugging Face",endpointDescription: "Da dove vengono scaricati modelli e dataset. Lascia vuoto per huggingface.co oppure inserisci un mirror come https://hf-mirror.com.",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex 4f6ac3f3333..d72c4fa07dc 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -1075,6 +1075,9 @@ export const ja = {source: "モデルの取得元",sourceDescription: "モデルハブの検索とダウンロード先です。ネットワークで Hugging Face がブロックされている、または遅い場合は ModelScope を選んでください。",sourceFallback: "ModelScope を起動できなかったため、Hugging Face を使用しています。Unsloth のログを確認してください。",+ autoSourceTitle: "モデルのソースを ModelScope に切り替えました",+ autoSourceDescription: "お住まいの地域では Hugging Face が遅い、またはつながらないことが多いため、Unsloth は ModelScope からモデルをダウンロードします。",+ autoSourceAction: "モデルの取得元の設定を開く",sectionTitle: "モデルハブ",endpoint: "Hugging Face エンドポイント",endpointDescription: "モデルとデータセットのダウンロード元です。空欄なら huggingface.co、ミラーを使う場合は https://hf-mirror.com などを入力します。",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex 0b0194a8233..619b02688c3 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -1083,6 +1083,9 @@ export const ko = {source: "모델 소스",sourceDescription: "모델 허브가 검색하고 다운로드하는 곳입니다. 네트워크에서 Hugging Face가 차단되었거나 느리면 ModelScope를 선택하세요.",sourceFallback: "ModelScope를 시작할 수 없어 Hugging Face를 사용하고 있습니다. Unsloth 로그를 확인하세요.",+ autoSourceTitle: "모델 소스를 ModelScope로 전환했습니다",+ autoSourceDescription: "현재 지역에서는 Hugging Face가 느리거나 차단되는 경우가 많아 Unsloth가 이제 ModelScope에서 모델을 다운로드합니다.",+ autoSourceAction: "모델 소스 설정 열기",sectionTitle: "모델 허브",endpoint: "Hugging Face 엔드포인트",endpointDescription: "모델과 데이터셋을 내려받는 곳입니다. 비워 두면 huggingface.co를 사용하고, 미러를 쓰려면 https://hf-mirror.com 같은 주소를 입력하세요.",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex 3aab2852e37..ea031f294dd 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -1097,6 +1097,9 @@ export const ptBR = {source: "Origem dos modelos",sourceDescription: "Onde o hub de modelos pesquisa e baixa. Escolha ModelScope se o Hugging Face estiver bloqueado ou lento na sua rede.",sourceFallback: "Não foi possível iniciar o ModelScope, então o Hugging Face está em uso. Verifique os logs do Unsloth.",+ autoSourceTitle: "Origem dos modelos alterada para ModelScope",+ autoSourceDescription: "O Hugging Face costuma ser lento ou bloqueado na sua região, então o Unsloth agora baixa os modelos do ModelScope.",+ autoSourceAction: "Abrir as configurações da origem dos modelos",sectionTitle: "Hub de modelos",endpoint: "Endpoint do Hugging Face",endpointDescription: "De onde os modelos e conjuntos de dados são baixados. Deixe vazio para usar huggingface.co ou informe um espelho como https://hf-mirror.com.",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 400b9bc921b..e705577d5bf 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -1091,6 +1091,9 @@ export const ru = {source: "Источник моделей",sourceDescription: "Где хаб моделей ищет и откуда скачивает. Выберите ModelScope, если Hugging Face заблокирован или медленно работает в вашей сети.",sourceFallback: "Не удалось запустить ModelScope, поэтому используется Hugging Face. Проверьте журналы Unsloth.",+ autoSourceTitle: "Источник моделей переключён на ModelScope",+ autoSourceDescription: "В вашем регионе Hugging Face часто работает медленно или заблокирован, поэтому Unsloth теперь загружает модели из ModelScope.",+ autoSourceAction: "Открыть настройки «Источник моделей»",sectionTitle: "Хаб моделей",endpoint: "Эндпоинт Hugging Face",endpointDescription: "Откуда загружаются модели и датасеты. Оставьте пустым для huggingface.co или укажите зеркало, например https://hf-mirror.com.",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex c5e07729855..e9edcb7c131 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -1066,6 +1066,9 @@ export const zhCN = {source: "模型来源",sourceDescription: "模型中心搜索和下载的来源。如果你的网络无法访问 Hugging Face 或速度很慢,请选择 ModelScope。",sourceFallback: "无法启动 ModelScope,当前使用 Hugging Face。请查看 Unsloth 日志。",+ autoSourceTitle: "模型来源已切换为 ModelScope",+ autoSourceDescription: "Hugging Face 在你所在的地区经常较慢或无法访问,因此 Unsloth 现在从 ModelScope 下载模型。",+ autoSourceAction: "打开模型来源设置",sectionTitle: "模型中心",endpoint: "Hugging Face 端点",endpointDescription: "模型和数据集的下载来源。留空则使用 huggingface.co,或填写镜像地址,例如 https://hf-mirror.com。",diff --git a/studio/frontend/tests/hub-network-availability.test.ts b/studio/frontend/tests/hub-network-availability.test.tsindex 4fa93e7de87..05865dc2e2f 100644--- a/studio/frontend/tests/hub-network-availability.test.ts+++ b/studio/frontend/tests/hub-network-availability.test.ts@@ -136,7 +136,7 @@ test("classification separates timeout, abort, offline and opaque failures", ()const opaque = classifyFetchFailure(new TypeError("Failed to fetch"), HF);assert.equal(opaque.kind, "network-opaque");assert.match(opaque.message, /huggingface\.co/);- assert.match(opaque.message, /extension|antivirus|filter/i);+ assert.doesNotMatch(opaque.message, /offline/i);});test("a browser reporting itself offline is named as such", () => {diff --git a/studio/frontend/tests/hub-source-notice.test.ts b/studio/frontend/tests/hub-source-notice.test.tsnew file mode 100644index 00000000000..7ebb63d9557--- /dev/null+++ b/studio/frontend/tests/hub-source-notice.test.ts@@ -0,0 +1,53 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import { register } from "node:module";+import test from "node:test";++// The claim both saves ModelScope and grants the notice, so anything but an explicit grant+// shows nothing: a notice on a failed claim would announce a switch that was never saved.+register("./store-stub-resolver.mjs", import.meta.url);+const { setAuthFetchHandler } = await import("./helpers/store-stubs/auth.ts");+const { claimHubSourceNotice } = await import(+ "../src/features/settings/api/hub-settings.ts"+);++test("only an explicit grant shows the notice", async (t) => {+ t.after(() => setAuthFetchHandler(null));+ const urls: string[] = [];+ const answer = (respond: () => Response) =>+ setAuthFetchHandler((url, init) => {+ urls.push(`${init?.method} ${url}`);+ return respond();+ });++ answer(() => Response.json({ granted: true }));+ assert.equal(await claimHubSourceNotice(), true);+ assert.deepEqual(urls, ["POST /api/settings/hub/source-notice"]);++ for (const refused of [+ () => Response.json({ granted: false }),+ () => Response.json({ detail: "Not Found" }),+ () => Response.json({ granted: true }, { status: 500 }),+ () => {+ throw new Error("network down");+ },+ ]) {+ answer(refused);+ assert.equal(await claimHubSourceNotice(), false);+ }+});++test("the side-effect mount cannot renumber the existing app shell", () => {+ const root = readFileSync(+ new URL("../src/app/routes/__root.tsx", import.meta.url),+ "utf8",+ );+ assert.ok(+ root.lastIndexOf("<HubSourceNoticeMount />") >+ root.lastIndexOf("</SidebarProvider>"),+ "a null-rendering root sibling must follow the rendered shell so React useId paths stay stable",+ );+});diff --git a/studio/frontend/tests/settings-deep-open-requests.test.ts b/studio/frontend/tests/settings-deep-open-requests.test.tsindex da934530805..2891eef523e 100644--- a/studio/frontend/tests/settings-deep-open-requests.test.ts+++ b/studio/frontend/tests/settings-deep-open-requests.test.ts@@ -137,6 +137,7 @@ test("canvas network and Library storage land on their tab and stay until it reafor (const [tab, target, from] of [["chat", "chat-canvas-network", null],["library", "library-storage", "data"],+ ["general", "general-hub", "data"],] as const) {reset();if (from) store.getState().openDialog(from);