Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Fix model picker stuck on "Loading variants" (#7767)

Michael Hanaa9ca854590a
diff --git a/studio/backend/hub/services/models/gguf_variants.py b/studio/backend/hub/services/models/gguf_variants.py
index 4d6cc5a55e8..0de0575e91c 100644
--- a/studio/backend/hub/services/models/gguf_variants.py
+++ b/studio/backend/hub/services/models/gguf_variants.py
@@ -8,6 +8,7 @@ from __future__ import annotations
import asyncio
import threading
import time
+import weakref
from collections import OrderedDict
from pathlib import Path
from typing import NamedTuple, Optional
@@ -541,13 +542,52 @@ def _complete_quants_under(snapshot: str):
return None
-async def get_gguf_variants_response(
+# One scan per identical request in flight. Aborting the HTTP request cannot stop the scan
+# already running in its thread, so the picker's Retry, and reopening a row, would each start
+# another against a filesystem that is not answering: measured 23 retries filling all 20
+# default-executor workers, starving unrelated offloaded work and holding up exit. Joining the
+# running scan costs at most its own duration in staleness, well inside the client's cache TTL.
+_VARIANTS_INFLIGHT: "weakref.WeakKeyDictionary" = weakref.WeakKeyDictionary()
+
+
+async def _shared_variants_scan(key: tuple, compute):
+ """*compute* in a thread, shared with any identical request already running."""
+ loop = asyncio.get_running_loop()
+ inflight = _VARIANTS_INFLIGHT.get(loop)
+ if inflight is None:
+ inflight = {}
+ _VARIANTS_INFLIGHT[loop] = inflight
+
+ task = inflight.get(key)
+ if task is None:
+ task = asyncio.ensure_future(asyncio.to_thread(compute))
+
+ def _release(finished: asyncio.Future) -> None:
+ inflight.pop(key, None)
+ if not finished.cancelled():
+ finished.exception() # retrieved, so a caller-less failure stays quiet
+
+ inflight[key] = task
+ task.add_done_callback(_release)
+ # Shielded: one caller giving up must not cancel the scan the others are waiting on.
+ return await asyncio.shield(task)
+
+
+class VariantsAnswer(NamedTuple):
+ """The listing, plus the directory it came from so a caller reading metadata reads the
+ same copy. None means no single directory: the repo's caches answered."""
+
+ response: GgufVariantsResponse
+ context_source: Optional[str]
+
+
+async def get_gguf_variants_answer(
repo_id: str,
prefer_local_cache: bool = False,
offline: bool = False,
local_path: Optional[str] = None,
hf_token: Optional[str] = None,
-):
+) -> VariantsAnswer:
"""
List available GGUF quantization variants for a HuggingFace repo
or a local directory (e.g. LM Studio model folder).
@@ -556,6 +596,9 @@ async def get_gguf_variants_response(
with file sizes, whether the model supports vision, and the recommended
default variant.
"""
+ # Set by whichever branch answers, and returned with the listing: the HF cache answers
+ # before local_path, so a caller cannot infer the copy from the request alone.
+ answered_from: list[Optional[str]] = [None]
def _compute() -> GgufVariantsResponse:
repo_cache_dir = (
@@ -663,6 +706,7 @@ async def get_gguf_variants_response(
# Local directory path (e.g. LM Studio models) — scan filesystem
if is_local_path(repo_id):
variants, has_vision = list_local_gguf_variants(repo_id)
+ answered_from[0] = repo_id
# The load id is this path, so a quant offered here has to resolve here.
return _local_response(repo_id, variants, has_vision, _complete_quants_under(repo_id))
@@ -678,6 +722,7 @@ async def get_gguf_variants_response(
variants, has_vision = list_local_gguf_variants(str(snapshot_scope))
if not (variants or has_vision):
return None
+ answered_from[0] = str(snapshot_scope)
return _with_state_partials(
_local_response(
repo_id, variants, has_vision, _complete_quants_under(str(snapshot_scope))
@@ -692,6 +737,10 @@ async def get_gguf_variants_response(
cached = list_gguf_variants_from_hf_cache(repo_id, root = hub_cache)
if cached is not None:
variants, has_vision, complete = cached
+ # This listing is scoped to one cache, so name it: a repo-wide walk starts at
+ # the active cache and could read a different copy's context length.
+ if repo_cache_dir is not None and repo_cache_dir.is_dir():
+ answered_from[0] = str(repo_cache_dir)
# The lister leaves torn quants in: they stay listed for management, but not ready.
return _with_state_partials(
_local_response(repo_id, variants, has_vision, complete)
@@ -699,6 +748,7 @@ async def get_gguf_variants_response(
if local_path and is_local_path(local_path):
variants, has_vision = list_local_gguf_variants(local_path)
if variants or has_vision:
+ answered_from[0] = local_path
# Same reason as the is_local_path branch above.
return _local_response(
repo_id, variants, has_vision, _complete_quants_under(local_path)
@@ -990,7 +1040,12 @@ async def get_gguf_variants_response(
default_variant = default_variant,
)
- def _compute_with_cleanables() -> GgufVariantsResponse:
+ def _compute_with_cleanables() -> VariantsAnswer:
+ # Returned with the answer, not read from the closure afterwards: coalesced callers
+ # share one computation and must all see the copy it actually answered from.
+ return VariantsAnswer(_compute_response(), answered_from[0])
+
+ def _compute_response() -> GgufVariantsResponse:
skip = is_local_path(repo_id) or not _is_valid_repo_id(repo_id)
try:
response = _compute()
@@ -1016,8 +1071,20 @@ async def get_gguf_variants_response(
_repo_cache_dir_for_request(repo_id, local_path),
)
+ from utils.hf_cache_settings import configured_cache_key
+
+ inflight_key = (
+ repo_id,
+ bool(prefer_local_cache),
+ bool(offline),
+ local_path or "",
+ hf_cache_scan.token_fingerprint(hf_token),
+ # Switching cache storage must start a fresh scan rather than join one that is
+ # stuck on the old volume.
+ configured_cache_key(),
+ )
try:
- return await asyncio.to_thread(_compute_with_cleanables)
+ return await _shared_variants_scan(inflight_key, _compute_with_cleanables)
except HTTPException:
raise
except Exception as e:
@@ -1031,3 +1098,21 @@ async def get_gguf_variants_response(
status_code = 500,
detail = "Failed to list GGUF variants: " + scrubbed,
)
+
+
+async def get_gguf_variants_response(
+ repo_id: str,
+ prefer_local_cache: bool = False,
+ offline: bool = False,
+ local_path: Optional[str] = None,
+ hf_token: Optional[str] = None,
+) -> GgufVariantsResponse:
+ """The listing alone, for callers that do not read metadata off the same copy."""
+ answer = await get_gguf_variants_answer(
+ repo_id,
+ prefer_local_cache = prefer_local_cache,
+ offline = offline,
+ local_path = local_path,
+ hf_token = hf_token,
+ )
+ return answer.response
diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.py
index 837b01c3c46..b1e5da974a8 100644
--- a/studio/backend/routes/models.py
+++ b/studio/backend/routes/models.py
@@ -10,7 +10,10 @@ import os
import re
import shutil
import sys
+import threading
+import time
import uuid
+import weakref
from pathlib import Path
from fastapi import APIRouter, Body, Depends, Header, HTTPException, Query
from pydantic import BaseModel
@@ -2717,14 +2720,102 @@ async def check_embedding_model(
)
+# Budget for the walk below: a slow volume or a large tree can far outlast the
+# listing it is attached to.
+_NATIVE_CONTEXT_READ_TIMEOUT_SECONDS = 5.0
+# Backstop for the case the walk's own budget cannot cover: a single syscall that
+# never returns, which no in-loop check can interrupt. Longer than the walk budget,
+# so a responding filesystem always ends the walk itself and this never fires.
+_NATIVE_CONTEXT_HARD_TIMEOUT_SECONDS = 8.0
+# Reads running at once. A read stranded on a hung mount holds its slot, so retries wait
+# for one instead of starting a thread apiece.
+_NATIVE_CONTEXT_MAX_CONCURRENT_READS = 4
+_NATIVE_CONTEXT_SLOTS: "weakref.WeakKeyDictionary" = weakref.WeakKeyDictionary()
+
+
+def _native_context_slots() -> asyncio.Semaphore:
+ """Per running loop, since an asyncio primitive cannot be shared across loops."""
+ loop = asyncio.get_running_loop()
+ slots = _NATIVE_CONTEXT_SLOTS.get(loop)
+ if slots is None:
+ slots = asyncio.Semaphore(_NATIVE_CONTEXT_MAX_CONCURRENT_READS)
+ _NATIVE_CONTEXT_SLOTS[loop] = slots
+ return slots
+
+
+def _settle_native_context(
+ slots: asyncio.Semaphore, future: "asyncio.Future", value: Optional[int]
+) -> None:
+ slots.release()
+ if not future.done():
+ future.set_result(value)
+
+
+async def _read_native_context_length_bounded(model: str, is_local: bool) -> Optional[int]:
+ """``_read_native_context_length`` off the event loop, with a hard bound.
+
+ Reporting None costs a pre-filled context field; waiting costs the whole variant
+ listing, which is what left the picker on "Loading variants…". Runs on a daemon
+ thread, not a pool: a stranded read must not join at interpreter exit, which would
+ hang shutdown for as long as the mount stays hung. Waiting for a slot is awaited
+ rather than skipped, so ordinary concurrent reads queue instead of losing their
+ length; the wait and the read share one budget.
+ """
+ slots = _native_context_slots()
+ began = time.monotonic()
+ try:
+ await asyncio.wait_for(slots.acquire(), timeout = _NATIVE_CONTEXT_HARD_TIMEOUT_SECONDS)
+ except asyncio.TimeoutError:
+ logger.debug("native context read for '%s' waited out its slot; reporting none", model)
+ return None
+
+ remaining = _NATIVE_CONTEXT_HARD_TIMEOUT_SECONDS - (time.monotonic() - began)
+ loop = asyncio.get_running_loop()
+ future: "asyncio.Future" = loop.create_future()
+
+ def worker() -> None:
+ try:
+ value = _read_native_context_length(model, is_local = is_local)
+ except Exception:
+ value = None
+ try:
+ loop.call_soon_threadsafe(_settle_native_context, slots, future, value)
+ except RuntimeError:
+ pass # loop already closed; nothing is waiting on this
+
+ if remaining <= 0:
+ slots.release()
+ return None
+ try:
+ threading.Thread(target = worker, name = "native-ctx", daemon = True).start()
+ except RuntimeError:
+ slots.release() # thread never ran, so it will never release
+ return None
+
+ try:
+ return await asyncio.wait_for(future, timeout = remaining)
+ except asyncio.TimeoutError:
+ logger.debug("native context read for '%s' did not return; reporting none", model)
+ return None
+
+
def _read_native_context_length(repo_id: str, is_local: bool) -> Optional[int]:
"""Native max context from a downloaded GGUF for this repo, or None.
The value is identical across quants, so reading one non-mmproj shard's
header is enough. Only resolves once a file is on disk. Never raises.
+
+ Bounded by ``_NATIVE_CONTEXT_READ_TIMEOUT_SECONDS``: this only pre-fills a
+ context field on an already selectable row, so a dragging walk reports None
+ rather than holding the variant listing open. Checked between files, and
+ files already read stay cached, so a later request resumes.
"""
try:
from utils.models.gguf_metadata import read_gguf_context_length
+
+ # Before cache discovery, which touches the filesystem too: started after, a slow
+ # enumeration would hand the walk a full fresh budget on top of its own cost.
+ deadline = time.monotonic() + _NATIVE_CONTEXT_READ_TIMEOUT_SECONDS
if is_local:
roots = [Path(repo_id)]
else:
@@ -2734,7 +2825,13 @@ def _read_native_context_length(repo_id: str, is_local: bool) -> Optional[int]:
roots = list(iter_repo_cache_dirs("model", repo_id))
for root in roots:
- for f in _iter_gguf_paths(root):
+ if time.monotonic() >= deadline:
+ logger.debug("native context read for '%s' out of budget", repo_id)
+ return None
+ for f in _iter_gguf_paths(root, deadline):
+ if time.monotonic() >= deadline:
+ logger.debug("native context read for '%s' out of budget", repo_id)
+ return None
if _is_mmproj_filename(f.name):
continue
n = read_gguf_context_length(str(f))
@@ -2872,6 +2969,7 @@ async def get_gguf_variants(
..., description = "HuggingFace repo ID (e.g. 'unsloth/gemma-3-4b-it-GGUF')"
),
prefer_local_cache: bool = False,
+ offline: bool = False,
local_path: Optional[str] = None,
hf_token: Optional[str] = Query(None, description = "HuggingFace token for private repos"),
hf_token_header: Optional[str] = Depends(get_hf_token),
@@ -2882,17 +2980,20 @@ async def get_gguf_variants(
hf_token = _normalize_hf_token(hf_token_header) or _normalize_hf_token(hf_token)
from hub.services.models import gguf_variants as hub_gguf_variants
- response = await hub_gguf_variants.get_gguf_variants_response(
+ answer = await hub_gguf_variants.get_gguf_variants_answer(
repo_id,
prefer_local_cache = prefer_local_cache,
+ offline = offline,
local_path = local_path,
hf_token = hf_token,
)
- # A pin names the copy that will load; a repo-wide walk can read another revision's length.
- context_model = hub_gguf_variants.pinned_snapshot_for_request(repo_id, local_path) or (
- local_path
- if prefer_local_cache and local_path and is_local_path(local_path)
- else repo_id
+ response = answer.response
+ # The copy the listing answered from, else the pin naming the copy that will load.
+ # Both beat a repo-wide walk, which can read another revision's length.
+ context_model = (
+ answer.context_source
+ or hub_gguf_variants.pinned_snapshot_for_request(repo_id, local_path)
+ or repo_id
)
local = is_local_path(context_model)
@@ -2914,11 +3015,7 @@ async def get_gguf_variants(
],
has_vision = response.has_vision,
default_variant = response.default_variant,
- # The header walk reads tokenizer arrays on dense models (tens of
- # ms per uncached file); keep it off the event loop.
- context_length = await asyncio.to_thread(
- _read_native_context_length, context_model, is_local = local
- ),
+ context_length = await _read_native_context_length_bounded(context_model, local),
)
except HTTPException:
raise
@@ -3130,8 +3227,13 @@ def _cached_gguf_row_has_vision(repo_info, load_id: Optional[str]) -> bool:
return True
-def _iter_gguf_paths(root: Path):
+def _iter_gguf_paths(root: Path, deadline: Optional[float] = None):
+ """GGUF files under ``root``. With a ``deadline`` (time.monotonic), gives up mid-walk:
+ only .gguf files are yielded, so a large tree can walk for a long time yielding nothing,
+ and a caller checking its budget per yield would never get to check it."""
for path in root.rglob("*"):
+ if deadline is not None and time.monotonic() >= deadline:
+ return
if path.is_file() and _is_gguf_filename(path.name):
yield path
diff --git a/studio/backend/tests/test_cached_gguf_routes.py b/studio/backend/tests/test_cached_gguf_routes.py
index 4444f28649c..94e6c4feb7a 100644
--- a/studio/backend/tests/test_cached_gguf_routes.py
+++ b/studio/backend/tests/test_cached_gguf_routes.py
@@ -3,6 +3,8 @@
import asyncio
import sys
+import threading
+import time
import types
from pathlib import Path
from types import SimpleNamespace
@@ -25,6 +27,25 @@ import routes.models as models_route
from hub.services.models import gguf_variants as GV
+def _answer(
+ repo_id,
+ variants = (),
+ *,
+ default_variant = None,
+ source = None,
+):
+ """The (listing, source) pair the route consumes; *source* is the copy it came from."""
+ return GV.VariantsAnswer(
+ SimpleNamespace(
+ repo_id = repo_id,
+ variants = list(variants),
+ has_vision = False,
+ default_variant = default_variant,
+ ),
+ source,
+ )
+
+
def _repo(
repo_id: str,
files: list[SimpleNamespace],
@@ -1821,15 +1842,10 @@ def test_gguf_variants_route_scopes_local_probe_to_selected_cache(monkeypatch, t
async def scoped_variants(repo_id, **kwargs):
calls.append((repo_id, kwargs))
- return SimpleNamespace(
- repo_id = repo_id,
- variants = [],
- has_vision = False,
- default_variant = None,
- )
+ return _answer(repo_id)
context_calls = []
- monkeypatch.setattr(GV, "get_gguf_variants_response", scoped_variants)
+ monkeypatch.setattr(GV, "get_gguf_variants_answer", scoped_variants)
monkeypatch.setattr(
models_route,
"_read_native_context_length",
@@ -1851,6 +1867,7 @@ def test_gguf_variants_route_scopes_local_probe_to_selected_cache(monkeypatch, t
"org/repo",
{
"prefer_local_cache": True,
+ "offline": False,
"local_path": str(snapshot),
"hf_token": None,
},
@@ -1867,10 +1884,10 @@ def test_gguf_variants_route_reads_context_from_the_pinned_snapshot(monkeypatch,
snapshot.mkdir(parents = True)
async def scoped_variants(repo_id, **kwargs):
- return SimpleNamespace(repo_id = repo_id, variants = [], has_vision = False, default_variant = None)
+ return _answer(repo_id)
context_calls = []
- monkeypatch.setattr(GV, "get_gguf_variants_response", scoped_variants)
+ monkeypatch.setattr(GV, "get_gguf_variants_answer", scoped_variants)
monkeypatch.setattr(
models_route,
"_read_native_context_length",
@@ -1897,10 +1914,10 @@ def test_gguf_variants_route_ignores_a_pin_naming_another_repo(monkeypatch, tmp_
other.mkdir(parents = True)
async def scoped_variants(repo_id, **kwargs):
- return SimpleNamespace(repo_id = repo_id, variants = [], has_vision = False, default_variant = None)
+ return _answer(repo_id)
context_calls = []
- monkeypatch.setattr(GV, "get_gguf_variants_response", scoped_variants)
+ monkeypatch.setattr(GV, "get_gguf_variants_answer", scoped_variants)
monkeypatch.setattr(
models_route,
"_read_native_context_length",
@@ -1920,6 +1937,294 @@ def test_gguf_variants_route_ignores_a_pin_naming_another_repo(monkeypatch, tmp_
assert context_calls == [("org/repo", False)]
+def test_gguf_variants_route_forwards_offline(monkeypatch):
+ """Parity with /api/hub/gguf-variants: without this an unreachable Hub still sends the
+ picker down the remote path."""
+ calls = []
+
+ async def scoped_variants(repo_id, **kwargs):
+ calls.append(kwargs)
+ return _answer(repo_id)
+
+ monkeypatch.setattr(GV, "get_gguf_variants_answer", scoped_variants)
+ monkeypatch.setattr(
+ models_route, "_read_native_context_length", lambda model, *, is_local: None
+ )
+
+ asyncio.run(
+ models_route.get_gguf_variants(
+ repo_id = "org/repo",
+ offline = True,
+ hf_token = None,
+ current_subject = "test-user",
+ )
+ )
+
+ assert calls == [
+ {"prefer_local_cache": False, "offline": True, "local_path": None, "hf_token": None}
+ ]
+
+
+def test_native_context_read_gives_up_when_the_cache_walk_drags(monkeypatch, tmp_path):
+ """Unbounded, this walk held the variant listing open, leaving the picker on
+ "Loading variants…" with no quant to click. It reports None and stops walking instead."""
+ visited = []
+
+ def dragging_walk(root, deadline = None):
+ for index in range(200):
+ time.sleep(0.01)
+ visited.append(index)
+ yield Path(root) / f"model-{index}.gguf"
+
+ monkeypatch.setattr(models_route, "_iter_gguf_paths", dragging_walk)
+ monkeypatch.setattr(models_route, "_NATIVE_CONTEXT_READ_TIMEOUT_SECONDS", 0.1)
+
+ started = time.monotonic()
+ result = models_route._read_native_context_length(str(tmp_path), is_local = True)
+ elapsed = time.monotonic() - started
+
+ assert result is None
+ # A signature drift here raises inside the broad except and returns instantly, which
+ # would pass every other assertion without walking anything.
+ assert visited, "the walk never ran, so this proves nothing"
+ assert elapsed < 2
+ assert len(visited) < 200
+
+
+def test_native_context_read_budget_binds_on_a_walk_that_yields_nothing(monkeypatch, tmp_path):
+ """_iter_gguf_paths yields only .gguf files, so a large cache can walk a long time
+ yielding nothing. Checking the budget per yield alone would never check it at all."""
+ handed = []
+
+ def walk(root, deadline = None):
+ handed.append(deadline)
+ for _ in range(200):
+ time.sleep(0.005)
+ if deadline is not None and time.monotonic() >= deadline:
+ return
+ return
+ yield # pragma: no cover
+
+ monkeypatch.setattr(models_route, "_iter_gguf_paths", walk)
+ monkeypatch.setattr(models_route, "_NATIVE_CONTEXT_READ_TIMEOUT_SECONDS", 0.05)
+
+ started = time.monotonic()
+ assert models_route._read_native_context_length(str(tmp_path), is_local = True) is None
+ assert handed and handed[0] is not None, "the walker was given no deadline"
+ assert time.monotonic() - started < 1
+
+
+def test_native_context_read_budget_is_checked_between_caches(monkeypatch, tmp_path):
+ """A repo present in several caches must not restart the budget per cache."""
+ walked = []
+
+ def walk(root, deadline = None):
+ walked.append(str(root))
+ time.sleep(0.2)
+ return iter(())
+
+ monkeypatch.setattr(models_route, "_iter_gguf_paths", walk)
+ monkeypatch.setattr(models_route, "_NATIVE_CONTEXT_READ_TIMEOUT_SECONDS", 0.05)
+ monkeypatch.setattr(models_route, "_is_valid_repo_id", lambda _r: True)
+ monkeypatch.setattr(
+ "hub.utils.hf_cache_state.iter_repo_cache_dirs",
+ lambda _kind, _repo: [tmp_path / "a", tmp_path / "b", tmp_path / "c"],
+ )
+
+ models_route._read_native_context_length("org/repo", is_local = False)
+ assert len(walked) < 3, f"every cache was walked despite the budget: {walked}"
+
+
+def test_native_context_read_budget_covers_cache_discovery(monkeypatch, tmp_path):
+ """Cache enumeration touches the filesystem too. Started after it, the budget would hand
+ the walk a full fresh allowance on top of whatever discovery already cost."""
+
+ def slow_discovery(_kind, _repo):
+ time.sleep(0.4)
+ return [tmp_path / "a", tmp_path / "b", tmp_path / "c"]
+
+ def slow_walk(root, deadline = None):
+ time.sleep(0.3)
+ return iter(())
+
+ monkeypatch.setattr(models_route, "_is_valid_repo_id", lambda _r: True)
+ monkeypatch.setattr("hub.utils.hf_cache_state.iter_repo_cache_dirs", slow_discovery)
+ monkeypatch.setattr(models_route, "_iter_gguf_paths", slow_walk)
+ monkeypatch.setattr(models_route, "_NATIVE_CONTEXT_READ_TIMEOUT_SECONDS", 0.05)
+
+ started = time.monotonic()
+ assert models_route._read_native_context_length("org/repo", is_local = False) is None
+ # Discovery itself is not interruptible; a walk on top of it means the budget restarted.
+ assert time.monotonic() - started < 0.55
+
+
+def test_gguf_variants_route_answers_when_a_header_read_never_returns(monkeypatch, tmp_path):
+ """One syscall that never returns cannot be interrupted from inside the walk, so the
+ route bounds it. Without that the listing waits on it and the picker has nothing to click."""
+ (tmp_path / "model-Q4_K_M.gguf").write_bytes(b"x")
+
+ def hung_read(_path):
+ time.sleep(5)
+ return 8192
+
+ monkeypatch.setattr("utils.models.gguf_metadata.read_gguf_context_length", hung_read)
+ monkeypatch.setattr(models_route, "_NATIVE_CONTEXT_READ_TIMEOUT_SECONDS", 0.05)
+ monkeypatch.setattr(models_route, "_NATIVE_CONTEXT_HARD_TIMEOUT_SECONDS", 0.2)
+
+ async def scoped_variants(repo_id, **kwargs):
+ return _answer(
+ repo_id,
+ [
+ SimpleNamespace(
+ filename = "model-Q4_K_M.gguf",
+ quant = "Q4_K_M",
+ size_bytes = 10,
+ download_size_bytes = 10,
+ downloaded = True,
+ )
+ ],
+ default_variant = "Q4_K_M",
+ )
+
+ monkeypatch.setattr(GV, "get_gguf_variants_answer", scoped_variants)
+
+ async def drive():
+ began = time.monotonic()
+ answer = await models_route.get_gguf_variants(
+ repo_id = str(tmp_path), hf_token = None, current_subject = "test-user"
+ )
+ return answer, time.monotonic() - began
+
+ result, elapsed = asyncio.run(drive())
+ assert [v.quant for v in result.variants] == ["Q4_K_M"]
+ assert result.context_length is None
+ assert elapsed < 3
+
+
+def test_native_context_read_runs_on_a_daemon_thread(monkeypatch):
+ """A thread pool's workers are joined at interpreter exit, so a read abandoned on a hung
+ mount would hold up shutdown for as long as the mount stays hung (measured: the full
+ length of the read). A daemon thread does not."""
+ observed = {}
+ entered = threading.Event()
+
+ def stalled(model, *, is_local):
+ observed["daemon"] = threading.current_thread().daemon
+ entered.set()
+ time.sleep(0.5)
+ return 8192
+
+ monkeypatch.setattr(models_route, "_read_native_context_length", stalled)
+ monkeypatch.setattr(models_route, "_NATIVE_CONTEXT_HARD_TIMEOUT_SECONDS", 0.1)
+
+ async def drive():
+ return await models_route._read_native_context_length_bounded("/tmp", True)
+
+ assert asyncio.run(drive()) is None
+ assert entered.wait(3)
+ assert observed["daemon"] is True
+
+
+def _live_context_threads() -> int:
+ return sum(1 for thread in threading.enumerate() if thread.name == "native-ctx")
+
+
+def _drain_context_threads(timeout: float = 5.0) -> None:
+ """Reads abandoned by an earlier test outlive it, so wait them out before counting."""
+ end = time.monotonic() + timeout
+ while _live_context_threads() and time.monotonic() < end:
+ time.sleep(0.02)
+
+
+def test_native_context_reads_stop_starting_once_every_slot_is_stranded(monkeypatch):
+ """Retries against a hung mount must not start a thread apiece; they wait for a slot
+ and give up inside the bound."""
+ release = threading.Event()
+
+ def stalled(model, *, is_local):
+ release.wait(5)
+ return 8192
+
+ monkeypatch.setattr(models_route, "_read_native_context_length", stalled)
+ monkeypatch.setattr(models_route, "_NATIVE_CONTEXT_HARD_TIMEOUT_SECONDS", 0.1)
+ monkeypatch.setattr(models_route, "_NATIVE_CONTEXT_MAX_CONCURRENT_READS", 2)
+ _drain_context_threads()
+
+ async def drive():
+ for _ in range(2): # strand every slot
+ assert await models_route._read_native_context_length_bounded("/tmp", True) is None
+ live_before = _live_context_threads()
+ began = time.monotonic()
+ answer = await models_route._read_native_context_length_bounded("/tmp", True)
+ return answer, time.monotonic() - began, live_before, _live_context_threads()
+
+ try:
+ answer, elapsed, before, after = asyncio.run(drive())
+ assert answer is None
+ assert elapsed < 1 # gave up inside the bound rather than waiting on the mount
+ assert before == 2 # the cap held
+ assert after <= before # and nothing new was started
+ finally:
+ release.set()
+
+
+def test_concurrent_native_context_reads_all_keep_their_length(monkeypatch):
+ """Ordinary concurrency must queue for a slot, not skip the read. Giving up when no slot
+ was free on the spot dropped most lengths on a healthy cache (measured 4 of 64)."""
+ monkeypatch.setattr(
+ models_route,
+ "_read_native_context_length",
+ lambda model, *, is_local: (time.sleep(0.002), 8192)[1],
+ )
+
+ async def drive():
+ return await asyncio.gather(
+ *[models_route._read_native_context_length_bounded("/tmp", True) for _ in range(64)]
+ )
+
+ assert asyncio.run(drive()) == [8192] * 64
+
+
+def test_offline_reads_context_from_the_copy_the_variants_came_from(monkeypatch, tmp_path):
+ """The length has to come from the copy the listing came from. Which copy that is cannot
+ be read off the request: the HF cache answers before local_path, so the service reports
+ it and the route follows."""
+ context_calls = []
+
+ async def scoped_variants(repo_id, **kwargs):
+ return _answer(repo_id, source = kwargs["local_path"])
+
+ monkeypatch.setattr(GV, "get_gguf_variants_answer", scoped_variants)
+ monkeypatch.setattr(
+ models_route,
+ "_read_native_context_length",
+ lambda model, *, is_local: context_calls.append((model, is_local)) or 4096,
+ )
+
+ asyncio.run(
+ models_route.get_gguf_variants(
+ repo_id = "org/repo",
+ offline = True,
+ prefer_local_cache = False,
+ local_path = str(tmp_path),
+ hf_token = None,
+ current_subject = "test-user",
+ )
+ )
+ assert context_calls == [(str(tmp_path), True)]
+
+
+def test_native_context_read_still_reports_a_length_within_budget(monkeypatch, tmp_path):
+ """Control: the bound only trims a walk that drags; a header reached in time still answers."""
+ gguf = tmp_path / "model-Q4_K_M.gguf"
+ gguf.write_bytes(b"x")
+
+ monkeypatch.setattr(models_route, "_iter_gguf_paths", lambda root, deadline = None: iter([gguf]))
+ monkeypatch.setattr("utils.models.gguf_metadata.read_gguf_context_length", lambda _path: 8192)
+
+ assert models_route._read_native_context_length(str(tmp_path), is_local = True) == 8192
+
+
def test_gguf_variants_ignore_big_endian_siblings(monkeypatch, tmp_path):
siblings = [
SimpleNamespace(rfilename = "model-Q4_K_M-be.gguf", size = 100),
@@ -2204,3 +2509,244 @@ def test_a_cancelled_siblings_marker_shows_on_the_repo_row(monkeypatch, tmp_path
assert after["last_modified"] == before["last_modified"]
assert after["partial"] is False
assert after["has_variant_state"] is True
+
+
+def test_identical_variant_scans_in_flight_run_once(monkeypatch):
+ """Aborting the HTTP request cannot stop the scan already running in its thread, so the
+ picker's Retry would start another against a filesystem that is not answering. Measured
+ before this: 23 retries filled all 20 default-executor workers and starved unrelated
+ offloaded work."""
+ scans = []
+ release = threading.Event()
+
+ def slow_scan(path):
+ scans.append(path)
+ release.wait(5)
+ return ([], False)
+
+ monkeypatch.setattr(GV, "is_local_path", lambda _p: True)
+ monkeypatch.setattr(GV, "list_local_gguf_variants", slow_scan)
+
+ async def drive():
+ pending = [
+ asyncio.ensure_future(GV.get_gguf_variants_response("/models/x")) for _ in range(8)
+ ]
+ await asyncio.sleep(0.1)
+ release.set()
+ return await asyncio.gather(*pending)
+
+ try:
+ results = asyncio.run(drive())
+ finally:
+ release.set()
+
+ assert len(results) == 8
+ assert len(scans) == 1, f"the scan ran {len(scans)} times"
+
+
+def test_variant_scans_for_different_requests_do_not_share(monkeypatch):
+ """Coalescing must key on everything that changes the answer."""
+ scans = []
+
+ def scan(path):
+ scans.append(path)
+ return ([], False)
+
+ monkeypatch.setattr(GV, "is_local_path", lambda _p: True)
+ monkeypatch.setattr(GV, "list_local_gguf_variants", scan)
+
+ async def drive():
+ await GV.get_gguf_variants_response("/models/a")
+ await GV.get_gguf_variants_response("/models/b")
+ await GV.get_gguf_variants_response("/models/a", offline = True)
+ await GV.get_gguf_variants_response("/models/a", local_path = "/other")
+
+ asyncio.run(drive())
+ assert len(scans) == 4
+
+
+def test_a_failed_variant_scan_is_not_pinned(monkeypatch):
+ """A failure must reach every waiter and leave nothing cached, or one bad scan would
+ answer for the rest of the session."""
+ attempts = []
+
+ def failing_scan(path):
+ attempts.append(path)
+ raise OSError("mount went away")
+
+ monkeypatch.setattr(GV, "is_local_path", lambda _p: True)
+ monkeypatch.setattr(GV, "list_local_gguf_variants", failing_scan)
+
+ async def drive():
+ for _ in range(3):
+ with pytest.raises(Exception):
+ await GV.get_gguf_variants_response("/models/x")
+
+ asyncio.run(drive())
+ assert len(attempts) == 3, "a failure was reused instead of retried"
+
+
+def test_one_caller_giving_up_leaves_the_scan_for_the_others(monkeypatch):
+ """The picker abandons its request when the row collapses; the caller still waiting
+ must still get an answer."""
+ release = threading.Event()
+ scans = []
+
+ def slow_scan(path):
+ scans.append(path)
+ release.wait(5)
+ return ([], False)
+
+ monkeypatch.setattr(GV, "is_local_path", lambda _p: True)
+ monkeypatch.setattr(GV, "list_local_gguf_variants", slow_scan)
+
+ async def drive():
+ staying = asyncio.ensure_future(GV.get_gguf_variants_response("/models/x"))
+ leaving = asyncio.ensure_future(GV.get_gguf_variants_response("/models/x"))
+ await asyncio.sleep(0.1)
+ leaving.cancel()
+ release.set()
+ return await staying
+
+ try:
+ answer = asyncio.run(drive())
+ finally:
+ release.set()
+
+ assert answer.repo_id == "/models/x"
+ assert len(scans) == 1
+
+
+def test_offline_context_follows_the_hf_cache_when_it_answers(monkeypatch, tmp_path):
+ """The HF cache answers before local_path, so with both present the length must come
+ from the cache. Picking local_path on the offline flag alone attached another copy's
+ context to the cache's variants. Real service, no stub."""
+ context_calls = []
+
+ monkeypatch.setattr(
+ GV,
+ "list_gguf_variants_from_hf_cache",
+ lambda repo_id, root = None: (
+ [
+ SimpleNamespace(
+ filename = "m-Q4_K_M.gguf",
+ quant = "Q4_K_M",
+ display_label = None,
+ size_bytes = 10,
+ )
+ ],
+ False,
+ {"q4_k_m"},
+ ),
+ )
+ monkeypatch.setattr(GV, "list_partial_gguf_variants_from_state", lambda *a, **k: None)
+ monkeypatch.setattr(
+ models_route,
+ "_read_native_context_length",
+ lambda model, *, is_local: context_calls.append((model, is_local)) or 4096,
+ )
+
+ asyncio.run(
+ models_route.get_gguf_variants(
+ repo_id = "org/repo",
+ offline = True,
+ local_path = str(tmp_path), # an ordinary directory, not this repo's cache
+ hf_token = None,
+ current_subject = "test-user",
+ )
+ )
+ assert context_calls == [("org/repo", False)]
+
+
+def test_offline_context_follows_the_cache_the_variants_were_read_from(monkeypatch, tmp_path):
+ """A local_path under a non-active cache scopes the listing to that cache, so the length
+ has to come from there too. Falling back to the repo id walks every cache, active one
+ first, and can attach another copy's context to these variants. Real service, no stub."""
+ legacy_repo = tmp_path / "legacy" / "hub" / "models--org--repo"
+ (legacy_repo / "snapshots" / "rev").mkdir(parents = True)
+ context_calls = []
+
+ monkeypatch.setattr(
+ GV,
+ "list_gguf_variants_from_hf_cache",
+ lambda repo_id, root = None: (
+ [
+ SimpleNamespace(
+ filename = "m-Q4_K_M.gguf",
+ quant = "Q4_K_M",
+ display_label = None,
+ size_bytes = 10,
+ )
+ ],
+ False,
+ {"q4_k_m"},
+ ),
+ )
+ monkeypatch.setattr(GV, "list_partial_gguf_variants_from_state", lambda *a, **k: None)
+ monkeypatch.setattr(
+ models_route,
+ "_read_native_context_length",
+ lambda model, *, is_local: context_calls.append((model, is_local)) or 4096,
+ )
+
+ asyncio.run(
+ models_route.get_gguf_variants(
+ repo_id = "org/repo",
+ offline = True,
+ local_path = str(legacy_repo),
+ hf_token = None,
+ current_subject = "test-user",
+ )
+ )
+ assert context_calls == [(str(legacy_repo), True)]
+
+
+def test_switching_cache_storage_does_not_join_a_stuck_scan(monkeypatch, tmp_path):
+ """Pointing Studio at another cache has to start a fresh scan. Coalescing on the request
+ alone made the new request wait on the scan wedged against the old volume."""
+ import storage.studio_db as studio_db
+ import utils.hf_cache_settings as hf_cache_settings
+
+ wedged = threading.Event()
+ cache_home = [tmp_path / "wedgedvol"]
+ scanned = []
+
+ # Only the stored setting picks the cache home here.
+ monkeypatch.setattr(hf_cache_settings, "_EXPLICIT_CACHE_ENV", {})
+ monkeypatch.setattr(
+ studio_db,
+ "get_app_setting",
+ lambda key, default = None: (
+ str(cache_home[0]) if key == hf_cache_settings.CACHE_HOME_SETTING_KEY else default
+ ),
+ )
+
+ def scan(repo_id, root = None):
+ scanned.append(str(root))
+ if "wedgedvol" in str(root):
+ wedged.wait(5)
+ return None
+
+ monkeypatch.setattr(GV, "list_gguf_variants_from_hf_cache", scan)
+ monkeypatch.setattr(GV, "list_partial_gguf_variants_from_state", lambda *a, **k: None)
+ monkeypatch.setattr(GV, "list_local_gguf_variants", lambda _p: ([], False))
+ monkeypatch.setattr(GV, "_snapshot_scope_for_request", lambda *a, **k: None)
+
+ async def drive():
+ stuck = asyncio.ensure_future(GV.get_gguf_variants_answer("org/repo", offline = True))
+ await asyncio.sleep(0.2)
+ cache_home[0] = tmp_path / "healthyvol"
+ second = asyncio.ensure_future(GV.get_gguf_variants_answer("org/repo", offline = True))
+ done, _ = await asyncio.wait({second}, timeout = 1.5)
+ for task in (stuck, second):
+ task.cancel()
+ return bool(done)
+
+ try:
+ answered = asyncio.run(drive())
+ finally:
+ wedged.set()
+
+ assert any("wedgedvol" in root for root in scanned), scanned
+ assert answered, "the new request waited on the scan stuck against the old cache"
+ assert any("healthyvol" in root for root in scanned), scanned
diff --git a/studio/backend/utils/hf_cache_settings.py b/studio/backend/utils/hf_cache_settings.py
index cc01f0b97ad..73801101ec0 100644
--- a/studio/backend/utils/hf_cache_settings.py
+++ b/studio/backend/utils/hf_cache_settings.py
@@ -123,6 +123,29 @@ def _stored_cache_home() -> Optional[Path]:
return None
+def configured_cache_key() -> str:
+ """The configured cache location, for keying caches and in-flight work.
+
+ Deliberately unresolved: resolve() can block on the very volume a caller is
+ trying to move off. Only equality matters here, not the real path.
+ """
+ explicit = (
+ _EXPLICIT_CACHE_ENV.get("HF_HUB_CACHE")
+ or _EXPLICIT_CACHE_ENV.get("HUGGINGFACE_HUB_CACHE")
+ or _EXPLICIT_CACHE_ENV.get("HF_HOME")
+ )
+ if explicit:
+ return "env:" + explicit
+ try:
+ from storage.studio_db import get_app_setting
+ value = get_app_setting(CACHE_HOME_SETTING_KEY, None)
+ except Exception:
+ return "default"
+ if isinstance(value, str) and value.strip():
+ return "studio:" + value.strip()
+ return "default"
+
+
def get_hf_cache_paths() -> HuggingFaceCachePaths:
env_paths = _environment_paths()
if env_paths is not None:
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index 5d15ab80eab..eb4e6b7e79d 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -8,6 +8,8 @@ import { prepareHfTokenForUse } from "@/features/hf-auth";
// eslint-disable-next-line no-restricted-imports
import { hubTokenHeader } from "@/features/hub/lib/hub-token-header";
// eslint-disable-next-line no-restricted-imports
+import { isHuggingFaceOffline } from "@/features/hub/lib/network";
+// eslint-disable-next-line no-restricted-imports
import { consumeNativePathToken } from "@/features/native-intents/api";
import { formatFastApiDetail } from "@/lib/format-fastapi-error";
import type {
@@ -31,6 +33,11 @@ import type {
UnloadModelRequest,
ValidateModelResponse,
} from "../types/api";
+import {
+ type GgufVariantsRequestOptions,
+ ggufVariantsQuery,
+ runBoundedVariantsRequest,
+} from "./gguf-variants-request";
import { assertCompletedPaddedBody } from "./padded-response";
export const CHAT_HISTORY_UPDATED_EVENT = "unsloth-chat-history-updated";
@@ -1064,23 +1071,16 @@ export async function browseFolders(
export async function listGgufVariants(
repoId: string,
hfToken?: string,
- options?: {
- preferLocalCache?: boolean;
- localPath?: string | null;
- },
+ options?: GgufVariantsRequestOptions,
): Promise<GgufVariantsResponse> {
- const params = new URLSearchParams({ repo_id: repoId });
- if (options?.preferLocalCache) {
- params.set("prefer_local_cache", "true");
- }
- const localPath = options?.localPath?.trim();
- if (localPath) {
- params.set("local_path", localPath);
- }
- const response = await authFetch(`/api/models/gguf-variants?${params}`, {
- headers: hubTokenHeader(hfToken),
+ const params = ggufVariantsQuery(repoId, options, isHuggingFaceOffline());
+ return runBoundedVariantsRequest(options?.signal, async (signal) => {
+ const response = await authFetch(`/api/models/gguf-variants?${params}`, {
+ headers: hubTokenHeader(hfToken),
+ signal,
+ });
+ return parseJsonOrThrow<GgufVariantsResponse>(response);
});
- return parseJsonOrThrow<GgufVariantsResponse>(response);
}
export interface KvCacheEstimate {
diff --git a/studio/frontend/src/features/chat/api/gguf-variants-request.ts b/studio/frontend/src/features/chat/api/gguf-variants-request.ts
new file mode 100644
index 00000000000..397a77e7804
--- /dev/null
+++ b/studio/frontend/src/features/chat/api/gguf-variants-request.ts
@@ -0,0 +1,75 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// How the chat side asks for a repo's GGUF quants. Split out of chat-api so it imports
+// without the auth barrel. The picker's expander and chat auto-load both block on this
+// listing, so an unbounded request leaves the expander on "Loading variants…" forever.
+
+import {
+ type PollSignal,
+ disposableTimeoutSignal,
+ pollSignal,
+ withAbort,
+} from "@/features/hub/lib/abort-signals";
+
+/** Matches the Hub client's bound on the same listing (features/hub/inventory/api.ts). */
+export const GGUF_VARIANTS_TIMEOUT_MS = 30_000;
+
+export interface GgufVariantsRequestOptions {
+ preferLocalCache?: boolean;
+ localPath?: string | null;
+ signal?: AbortSignal;
+}
+
+/**
+ * Query for GET /api/models/gguf-variants. A Hub already known to be unreachable is asked
+ * for the cached answer instead of a remote listing that cannot arrive, as the Hub client does.
+ */
+export function ggufVariantsQuery(
+ repoId: string,
+ options: GgufVariantsRequestOptions | undefined,
+ offline: boolean,
+): URLSearchParams {
+ const params = new URLSearchParams({ repo_id: repoId });
+ if (options?.preferLocalCache || offline) {
+ params.set("prefer_local_cache", "true");
+ }
+ const localPath = options?.localPath?.trim();
+ if (localPath) {
+ params.set("local_path", localPath);
+ }
+ if (offline) {
+ params.set("offline", "true");
+ }
+ return params;
+}
+
+/**
+ * Signal every variant request carries: the caller's abort (the expander drops the request
+ * when its row collapses) folded with the timeout. Callers MUST dispose once settled.
+ */
+export function ggufVariantsAbort(signal?: AbortSignal): PollSignal {
+ return signal
+ ? pollSignal(signal, GGUF_VARIANTS_TIMEOUT_MS)
+ : disposableTimeoutSignal(GGUF_VARIANTS_TIMEOUT_MS);
+}
+
+/**
+ * Runs a listing under the bound and settles on it whatever the request is doing. Handing
+ * the signal to fetch alone is not enough: on a 401 authFetch awaits a shared session
+ * refresh that carries no signal, so the listing could still hang there.
+ */
+export function runBoundedVariantsRequest<T>(
+ signal: AbortSignal | undefined,
+ request: (signal: AbortSignal) => Promise<T>,
+): Promise<T> {
+ const abort = ggufVariantsAbort(signal);
+ let started: Promise<T>;
+ try {
+ started = request(abort.signal);
+ } catch (err) {
+ abort.dispose();
+ return Promise.reject(err);
+ }
+ return withAbort(started, abort.signal).finally(() => abort.dispose());
+}
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
index 264db06a5d2..b307976c74d 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
@@ -147,6 +147,7 @@ import type {
ModelOption,
ModelSelectorChangeMeta,
} from "./types";
+import { describeVariantListingError } from "./variant-listing-error";
import {
shouldMountVariantExpander,
toggleAutoExpandedRow,
@@ -1156,6 +1157,9 @@ function GgufVariantExpander({
useEffect(() => {
let canceled = false;
+ // Collapsing the row drops the request: a stalled one otherwise holds a
+ // per-host connection, and enough of them stall download and load too.
+ const controller = new AbortController();
queueMicrotask(() => {
if (canceled) return;
setLoading(true);
@@ -1164,7 +1168,10 @@ function GgufVariantExpander({
// The row's own directory, so disk contents count against that cache, not the active one. No
// preferLocalCache: it answers from disk alone and drops the undownloaded.
- listGgufVariants(repoId, hfToken, localSource ? { localPath: localSource } : undefined)
+ listGgufVariants(repoId, hfToken, {
+ ...(localSource ? { localPath: localSource } : {}),
+ signal: controller.signal,
+ })
.then((res) => {
if (canceled) return;
const normalized = normalizeGgufVariantsResponse(res);
@@ -1176,9 +1183,7 @@ function GgufVariantExpander({
})
.catch((err) => {
if (canceled) return;
- setError(
- err instanceof Error ? err.message : "Failed to load variants",
- );
+ setError(describeVariantListingError(err));
})
.finally(() => {
if (!canceled) setLoading(false);
@@ -1186,6 +1191,7 @@ function GgufVariantExpander({
return () => {
canceled = true;
+ controller.abort();
};
}, [repoId, localSource, refreshKey, hfToken]);
@@ -1324,7 +1330,18 @@ function GgufVariantExpander({
}
if (error) {
- return <div className="px-5 py-2 text-xs text-destructive">{error}</div>;
+ return (
+ <div className="flex flex-wrap items-center gap-2 px-5 py-2 text-xs text-destructive">
+ <span>{error}</span>
+ <button
+ type="button"
+ onClick={() => setRefreshKey((key) => key + 1)}
+ className="rounded-full border border-destructive/40 px-2 py-0.5 font-medium text-destructive transition-colors hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
+ >
+ Retry
+ </button>
+ </div>
+ );
}
if (!displayVariants || displayVariants.length === 0) {
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/variant-listing-error.ts b/studio/frontend/src/features/model-picker/components/model-selector/variant-listing-error.ts
new file mode 100644
index 00000000000..7f0d9a20bd7
--- /dev/null
+++ b/studio/frontend/src/features/model-picker/components/model-selector/variant-listing-error.ts
@@ -0,0 +1,25 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Read by property, not instanceof: DOMException does not inherit from Error in older
+// WebKit, so `err instanceof Error` misses exactly the aborts this needs to classify.
+function propString(err: unknown, key: "name" | "message"): string {
+ if (typeof err !== "object" || err === null) return "";
+ const value = (err as Record<string, unknown>)[key];
+ return typeof value === "string" ? value : "";
+}
+
+/**
+ * Why a repo's quant listing did not arrive. A raw timeout reads as "The operation timed
+ * out.", which names neither the Hub nor the retry that usually clears it. Engines without
+ * `signal.reason` (Safari < 15.4, older WebKitGTK) report a plain AbortError for a timed-out
+ * fetch, so that counts as a timeout too; a deliberate abort never reaches here, because the
+ * expander drops its result before rendering.
+ */
+export function describeVariantListingError(err: unknown): string {
+ const name = propString(err, "name");
+ if (name === "TimeoutError" || name === "AbortError") {
+ return "Timed out listing quantizations. Check your connection to Hugging Face, then retry.";
+ }
+ return propString(err, "message") || "Failed to load variants";
+}
diff --git a/studio/frontend/tests/gguf-variants-request-bounds.test.ts b/studio/frontend/tests/gguf-variants-request-bounds.test.ts
new file mode 100644
index 00000000000..348aa5294bd
--- /dev/null
+++ b/studio/frontend/tests/gguf-variants-request-bounds.test.ts
@@ -0,0 +1,112 @@
+// 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 picker's quant listing was issued with no abort signal and no offline handling, so
+// an unanswered request left the expander on "Loading variants…" and auto-load behind it,
+// while the Hub page, bounded and offline-aware, kept working.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+// The module reaches the abort-signal ponyfills through "@/".
+registerBundlerResolver();
+const {
+ GGUF_VARIANTS_TIMEOUT_MS,
+ ggufVariantsAbort,
+ ggufVariantsQuery,
+ runBoundedVariantsRequest,
+} = await import("../src/features/chat/api/gguf-variants-request.ts");
+
+const REPO = "unsloth/Qwen3-8B-GGUF";
+
+test("every listing carries a signal, so an unanswered one can still be given up on", () => {
+ const abort = ggufVariantsAbort();
+ try {
+ assert.ok(abort.signal instanceof AbortSignal);
+ assert.equal(abort.signal.aborted, false);
+ } finally {
+ abort.dispose();
+ }
+ assert.ok(GGUF_VARIANTS_TIMEOUT_MS > 0 && Number.isFinite(GGUF_VARIANTS_TIMEOUT_MS));
+});
+
+test("collapsing the row aborts the listing it started", () => {
+ const controller = new AbortController();
+ const abort = ggufVariantsAbort(controller.signal);
+ try {
+ assert.equal(abort.signal.aborted, false);
+ controller.abort();
+ assert.equal(abort.signal.aborted, true);
+ } finally {
+ abort.dispose();
+ }
+});
+
+test("a row already collapsed never opens a request", () => {
+ const controller = new AbortController();
+ controller.abort();
+ const abort = ggufVariantsAbort(controller.signal);
+ try {
+ assert.equal(abort.signal.aborted, true);
+ } finally {
+ abort.dispose();
+ }
+});
+
+test("an unreachable Hub asks for the cached listing", () => {
+ const params = ggufVariantsQuery(REPO, undefined, true);
+ assert.equal(params.get("repo_id"), REPO);
+ assert.equal(params.get("offline"), "true");
+ // Without this the route takes the remote path anyway and spends the whole timeout.
+ assert.equal(params.get("prefer_local_cache"), "true");
+});
+
+test("a reachable Hub is still asked for the remote listing", () => {
+ const params = ggufVariantsQuery(REPO, undefined, false);
+ assert.equal(params.get("offline"), null);
+ assert.equal(params.get("prefer_local_cache"), null);
+});
+
+test("the row's own directory is scoped to, and blank paths are dropped", () => {
+ const scoped = ggufVariantsQuery(
+ REPO,
+ { preferLocalCache: true, localPath: " /models/qwen " },
+ false,
+ );
+ assert.equal(scoped.get("local_path"), "/models/qwen");
+ assert.equal(scoped.get("prefer_local_cache"), "true");
+
+ const blank = ggufVariantsQuery(REPO, { localPath: " " }, false);
+ assert.equal(blank.get("local_path"), null);
+});
+
+test("the bound settles the listing even when the request never does", async () => {
+ // authFetch awaits a shared session refresh on a 401, and that refresh carries no signal
+ // of its own. Handing the signal to fetch alone would leave the listing pending there.
+ const caller = new AbortController();
+ let requestSignal: AbortSignal | undefined;
+ const pending = runBoundedVariantsRequest(caller.signal, (signal) => {
+ requestSignal = signal;
+ return new Promise<never>(() => {}); // never settles, like a stalled refresh
+ });
+ caller.abort();
+ await assert.rejects(pending);
+ assert.ok(requestSignal, "the request was never handed a signal");
+});
+
+test("a request that throws synchronously still rejects and disposes", async () => {
+ const caller = new AbortController();
+ await assert.rejects(
+ runBoundedVariantsRequest(caller.signal, () => {
+ throw new Error("boom");
+ }),
+ /boom/,
+ );
+});
+
+test("a successful request passes its value straight through", async () => {
+ const value = await runBoundedVariantsRequest(undefined, async () => "listed");
+ assert.equal(value, "listed");
+});
diff --git a/studio/frontend/tests/variant-listing-error.test.ts b/studio/frontend/tests/variant-listing-error.test.ts
new file mode 100644
index 00000000000..c02d4ce0567
--- /dev/null
+++ b/studio/frontend/tests/variant-listing-error.test.ts
@@ -0,0 +1,38 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Engines disagree on what a timed-out fetch rejects with. Measured in real engines:
+// Chromium and Gecko give TimeoutError, WebKit gives AbortError, and engines without
+// signal.reason (Safari < 15.4, older WebKitGTK) give AbortError whatever we abort with.
+// WebKit is what the desktop app embeds, so classifying only TimeoutError left exactly
+// those users on the generic message.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { describeVariantListingError } from "../src/features/model-picker/components/model-selector/variant-listing-error.ts";
+
+const TIMED_OUT =
+ "Timed out listing quantizations. Check your connection to Hugging Face, then retry.";
+
+test("a timeout is named as one on every engine", () => {
+ assert.equal(describeVariantListingError(new DOMException("x", "TimeoutError")), TIMED_OUT);
+ assert.equal(describeVariantListingError(new DOMException("x", "AbortError")), TIMED_OUT);
+ // Older WebKit: DOMException does not inherit from Error, so instanceof misses it.
+ assert.equal(describeVariantListingError({ name: "TimeoutError" }), TIMED_OUT);
+ assert.equal(describeVariantListingError({ name: "AbortError", message: "" }), TIMED_OUT);
+});
+
+test("a real backend failure keeps its own message", () => {
+ assert.equal(
+ describeVariantListingError(new Error("Failed to list GGUF variants: boom")),
+ "Failed to list GGUF variants: boom",
+ );
+});
+
+test("anything unrecognisable still reads as a failure, never blank", () => {
+ for (const value of [null, undefined, "a string", 42, {}, { name: 42 }, new Error("")]) {
+ assert.equal(describeVariantListingError(value), "Failed to load variants");
+ }
+ assert.equal(describeVariantListingError(Object.create(null)), "Failed to load variants");
+});