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
fix(studio): retain GGUF quants across cache-folder switches (#11938)
Wasim Yousef Said7af93867a18e
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex c26a7105e78..fdc3ccf9f88 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -3050,6 +3050,20 @@ def _resolve_repo_id_casing(hf_repo: str) -> str:return hf_repo+def _cached_gguf_snapshots(repo_id: str):+ """Retain the existing active-cache lookup; add remembered chat copies once."""+ from utils.models.model_config import _iter_hf_cache_snapshots+ from hub.utils.gguf_sources import gguf_cache_snapshots++ seen = set()+ for snapshots in (_iter_hf_cache_snapshots(repo_id), gguf_cache_snapshots(repo_id)):+ for snapshot in snapshots:+ key = str(snapshot.resolve())+ if key not in seen:+ seen.add(key)+ yield snapshot++def _cached_colocated_split_main(repo_id: str, main_filename: str, shards: Iterable[str], expected_sizes: dict[str, int]) -> Optional[str]:@@ -3065,8 +3079,7 @@ def _cached_colocated_split_main(if not main_parts or any(part in (".", "..") for part in main_parts):return Nonetry:- from utils.models.model_config import _iter_hf_cache_snapshots- for snap in _iter_hf_cache_snapshots(repo_id):+ for snap in _cached_gguf_snapshots(repo_id):main_path = snap.joinpath(*main_parts)if not main_path.is_file():continue@@ -3100,8 +3113,13 @@ def _cached_variant_candidates() -> Generator[tuple[str, str, list[str], Path], None, None]:"""Yield complete cached variant copies in snapshot preference order."""try:- from utils.models.model_config import _iter_hf_cache_snapshots- for snap in _iter_hf_cache_snapshots(repo_id):+ from hub.utils.gguf_sources import (+ cached_gguf_manifest_complete,+ cached_gguf_source_partial,+ )++ pending_downloads = []+ for snap in _cached_gguf_snapshots(repo_id):cached_files = _gguf_snapshot_files(snap)matches = _gguf_files_for_variant(cached_files, hf_variant)if not matches:@@ -3124,7 +3142,15 @@ def _cached_variant_candidates(continueif require_mmproj and not _pick_mmproj(cached_files):continue- yield str(main_path), main, shards, snap+ candidate = (str(main_path), main, shards, snap)+ if not cached_gguf_manifest_complete(+ repo_id, hf_variant, snap+ ) or cached_gguf_source_partial(repo_id, hf_variant, snap):+ pending_downloads.append(candidate)+ continue+ yield candidate+ # Keep existing reuse semantics when no completed duplicate is available.+ yield from pending_downloadsexcept Exception as e:logger.debug(f"Cache lookup for variant failed: {e}")diff --git a/studio/backend/hub/routes/inventory.py b/studio/backend/hub/routes/inventory.pyindex fa41d2c6403..a6815519adb 100644--- a/studio/backend/hub/routes/inventory.py+++ b/studio/backend/hub/routes/inventory.py@@ -151,6 +151,7 @@ async def get_gguf_variants(prefer_local_cache: bool = Query(False),offline: bool = Query(False),local_path: Optional[str] = Query(None),+ include_cache_locations: bool = Query(False),hf_token: HfTokenArg = Depends(get_request_hf_token),current_subject: str = Depends(get_current_subject),via_api_key: bool = Depends(authenticated_via_api_key),@@ -166,6 +167,7 @@ async def get_gguf_variants(prefer_local_cache = prefer_local_cache,offline = offline,local_path = resolve_host_path_reference(local_path) or local_path,+ include_cache_locations = include_cache_locations,hf_token = hf_token,),via_api_key = via_api_key,@@ -318,14 +320,24 @@ async def list_hidden_models(async def delete_impact(repo_id: str = Body(...),variant: Optional[str] = Body(None),+ # The copy the listing advertised, so the preview describes the delete that will follow.+ cache_path: Optional[str] = Body(None),current_subject: str = Depends(get_current_subject),+ via_api_key: bool = Depends(authenticated_via_api_key),):"""Preview a delete: bytes reclaimed, shared assets retained, and anything blocking it.POST rather than GET because a repo id is a path-shaped value and this reads no cache of itsown; it is a pure query and mutates nothing."""- return await companion_cleanup.delete_impact_response(repo_id, variant)+ # The preview names the folder it would delete, so it takes the same host-path boundary as+ # the inventory routes; an API-key caller gets the opaque reference instead.+ return redact_host_paths(+ await companion_cleanup.delete_impact_response(+ repo_id, variant, resolve_host_path_reference(cache_path) or cache_path+ ),+ via_api_key = via_api_key,+ )@router.get("/orphan-companions", response_model = OrphanCompanionsResponse)diff --git a/studio/backend/hub/schemas/inventory.py b/studio/backend/hub/schemas/inventory.pyindex 253747c7922..b550534ccfb 100644--- a/studio/backend/hub/schemas/inventory.py+++ b/studio/backend/hub/schemas/inventory.py@@ -19,6 +19,15 @@ class GgufVariantDetail(BaseModel):filename: str = Field(..., description = "GGUF filename (e.g., 'gemma-3-4b-it-Q4_K_M.gguf')")quant: str = Field(..., description = "Quantization label or internal GGUF variant key")+ cache_path: Optional[str] = Field(+ None, description = "Owning cache repository for this complete variant"+ )+ # Declared so the host-path boundary's redacted stand-in survives response-model+ # serialization: without it an API-key caller loses both the path and the reference+ # that would pin a later delete to this copy.+ cache_ref: Optional[str] = Field(+ None, description = "Opaque stand-in for cache_path, stable for the server's life"+ )display_label: Optional[str] = Field(None, description = "Optional user-facing label when quant is an internal key")@@ -363,6 +372,12 @@ class CompanionAssetInfo(BaseModel):class DeleteImpactResponse(BaseModel):"""What a pending delete would actually do, so the confirm dialog can say it."""+ cache_path: Optional[str] = Field(+ None, description = "Cache repository folder targeted by this delete"+ )+ # Opaque stand-in for ``cache_path``, filled in by the host-path boundary for API-key callers.+ cache_ref: Optional[str] = None+repo_id: strvariant: Optional[str] = Nonereclaimed_bytes: int = Field(0, description = "Bytes this delete frees, from the cache scan")diff --git a/studio/backend/hub/services/models/cache_inventory.py b/studio/backend/hub/services/models/cache_inventory.pyindex bb06bf67c50..2c93c5f4b2b 100644--- a/studio/backend/hub/services/models/cache_inventory.py+++ b/studio/backend/hub/services/models/cache_inventory.py@@ -600,6 +600,7 @@ def _scan_cached_gguf(variant_states = Noneseen_lower: dict[str, dict] = {}+ repo_cache_roots: dict[str, set[Path]] = {}for hf_cache in cache_scans:for repo_info in hf_cache.repos:try:@@ -701,7 +702,11 @@ def _scan_cached_gguf(tts_only = row_task == "text-to-speech",))- # Only the winning cache root loads, so the loser's vision flag must not carry over.+ # Preserve a snapshot-pinned load id for a single cache: refs/main can+ # be stale or dangling even when a different snapshot holds the quant.+ # Only a repository spanning distinct cache roots needs repo-wide+ # resolution so chat can choose the requested quant's owning copy.+ repo_cache_roots.setdefault(key, set()).add(repo_path.parent)if _prefer_cache_row(row, existing):seen_lower[key] = rowelif last_modified > existing.get("last_modified", 0.0):@@ -710,6 +715,15 @@ def _scan_cached_gguf(repo_label = getattr(repo_info, "repo_id", "<unknown>")logger.warning("Skipping cached GGUF repo %s: %s", repo_label, scrub_paths(e))continue+ from hub.utils.gguf_sources import CHAT_GGUF_TASKS++ for key, row in seen_lower.items():+ if (+ len(repo_cache_roots.get(key, ())) > 1+ and not row["partial"]+ and row["task"] in CHAT_GGUF_TASKS+ ):+ row["load_id"] = row["repo_id"]return sorted(seen_lower.values(), key = lambda c: c["repo_id"])diff --git a/studio/backend/hub/services/models/companion_cleanup.py b/studio/backend/hub/services/models/companion_cleanup.pyindex f5b59257ac3..ae229803abc 100644--- a/studio/backend/hub/services/models/companion_cleanup.py+++ b/studio/backend/hub/services/models/companion_cleanup.py@@ -139,18 +139,41 @@ def _variant_is_a_required_companion_asset(repo_id: str, variant: str) -> bool:return _impl(repo_id, variant)-def _delete_impact_blocking(repo_id: str, variant: Optional[str]) -> dict:+def _delete_impact_blocking(+ repo_id: str,+ variant: Optional[str],+ cache_path: Optional[str] = None,+) -> dict:scans = _account_scans()by_id = _repos_by_id(scans)key = repo_id.strip().lower()- repos = by_id.get(key, [])+ all_copies = by_id.get(key, [])+ from hub.utils.gguf_sources import cached_gguf_action_path++ cache_path = cached_gguf_action_path(repo_id, variant, cache_path)+ repos = all_copies+ surviving = []+ if cache_path:+ from hub.utils.hf_cache_state import resolve_delete_target_root++ root = resolve_delete_target_root(+ "model",+ repo_id,+ cache_path,+ {Path(repo.repo_path).parent.resolve() for repo in all_copies},+ )+ if root is None:+ raise HTTPException(status_code = 400, detail = "Invalid cache_path")+ repos = [repo for repo in all_copies if Path(repo.repo_path).parent.resolve() == root]+ surviving = [repo for repo in all_copies if repo not in repos]reclaimed = 0for repo_info in repos:reclaimed += _variant_bytes(repo_info, variant) if variant else _repo_blob_bytes(repo_info)- # Would this delete leave the repo with no runnable checkpoint? Only then can its companions become reclaimable; while a sibling quant survives they stay in use.- removes_last_checkpoint = True+ # Would this delete leave the repo with no runnable checkpoint? Only then can its companions become reclaimable;+ # while a sibling quant survives they stay in use.+ removes_last_checkpoint = not any(_repo_holds_denoiser(repo) for repo in surviving)if variant:for repo_info in repos:if _remaining_main_gguf_variants(repo_info, excluding = variant):@@ -186,6 +209,7 @@ def _delete_impact_blocking(repo_id: str, variant: Optional[str]) -> dict:"repo_id": repo_id,"variant": variant,"reclaimed_bytes": reclaimed,+ "cache_path": cache_path,"retained_companions": retained,"freeable_companions": freeable,# Same predicate the destructive path uses: the native Qwen-Image encoder is a named quant inside a chat GGUF repo, so previewing only whole-repo deletes left Delete enabled and the refusal arriving after the user confirmed.@@ -205,14 +229,18 @@ class _SingleRepoScan:self.repos = repos-async def delete_impact_response(repo_id: str, variant: Optional[str] = None) -> dict:+async def delete_impact_response(+ repo_id: str,+ variant: Optional[str] = None,+ cache_path: Optional[str] = None,+) -> dict:"""What a delete of *repo_id* (/*variant*) would reclaim, retain, and be blocked by."""if not _is_valid_repo_id(repo_id):raise HTTPException(status_code = 400, detail = "Invalid repo_id format")variant = (variant or "").strip() or Noneif variant is not None and not _is_valid_gguf_variant(variant):raise HTTPException(status_code = 400, detail = f"Invalid gguf_variant: {variant!r}")- return await asyncio.to_thread(_delete_impact_blocking, repo_id, variant)+ return await asyncio.to_thread(_delete_impact_blocking, repo_id, variant, cache_path)def _orphan_companions_blocking() -> dict:diff --git a/studio/backend/hub/services/models/deletion.py b/studio/backend/hub/services/models/deletion.pyindex c81046c9d3a..6462ff50d1e 100644--- a/studio/backend/hub/services/models/deletion.py+++ b/studio/backend/hub/services/models/deletion.py@@ -937,7 +937,11 @@ def _delete_cached_model_blocking(*,only_if_orphan: bool = False,) -> dict:- # Free up space's list can be minutes old, and a background download finishing turns that orphan into an installed checkpoint neither guard below catches.+ from hub.utils.gguf_sources import cached_gguf_action_path++ cache_path = cached_gguf_action_path(repo_id, variant, cache_path)+ # Free up space's list can be minutes old, and a background download finishing turns that orphan+ # into an installed checkpoint neither guard below catches.if only_if_orphan:from hub.services.models import companion_cleanupfrom hub.utils import companion_assetsdiff --git a/studio/backend/hub/services/models/gguf_variants.py b/studio/backend/hub/services/models/gguf_variants.pyindex 44e8da5a271..c5f5cbffaff 100644--- a/studio/backend/hub/services/models/gguf_variants.py+++ b/studio/backend/hub/services/models/gguf_variants.py@@ -1009,6 +1009,9 @@ class VariantsAnswer(NamedTuple):# False when the caller may not read this repo's caches, for a reader that falls back# to the repo id rather than ``context_source``.cache_authorized: bool = True+ # Per-quant copy the listing answered from, for a reader that resolves each row's metadata+ # from the quant's own cache rather than one shared directory.+ variant_context_sources: Optional[dict[str, str]] = Nonedef _default_variant_candidates(variants) -> list[str]:@@ -1031,6 +1034,7 @@ async def get_gguf_variants_answer(offline: bool = False,local_path: Optional[str] = None,hf_token: Optional[str] = None,+ include_cache_locations: bool = False,) -> VariantsAnswer:"""List available GGUF quantization variants for a HuggingFace repo@@ -1063,8 +1067,11 @@ async def get_gguf_variants_answer(answered_locally = [False]# Read by the route before its own cache walk, which this listing does not cover.cache_authorized = [True]+ variant_context_sources: dict[str, str] = {}+ hub_listing = None- def _compute() -> GgufVariantsResponse:+ def _compute(local_path: Optional[str] = local_path) -> GgufVariantsResponse:+ nonlocal hub_listingrepo_cache_dir = (None if is_local_path(repo_id) else _repo_cache_dir_for_request(repo_id, local_path))@@ -1484,7 +1491,9 @@ async def get_gguf_variants_answer(return Nonetry:- variants, has_vision, siblings = list_gguf_variants(repo_id, hf_token = hf_token)+ if hub_listing is None:+ hub_listing = list_gguf_variants(repo_id, hf_token = hf_token)+ variants, has_vision, siblings = hub_listingexcept Exception:# Ungated: _cache_fallback_response already refuses an unauthorized caller.fallback = _cache_fallback_response()@@ -1893,7 +1902,10 @@ async def get_gguf_variants_answer(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 answered from.- return VariantsAnswer(_compute_response(), answered_from[0], cache_authorized[0])+ response = _compute_response()+ return VariantsAnswer(+ response, answered_from[0], cache_authorized[0], variant_context_sources+ )def _compute_response() -> GgufVariantsResponse:skip = is_local_path(repo_id) or not _is_valid_repo_id(repo_id)@@ -1906,26 +1918,165 @@ async def get_gguf_variants_answer(skip = True# Carried out: the route's context-length fallback walks these same caches.cache_authorized[0] = False+ # Explicit filesystem requests keep their original scope. Logical repository requests+ # include complete quantizations from remembered locations without adding inventory rows.+ # Scoped online verdicts, shared by duplicate ranking and the merge below: whether a+ # copy satisfies the companion set the CURRENT revision asks for is only known from+ # the Hub answer for that copy's own snapshot.+ scoped_responses = {}++ def _scoped_variant_row(snapshot: Path, quant: str):+ cached = scoped_responses.get(snapshot)+ if cached is None:+ original_source = answered_from[0]+ original_local = answered_locally[0]+ try:+ scoped = _compute(str(snapshot))+ finally:+ answered_from[0] = original_source+ # Restored too: this is a nested lookup, not the outer answer, and+ # leaving it set would suppress the merge that reads it.+ answered_locally[0] = original_local+ cached = {item.quant.lower(): item for item in scoped.variants}+ scoped_responses[snapshot] = cached+ return cached.get(quant.lower()) if quant else None++ def _scoped_quant_ready(snapshot: Path, quant: str) -> Optional[bool]:+ """This snapshot's readiness for *quant* per its own Hub answer; None when unknown.++ None for a local-only request: companion readiness is Hub metadata, and a+ ``prefer_local_cache``/``offline`` answer must rank on local state alone.+ """+ if prefer_local_cache or offline:+ return None+ row = _scoped_variant_row(snapshot, quant)+ return None if row is None else bool(row.downloaded)++ sources = {}+ if (+ include_cache_locations+ and not skip+ # No separate anonymous gate: hub_cached_read_refused above already refused the+ # callers that may not read this cache, and it authorizes a public repo's for+ # the sentinel. Re-testing it here dropped an authorized anonymous read.+ and (not local_path or local_path == repo_id)+ ):+ from hub.utils.gguf_sources import (+ cached_gguf_source_partial,+ cached_gguf_sources,+ )+ sources = cached_gguf_sources(repo_id, scoped_ready = _scoped_quant_ready)try:response = _compute()- except Exception:- # Surface an empty leftover <quant>/ folder so the UI can delete it; otherwise re-raise the original error.- if skip:+ except Exception as exc:+ if sources and (prefer_local_cache or offline or hf_error_status(exc) is None):+ response = GgufVariantsResponse(repo_id = repo_id, variants = [])+ else:+ if skip:+ raise+ enriched = _mark_empty_dir_cleanables(+ repo_id,+ GgufVariantsResponse(repo_id = repo_id, variants = []),+ _repo_cache_dir_for_request(repo_id, local_path),+ )+ if enriched.variants:+ return enrichedraise- enriched = _mark_empty_dir_cleanables(- repo_id,- GgufVariantsResponse(repo_id = repo_id, variants = []),- _repo_cache_dir_for_request(repo_id, local_path),- )- if enriched.variants:- return enriched- raise+ if sources and not answered_locally[0]:+ variants = {v.quant.lower(): v for v in response.variants}+ online_answer = not (prefer_local_cache or offline or answered_from[0])+ for key, source in sources.items():+ v = source.variant+ previous = variants.get(key)+ active_repo_dir = _repo_cache_dir_for_request(repo_id, None)+ if previous is not None and source.cache_path == str(active_repo_dir):+ if previous.downloaded:+ previous.cache_path = source.cache_path+ variant_context_sources[key] = str(source.snapshot / v.filename)+ continue+ variant_context_sources[key] = str(source.snapshot / v.filename)+ detail = GgufVariantDetail(+ filename = v.filename,+ quant = v.quant,+ display_label = v.display_label,+ size_bytes = v.size_bytes,+ download_size_bytes = v.size_bytes,+ # A source the snapshot itself lists as incomplete is a row to resume,+ # not a copy to load, even before the per-source readiness checks run.+ downloaded = not source.incomplete,+ partial = source.incomplete,+ cache_path = source.cache_path,+ dependency_key = _variant_dependency_key(repo_id, v.filename),+ )+ if source.incomplete:+ variant_context_sources.pop(key, None)+ if online_answer:+ # Apply the same readiness and update checks as a request for this snapshot.+ checked = _scoped_variant_row(source.snapshot, key)+ if checked is not None:+ detail = checked.model_copy(update = {"cache_path": source.cache_path})+ if detail.downloaded:+ detail.filename = v.filename+ detail.size_bytes = v.size_bytes+ else:+ variant_context_sources.pop(key, None)+ elif cached_gguf_source_partial(repo_id, v.quant, source.snapshot):+ # The current revision no longer describes this quant, so its scoped+ # answer cannot judge it; the copy's own manifest and marker still can.+ variant_context_sources.pop(key, None)+ detail.downloaded = False+ detail.partial = True+ elif cached_gguf_source_partial(repo_id, v.quant, source.snapshot):+ # A local-only or offline answer never reaches the Hub path above, so+ # that readiness check cannot run; this is its local twin. A remembered+ # copy whose own manifest, marker or blobs make the quant incomplete is+ # not a complete copy the picker may offer to load, or the row would+ # advertise a load that fails where the matching direct request offers+ # a resume.+ variant_context_sources.pop(key, None)+ detail.downloaded = False+ detail.partial = True+ if detail.partial:+ # Resume metadata has to describe the copy a resume will actually touch: a+ # download always lands in the ACTIVE cache, so a remembered partial keeps+ # ITS OWN marker, manifest and verdict only while that copy is the active+ # one. Otherwise the row would promise a byte-for-byte restart inside a+ # folder the transfer never writes to. The row still names the copy on disk+ # -- that is what delete and load resolve -- while the resume affordance+ # speaks for the root the continuation will really run in.+ resume_cache_dir = (+ Path(source.cache_path)+ if source.cache_path == str(active_repo_dir)+ else active_repo_dir+ )+ detail = detail.model_copy(+ update = {+ "download_remaining_bytes": variant_remaining_bytes_from_state(+ repo_id, v.quant, resume_cache_dir+ ),+ "partial_transport": _partial_transport_for_variant(+ repo_id, v.quant, resume_cache_dir+ ),+ "partial_resumable": _partial_resumable_for_variant(+ repo_id, v.quant, resume_cache_dir+ ),+ }+ )+ variants[key] = detail+ response.variants = list(variants.values())+ response.has_vision = response.has_vision or any(s.has_vision for s in sources.values())+ # Merging changes which rows are root-level, and _default_variant_candidates picks+ # among root rows, so a default chosen from the active cache alone can name the+ # wrong checkpoint once a remembered folder contributes a root row. A partial row+ # is not a load the picker may recommend while a ready row exists, so prefer ready.+ if sources or not response.default_variant:+ ready = [v for v in response.variants if v.downloaded and not v.partial]+ best = pick_best_gguf(_default_variant_candidates(ready or response.variants))+ response.default_variant = gguf_variant_key(best) if best else Noneif skip or answered_locally[0]:return responsereturn _mark_empty_dir_cleanables(- repo_id,- response,- _repo_cache_dir_for_request(repo_id, local_path),+ repo_id, response, _repo_cache_dir_for_request(repo_id, local_path))from utils.hf_cache_settings import configured_cache_key@@ -1934,6 +2085,7 @@ async def get_gguf_variants_answer(repo_id,bool(prefer_local_cache),bool(offline),+ bool(include_cache_locations),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.@@ -1962,6 +2114,7 @@ async def get_gguf_variants_response(offline: bool = False,local_path: Optional[str] = None,hf_token: Optional[str] = None,+ include_cache_locations: bool = False,) -> GgufVariantsResponse:"""The listing alone, for callers that do not read metadata off the same copy."""answer = await get_gguf_variants_answer(@@ -1970,5 +2123,6 @@ async def get_gguf_variants_response(offline = offline,local_path = local_path,hf_token = hf_token,+ include_cache_locations = include_cache_locations,)return answer.responsediff --git a/studio/backend/hub/utils/gguf_sources.py b/studio/backend/hub/utils/gguf_sources.pynew file mode 100644index 00000000000..e30e0350dba--- /dev/null+++ b/studio/backend/hub/utils/gguf_sources.py@@ -0,0 +1,176 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Resolve logical GGUF variants across remembered download folders."""++from __future__ import annotations++from dataclasses import dataclass+from pathlib import Path+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from hub.utils.gguf import GgufVariantInfo++CHAT_GGUF_TASKS = (None, "text-generation", "image-text-to-text")+++def gguf_cache_snapshots(repo_id: str):+ """Active cache first, then remembered caches; newest snapshots first in each."""+ from hub.services.models.catalog_classification import _gguf_path_task+ from hub.utils.gguf import iter_hf_cache_snapshots+ from hub.utils.hf_cache_state import hf_cache_roots+ from utils.hf_cache_settings import get_hf_cache_paths++ active = get_hf_cache_paths().hub_cache+ roots = [active, *hf_cache_roots()]+ seen = set()+ for index, root in enumerate(roots):+ key = str(Path(root).resolve())+ if key in seen:+ continue+ seen.add(key)+ for snapshot in iter_hf_cache_snapshots(repo_id, root = root):+ if index and _gguf_path_task(snapshot, (repo_id,)) not in CHAT_GGUF_TASKS:+ continue+ yield snapshot+++def cached_gguf_source_partial(repo_id: str, quant: str, snapshot: Path) -> bool:+ """Whether this snapshot's quant is incomplete by its own manifest, cancellation marker or blobs.++ The per-snapshot twin of the readiness check a listing runs for the cache it names. A+ caller merging remembered folders has to ask it about every source it reports: with+ ``prefer_local_cache``/``offline`` there is no Hub answer to fall back on, so an+ interrupted companion download would otherwise be advertised as a complete copy that+ the picker offers to load instead of to resume.++ Local-only by construction -- it reads the manifest and marker next to *snapshot* and+ never consults the Hub -- and judged against that same snapshot's own repo cache+ directory, since a cancellation marker belongs to the attempt that wrote it.+ """+ from hub.utils import inventory_scan++ repo_cache_dir = snapshot.parent.parent+ return inventory_scan.is_variant_partial(+ repo_id,+ quant,+ snapshot,+ repo_cache_dir = repo_cache_dir,+ repo_signal_applies = inventory_scan.repo_signal_applies_to_snapshot(+ repo_cache_dir, snapshot+ ),+ )+++def _prefer_duplicate(+ repo_id: str,+ quant: str,+ previous: Path,+ candidate: Path,+ scoped_ready = None,+) -> bool:+ """Whether *candidate* should replace *previous* as this quant's source.++ Manifest verification alone misses a copy that its own snapshot state marks partial -- a+ cancel marker or an unfinished companion -- which the merge then reports as unusable even+ though a complete duplicate of the same quant exists. Rank on the full per-snapshot verdict+ so the healthy copy wins, and keep the completed-vs-incomplete manifest rule it refines.++ *scoped_ready* adds the one verdict no local rule can see: whether a copy satisfies the+ companion set the CURRENT revision asks for, which only that copy's Hub answer knows.+ """+ if scoped_ready is not None:+ previous_ready = scoped_ready(previous, quant)+ candidate_ready = scoped_ready(candidate, quant)+ if previous_ready is not None and candidate_ready is not None:+ if previous_ready != candidate_ready:+ return candidate_ready+ if not cached_gguf_manifest_complete(+ repo_id, quant, previous+ ) and cached_gguf_manifest_complete(repo_id, quant, candidate):+ return True+ return cached_gguf_source_partial(repo_id, quant, previous) and not cached_gguf_source_partial(+ repo_id, quant, candidate+ )+++def cached_gguf_manifest_complete(repo_id: str, quant: str, snapshot: Path) -> bool:+ """Prefer completed downloads without applying a newer revision's manifest to an older copy."""+ from hub.services.models.catalog_classification import _gguf_path_task+ from hub.utils.download_manifest import read_manifest, verify_against_disk++ if _gguf_path_task(snapshot, (repo_id,)) not in CHAT_GGUF_TASKS:+ return True+ manifest = read_manifest("model", repo_id, quant, hub_cache = snapshot.parent.parent.parent)+ if manifest is None or manifest.commit_hash not in (None, snapshot.name):+ return True+ return verify_against_disk(manifest, snapshot).ok+++@dataclass(frozen = True)+class CachedGgufSource:+ variant: "GgufVariantInfo"+ snapshot: Path+ has_vision: bool+ # Listed by the snapshot but incomplete by its own manifest, marker or shards. The+ # fallback pass keeps such a source so a resume can name its folder; the merge then+ # reports it partial instead of as a loadable copy.+ incomplete: bool = False++ @property+ def cache_path(self) -> str:+ return str(self.snapshot.parent.parent)+++def cached_gguf_sources(repo_id: str, *, scoped_ready = None) -> dict[str, CachedGgufSource]:+ """One complete source per quant. Never assemble split weights across snapshots."""+ from hub.services.models.catalog_classification import _gguf_path_task+ from hub.utils.gguf import list_local_gguf_variants+ from hub.utils.inventory_scan import complete_snapshot_variants++ sources = {}+ partials: dict[str, CachedGgufSource] = {}+ for snapshot in gguf_cache_snapshots(repo_id):+ # Media GGUFs have a separate download/load pipeline and retain their existing scope.+ if _gguf_path_task(snapshot, (repo_id,)) not in CHAT_GGUF_TASKS:+ continue+ variants, has_vision = list_local_gguf_variants(str(snapshot))+ complete = complete_snapshot_variants(str(snapshot)) or set()+ for variant in variants:+ if not variant.quant:+ continue+ key = variant.quant.lower()+ if variant.quant in complete:+ previous = sources.get(key)+ if previous is None or _prefer_duplicate(+ repo_id,+ variant.quant,+ previous.snapshot,+ snapshot,+ scoped_ready,+ ):+ sources[key] = CachedGgufSource(variant, snapshot, has_vision)+ partials.pop(key, None)+ continue+ # An interrupted split quant is listed but not complete. Keep it as a fallback+ # instead of dropping it, so the merge can still show the row, mark it partial+ # and point a resume at the folder that holds it.+ partials.setdefault(+ key, CachedGgufSource(variant, snapshot, has_vision, incomplete = True)+ )+ for key, source in partials.items():+ sources.setdefault(key, source)+ return sources+++def cached_gguf_action_path(+ repo_id: str,+ variant: str | None,+ cache_path: str | None = None,+) -> str | None:+ """An explicit folder wins; logical quant actions use the same source as the listing."""+ if cache_path or not variant:+ return cache_path+ source = cached_gguf_sources(repo_id).get(variant.lower())+ return source.cache_path if source else Nonediff --git a/studio/backend/models/models.py b/studio/backend/models/models.pyindex 39e26252997..8fe54b8952e 100644--- a/studio/backend/models/models.py+++ b/studio/backend/models/models.py@@ -153,9 +153,20 @@ class GgufVariantDetail(BaseModel):filename: str = Field(..., description = "GGUF filename (e.g., 'gemma-3-4b-it-Q4_K_M.gguf')")quant: str = Field(..., description = "Quantization label or internal GGUF variant key")- # Mirrors hub.schemas.inventory.GgufVariantDetail. The route builds THIS model, so a field that exists only- # on the hub twin is dropped by pydantic without a word and a qualified row falls back to rendering its whole- # relative path.+ cache_path: Optional[str] = Field(+ None, description = "Owning cache repository for this complete variant"+ )+ # Mirrors hub.schemas.inventory.GgufVariantDetail; see display_label below. FastAPI+ # serializes through THIS model, so an undeclared redacted reference is dropped.+ cache_ref: Optional[str] = Field(+ None, description = "Opaque stand-in for cache_path, stable for the server's life"+ )+ context_length: Optional[int] = Field(+ None, description = "Native context limit from this variant's cached source"+ )+ # Mirrors hub.schemas.inventory.GgufVariantDetail. The route builds THIS model, so a field that+ # exists only on the hub twin is dropped by pydantic without a word and a qualified row falls back+ # to rendering its whole relative path.display_label: Optional[str] = Field(None, description = "Optional user-facing label when quant is an internal key")diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.pyindex b1c35c4ed43..f0d8c1ba410 100644--- a/studio/backend/routes/models.py+++ b/studio/backend/routes/models.py@@ -3647,11 +3647,16 @@ async def _read_native_context_length_bounded(model: str, is_local: bool) -> Optdef _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 one non-mmproj shard's header is enough. 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."""+ """Native max context from a downloaded GGUF for this repo, or None.++ A file path reads that exact quant; a directory reads one non-mmproj shard.+ 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_lengthfrom utils.paths.path_utils import file_contents_available_locally@@ -3670,7 +3675,8 @@ def _read_native_context_length(repo_id: str, is_local: bool) -> Optional[int]: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):+ paths = [root] if is_local and root.is_file() else _iter_gguf_paths(root, deadline)+ for f in paths:if time.monotonic() >= deadline:logger.debug("native context read for '%s' out of budget", repo_id)return None@@ -3707,6 +3713,11 @@ def _resolve_quant_gguf(repo_id: str, quant: str, is_local: bool) -> tuple[Optioif not _is_valid_repo_id(repo_id):return None, 0+ from hub.utils.gguf_sources import cached_gguf_sources++ source = cached_gguf_sources(repo_id).get((quant or "").strip().lower())+ if source is not None:+ return _resolve_quant_gguf(str(source.snapshot), quant, True)roots = []for entry in iter_repo_cache_dirs("model", repo_id):snaps = entry / "snapshots"@@ -4489,6 +4500,7 @@ async def get_gguf_variants(offline: bool = False,local_path: Optional[str] = None,hf_token: Optional[str] = Query(None, description = "HuggingFace token for private repos"),+ include_cache_locations: bool = False,hf_token_header: HfTokenArg = Depends(get_request_hf_token),current_subject: str = Depends(get_current_subject),via_api_key: bool = Depends(authenticated_via_api_key),@@ -4509,6 +4521,7 @@ async def get_gguf_variants(prefer_local_cache = prefer_local_cache,offline = offline,local_path = local_path,+ include_cache_locations = include_cache_locations,hf_token = hf_token,)response = answer.response@@ -4523,7 +4536,21 @@ async def get_gguf_variants(# not suppress from inside.if not answer.cache_authorized and not is_local_path(context_model):context_model = None- local = context_model is not None and is_local_path(context_model)+ variant_sources = getattr(answer, "variant_context_sources", None) or {}++ # One read per copy the listing answered from, so each quant is priced off its own+ # source. A None context_model (unauthorized caller) contributes no read at all.+ read_models = [+ model for model in dict.fromkeys([context_model, *variant_sources.values()]) if model+ ]+ # Share the existing hard deadline and concurrency guard across all source reads.+ context_values = await asyncio.gather(+ *(+ _read_native_context_length_bounded(model, is_local_path(model))+ for model in read_models+ )+ )+ context_lengths = dict(zip(read_models, context_values))# See the /hub twin: the identifier is resolved on the way in, so it has to be# referenced again on the way out.@@ -4534,6 +4561,10 @@ async def get_gguf_variants(GgufVariantDetail(filename = v.filename,quant = v.quant,+ cache_path = getattr(v, "cache_path", None),+ context_length = context_lengths.get(+ variant_sources.get(v.quant.lower(), context_model)+ ),# A path-qualified key is not a label a picker can show; without this# the row reads as its whole relative path.display_label = getattr(v, "display_label", None),@@ -4554,11 +4585,7 @@ async def get_gguf_variants(],has_vision = response.has_vision,default_variant = response.default_variant,- context_length = (- await _read_native_context_length_bounded(context_model, local)- if context_model is not None- else None- ),+ context_length = context_lengths.get(context_model),resolved_locally = bool(getattr(response, "resolved_locally", False)),dependencies_resolved = bool(getattr(response, "dependencies_resolved", False)),loadable_variants = getattr(response, "loadable_variants", None),@@ -5378,6 +5405,13 @@ def _resolve_cached_model_path(repo_id: str, variant: Optional[str]) -> Path:raise HTTPException(status_code = 404, detail = "Model not found in cache")if variant:+ from hub.utils.gguf_sources import cached_gguf_sources++ source = cached_gguf_sources(repo_id).get(variant.strip().lower())+ if source is not None:+ path = source.snapshot / source.variant.filename+ if path.is_file():+ return pathwant = (variant or "").strip()candidate_revisions = sorted((rev for repo_info in matching_repos for rev in repo_info.revisions),diff --git a/studio/backend/tests/gguf_cache_location_fixtures.py b/studio/backend/tests/gguf_cache_location_fixtures.pynew file mode 100644index 00000000000..579229ac08f--- /dev/null+++ b/studio/backend/tests/gguf_cache_location_fixtures.py@@ -0,0 +1,71 @@+# 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 asyncio+import os+from types import SimpleNamespace++import pytest++from hub.services.models import cache_inventory, deletion, gguf_variants+from hub.utils import inventory_scan+from utils import hf_cache_settings++[email protected](params = [False, True])+def cache_locations(monkeypatch, tmp_path, request):+ active_custom = request.param+ store = {}+ monkeypatch.setattr(hf_cache_settings, "_EXPLICIT_CACHE_ENV", {})+ monkeypatch.setenv("XDG_CACHE_HOME", str(tmp_path / "xdg"))+ monkeypatch.setattr(+ "storage.studio_db.get_app_setting",+ lambda key, fallback = None: store.get(key, fallback),+ )+ monkeypatch.setattr("storage.studio_db.upsert_app_settings", store.update)+ monkeypatch.setattr("hub.utils.paths.legacy_hf_cache_dir", lambda: tmp_path / "legacy")+ monkeypatch.setattr("hub.utils.paths.hf_default_cache_dir", lambda: tmp_path / "unused")+ default_root = hf_cache_settings.get_hf_cache_paths().hub_cache+ custom_home = tmp_path / "custom"+ repo_id = "Org/Model-GGUF"+ expected = {}++ def write_quant(root, quant):+ repo = root / "models--Org--Model-GGUF"+ snapshot = repo / "snapshots" / ("d" * 40)+ snapshot.mkdir(parents = True)+ filename = f"Model-{quant}.gguf"+ (snapshot / filename).write_bytes(b"\0" * 256)+ (repo / "refs").mkdir()+ (repo / "refs" / "main").write_text("d" * 40)+ expected[quant] = (repo, snapshot / filename)++ write_quant(default_root, "Q6_K")+ hf_cache_settings.set_hf_cache_home(str(custom_home))+ write_quant(custom_home / "hub", "Q8_0")+ hf_cache_settings.set_hf_cache_home(None)+ if active_custom:+ hf_cache_settings.set_hf_cache_home(str(custom_home))++ assert custom_home / "hub" in hf_cache_settings.known_hf_hub_caches()+ return repo_id, expected+++def cache_client():+ from auth.authentication import allow_ambient_hf_token, authenticated_via_api_key+ from fastapi import FastAPI+ from fastapi.testclient import TestClient+ from hub.routes import inventory+ from routes import models++ app = FastAPI()+ app.include_router(inventory.router, prefix = "/api/hub")+ app.include_router(models.router, prefix = "/api/models")+ app.dependency_overrides[inventory.get_current_subject] = lambda: "test"+ app.dependency_overrides[inventory.get_request_hf_token] = lambda: None+ # A browser session, not an sk-unsloth call: the route reads this before its cache walk.+ app.dependency_overrides[authenticated_via_api_key] = lambda: False+ app.dependency_overrides[allow_ambient_hf_token] = lambda: True+ with TestClient(app) as client:+ yield clientdiff --git a/studio/backend/tests/test_cache_inventory_path_boundary.py b/studio/backend/tests/test_cache_inventory_path_boundary.pyindex 0c245432337..3081ceaae5a 100644--- a/studio/backend/tests/test_cache_inventory_path_boundary.py+++ b/studio/backend/tests/test_cache_inventory_path_boundary.py@@ -940,6 +940,7 @@ def test_a_cache_reference_lists_the_quants_of_the_copy_it_names(monkeypatch, clprefer_local_cache = False,offline = False,local_path = None,+ include_cache_locations = False,hf_token = None,):seen.update(repo_id = repo_id, local_path = local_path)diff --git a/studio/backend/tests/test_cached_gguf_routes.py b/studio/backend/tests/test_cached_gguf_routes.pyindex f4b9c211f0c..76d3c426adf 100644--- a/studio/backend/tests/test_cached_gguf_routes.py+++ b/studio/backend/tests/test_cached_gguf_routes.py@@ -2165,6 +2165,7 @@ def test_gguf_variants_route_scopes_local_probe_to_selected_cache(monkeypatch, t"prefer_local_cache": True,"offline": False,"local_path": str(snapshot),+ "include_cache_locations": False,"hf_token": None,},)@@ -2234,7 +2235,13 @@ def test_gguf_variants_route_forwards_offline(monkeypatch):_variants(offline = True)assert calls == [- {"prefer_local_cache": False, "offline": True, "local_path": None, "hf_token": None}+ {+ "prefer_local_cache": False,+ "offline": True,+ "local_path": None,+ "include_cache_locations": False,+ "hf_token": None,+ }]diff --git a/studio/backend/tests/test_gguf_cache_location_switch.py b/studio/backend/tests/test_gguf_cache_location_switch.pynew file mode 100644index 00000000000..d18e101f9d9--- /dev/null+++ b/studio/backend/tests/test_gguf_cache_location_switch.py@@ -0,0 +1,192 @@+# 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 asyncio++import pytest++from hub.services.models import cache_inventory, deletion, gguf_variants+from hub.utils import inventory_scan+from .gguf_cache_location_fixtures import cache_client, cache_locations+from utils import hf_cache_settings++[email protected]("endpoint", ["/api/models/gguf-variants", "/api/hub/gguf-variants"])+def test_folder_switch_preserves_logical_row_and_both_quants(+ cache_locations, cache_client, endpoint+):+ from core.inference.llama_cpp import cached_gguf_for_load++ repo_id, expected = cache_locations+ rows = [r for r in cache_inventory._scan_cached_gguf() if r["repo_id"] == repo_id]+ assert len(rows) == 1+ assert rows[0]["load_id"] == repo_id+ response = cache_client.get(+ endpoint,+ params = {+ "repo_id": repo_id,+ "prefer_local_cache": True,+ "offline": True,+ "include_cache_locations": True,+ "local_path": rows[0]["load_id"],+ },+ )+ assert response.status_code == 200, response.text+ variants = {v["quant"]: v for v in response.json()["variants"] if v["downloaded"]}+ assert set(variants) == set(expected)+ for quant, (repo, path) in expected.items():+ assert variants[quant]["cache_path"] == str(repo)+ assert cached_gguf_for_load(repo_id, quant) == str(path)+++def test_logical_quant_actions_choose_the_same_cache(cache_locations, cache_client):+ repo_id, expected = cache_locations+ inactive_quant = next(+ q+ for q, (repo, _) in expected.items()+ if repo.parent != hf_cache_settings.get_hf_cache_paths().hub_cache+ )+ repo, path = expected[inactive_quant]+ payload = {"repo_id": repo_id, "variant": inactive_quant}+ copied = cache_client.get("/api/models/cached-model-path", params = payload)+ assert copied.status_code == 200, copied.text+ assert copied.json()["path"] == str(path)+ preview = cache_client.post("/api/hub/delete-impact", json = payload)+ assert preview.status_code == 200, preview.text+ assert preview.json()["reclaimed_bytes"] == 256+ assert preview.json()["cache_path"] == str(repo)+ deletion._delete_cached_model_blocking(repo_id, inactive_quant, None)+ assert not path.exists()+ assert all(p.exists() for q, (_, p) in expected.items() if q != inactive_quant)+++def test_complete_inactive_copy_beats_torn_active_copy(cache_locations, cache_client):+ from core.inference.llama_cpp import cached_gguf_for_load++ repo_id, expected = cache_locations+ inactive_quant = next(+ q+ for q, (repo, _) in expected.items()+ if repo.parent != hf_cache_settings.get_hf_cache_paths().hub_cache+ )+ active_repo = next(+ repo+ for repo, _ in expected.values()+ if repo.parent == hf_cache_settings.get_hf_cache_paths().hub_cache+ )+ active_snap = active_repo / "snapshots" / ("d" * 40)+ (active_snap / f"Model-{inactive_quant}-00001-of-00002.gguf").write_bytes(b"0" * 256)+ inventory_scan.invalidate_hf_cache_scans()+ response = asyncio.run(+ gguf_variants.get_gguf_variants_response(+ repo_id, prefer_local_cache = True, include_cache_locations = True+ )+ )+ found = next(v for v in response.variants if v.quant == inactive_quant)+ assert found.downloaded and not found.partial+ assert cached_gguf_for_load(repo_id, inactive_quant) == str(expected[inactive_quant][1])+++def test_loader_skips_a_cancelled_copy_for_a_healthy_duplicate(cache_locations):+ """The listing prefers the healthy duplicate, so the loader must not open the cancelled copy."""+ from core.inference.llama_cpp import cached_gguf_for_load+ from hub.utils import download_manifest++ repo_id, expected = cache_locations+ active = hf_cache_settings.get_hf_cache_paths().hub_cache+ quant = "Q4_K_M"+ cancelled = healthy = None+ cancelled_repo = None+ for repo, path in expected.values():+ (path.parent / f"Model-{quant}.gguf").write_bytes(b"0" * 256)+ if repo.parent == active:+ cancelled, cancelled_repo = path.parent, repo+ else:+ healthy = path.parent+ assert cancelled is not None and healthy is not None+ assert download_manifest.write_cancel_marker(+ "model", repo_id, quant, hub_cache = cancelled_repo.parent+ )+ inventory_scan.invalidate_hf_cache_scans()+ assert cached_gguf_for_load(repo_id, quant) == str(healthy / f"Model-{quant}.gguf")+++def test_duplicate_quant_prefers_active_cache_and_deletes_only_that_copy(+ cache_locations, cache_client+):+ from core.inference.llama_cpp import cached_gguf_for_load++ repo_id, expected = cache_locations+ for repo, path in expected.values():+ (path.parent / "Model-Q4_K_M.gguf").write_bytes(b"0" * 256)+ inventory_scan.invalidate_hf_cache_scans()+ active_repo = next(+ repo+ for repo, _ in expected.values()+ if repo.parent == hf_cache_settings.get_hf_cache_paths().hub_cache+ )+ active_path = active_repo / "snapshots" / ("d" * 40) / "Model-Q4_K_M.gguf"+ assert cached_gguf_for_load(repo_id, "Q4_K_M") == str(active_path)+ deletion._delete_cached_model_blocking(repo_id, "Q4_K_M", None)+ assert not active_path.exists()+ surviving = [+ path.parent / "Model-Q4_K_M.gguf" for repo, path in expected.values() if repo != active_repo+ ]+ assert all(path.exists() for path in surviving)+ assert cached_gguf_for_load(repo_id, "Q4_K_M") == str(surviving[0])+++def test_explicit_snapshot_remains_scoped(cache_locations):+ repo_id, expected = cache_locations+ for quant, (repo, path) in expected.items():+ response = asyncio.run(+ gguf_variants.get_gguf_variants_response(+ repo_id,+ prefer_local_cache = True,+ local_path = str(path.parent),+ include_cache_locations = True,+ )+ )+ assert {v.quant for v in response.variants if v.downloaded} == {quant}+++def test_download_worker_reuses_inactive_quant_without_network(cache_locations, monkeypatch):+ from core.inference.llama_cpp import LlamaCppBackend++ repo_id, expected = cache_locations+ quant = next(+ q+ for q, (repo, _) in expected.items()+ if repo.parent != hf_cache_settings.get_hf_cache_paths().hub_cache+ )++ def offline(*args, **kwargs):+ raise ConnectionError("offline test")++ def no_download(*args, **kwargs):+ pytest.fail("The downloaded variant must be reused without moving or fetching weights")++ monkeypatch.setattr("huggingface_hub.list_repo_files", offline)+ monkeypatch.setattr("huggingface_hub.get_paths_info", offline)+ monkeypatch.setattr("core.inference.llama_cpp.hf_hub_download_with_xet_fallback", no_download)+ resolved = LlamaCppBackend()._download_gguf(hf_repo = repo_id, hf_variant = quant)+ assert resolved == str(expected[quant][1])+++def test_listing_requires_opt_in(cache_locations, cache_client):+ repo_id, expected = cache_locations+ response = cache_client.get(+ "/api/hub/gguf-variants",+ params = {+ "repo_id": repo_id,+ "prefer_local_cache": True,+ "offline": True,+ },+ )+ assert response.status_code == 200, response.text+ active = {+ quant+ for quant, (repo, _) in expected.items()+ if repo.parent == hf_cache_settings.get_hf_cache_paths().hub_cache+ }+ assert {v["quant"] for v in response.json()["variants"] if v["downloaded"]} == activediff --git a/studio/backend/tests/test_gguf_cache_switch_partial.py b/studio/backend/tests/test_gguf_cache_switch_partial.pynew file mode 100644index 00000000000..df05a8aee33--- /dev/null+++ b/studio/backend/tests/test_gguf_cache_switch_partial.py@@ -0,0 +1,275 @@+# 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 asyncio++import pytest++from hub.services.models import deletion, gguf_variants+from hub.utils import inventory_scan+from .gguf_cache_location_fixtures import cache_client, cache_locations+from utils import hf_cache_settings+++def test_an_interrupted_split_quant_is_still_offered_from_its_folder(cache_locations):+ """list_local_gguf_variants sees the quant while complete_snapshot_variants excludes it, so+ the merge must keep it as a partial source with its folder rather than drop the row."""+ from hub.utils.gguf_sources import cached_gguf_source_partial, cached_gguf_sources++ repo_id, expected = cache_locations+ active = hf_cache_settings.get_hf_cache_paths().hub_cache+ remembered = next(repo for repo, _ in expected.values() if repo.parent != active)+ quant = "Q4_K_M"+ snap = remembered / "snapshots" / ("d" * 40)+ (snap / f"Model-{quant}-00001-of-00002.gguf").write_bytes(b"0" * 256)+ inventory_scan.invalidate_hf_cache_scans()++ # Listed by the scan but excluded as incomplete, so it is the fallback that carries it.+ source = cached_gguf_sources(repo_id)[quant.lower()]+ assert source.snapshot == snap++ response = asyncio.run(+ gguf_variants.get_gguf_variants_response(+ repo_id,+ prefer_local_cache = True,+ offline = True,+ include_cache_locations = True,+ )+ )+ variant = next(v for v in response.variants if v.quant == quant)+ assert not variant.downloaded+ assert variant.partial+ assert variant.cache_path == str(remembered)+++def test_merging_a_root_row_recomputes_the_default(cache_locations, monkeypatch):+ """The default is chosen among ROOT rows, so a default picked from the active cache alone+ must be recomputed once a remembered folder contributes a root checkpoint."""+ from hub.utils.gguf import GgufVariantInfo++ repo_id, expected = cache_locations+ active = hf_cache_settings.get_hf_cache_paths().hub_cache+ remembered = next(repo for repo, _ in expected.values() if repo.parent != active)+ quant = "Q6_K"+ (remembered / "snapshots" / ("d" * 40) / f"Model-{quant}.gguf").write_bytes(b"0" * 256)+ distilled = GgufVariantInfo(+ filename = "distilled/Model-Q6_K.gguf", quant = "distilled/Model-Q6_K", size_bytes = 256+ )+ monkeypatch.setattr(+ gguf_variants, "list_gguf_variants", lambda *a, **k: ([distilled], False, [])+ )+ inventory_scan.invalidate_hf_cache_scans()+ response = asyncio.run(+ gguf_variants.get_gguf_variants_response(+ repo_id, prefer_local_cache = True, offline = True, include_cache_locations = True+ )+ )+ assert response.default_variant == quant, response.default_variant+++def test_duplicate_ranking_honors_current_companion_readiness(cache_locations):+ """No local rule can see a companion the CURRENT revision newly requires, so a duplicate+ the snapshot itself judges partial must not outrank a usable copy of the same quant."""+ from hub.utils.gguf_sources import cached_gguf_sources++ repo_id, expected = cache_locations+ active = hf_cache_settings.get_hf_cache_paths().hub_cache+ quant = "Q4_K_M"+ for repo, path in expected.values():+ (path.parent / f"Model-{quant}.gguf").write_bytes(b"0" * 256)+ inventory_scan.invalidate_hf_cache_scans()+ active_snap = next(path.parent for repo, path in expected.values() if repo.parent == active)+ remembered_snap = next(path.parent for repo, path in expected.values() if repo.parent != active)+ # The active copy satisfies every local rule but its scoped Hub answer does not.+ readiness = {active_snap: False, remembered_snap: True}+ chosen = cached_gguf_sources(+ repo_id, scoped_ready = lambda snapshot, _quant: readiness.get(snapshot)+ )[quant.lower()].snapshot+ assert chosen == remembered_snap++ # The reverse verdict keeps the active copy: ranking is the comparison, not a bias.+ readiness = {active_snap: True, remembered_snap: False}+ kept = cached_gguf_sources(+ repo_id, scoped_ready = lambda snapshot, _quant: readiness.get(snapshot)+ )[quant.lower()].snapshot+ assert kept == active_snap+++def test_the_merged_default_prefers_a_ready_row(cache_locations):+ """An offline merge that offers a complete Q8_0 must not recommend a torn remembered+ quant just because that quant ranks higher."""+ repo_id, expected = cache_locations+ active = hf_cache_settings.get_hf_cache_paths().hub_cache+ active_repo = next(repo for repo, _ in expected.values() if repo.parent == active)+ (active_repo / "snapshots" / ("d" * 40) / "Model-Q8_0.gguf").write_bytes(b"0" * 256)+ remembered = next(repo for repo, _ in expected.values() if repo.parent != active)+ snapped = remembered / "snapshots" / ("d" * 40)+ (snapped / "Model-Q4_K_M-00001-of-00002.gguf").write_bytes(b"0" * 256)+ inventory_scan.invalidate_hf_cache_scans()++ response = asyncio.run(+ gguf_variants.get_gguf_variants_response(+ repo_id, prefer_local_cache = True, offline = True, include_cache_locations = True+ )+ )+ ready = {v.quant for v in response.variants if v.downloaded and not v.partial}+ assert "Q8_0" in ready+ assert response.default_variant in ready+++def test_a_remembered_partial_keeps_its_resume_metadata(cache_locations, monkeypatch):+ """A remembered partial's resume affordance has to describe the root a resume will really+ continue in. A download lands in the ACTIVE cache, so judging the row against the folder it+ happens to sit in would promise a byte-for-byte restart the continuation cannot honour."""+ from hub.utils import download_manifest++ repo_id, expected = cache_locations+ active = hf_cache_settings.get_hf_cache_paths().hub_cache+ quant, (repo, _path) = next(+ (q, value) for q, value in expected.items() if value[0].parent != active+ )+ snap = repo / "snapshots" / ("d" * 40)+ (snap / f"Model-{quant}-00001-of-00002.gguf").write_bytes(b"0" * 256)+ assert download_manifest.write_cancel_marker(+ "model", repo_id, quant, "http", hub_cache = repo.parent+ )+ inventory_scan.invalidate_hf_cache_scans()+ roots = []++ def _resumable(+ _repo_id,+ _quant,+ repo_cache_dir = None,+ ):+ roots.append(repo_cache_dir)+ # Only the remembered folder holds a resumable partial; the active root has none.+ return repo_cache_dir is not None and repo_cache_dir.parent == repo.parent++ monkeypatch.setattr(gguf_variants, "_partial_resumable_for_variant", _resumable)+ monkeypatch.setattr(gguf_variants, "variant_remaining_bytes_from_state", lambda *a, **k: 4096)++ response = asyncio.run(+ gguf_variants.get_gguf_variants_response(+ repo_id, prefer_local_cache = True, offline = True, include_cache_locations = True+ )+ )+ variant = next(v for v in response.variants if v.quant == quant)+ assert variant.partial and not variant.downloaded+ # The row still names the copy it was listed from, which is what delete and load resolve.+ assert variant.cache_path == str(repo)+ # The active root holds no marker or manifest for this quant, so there is no transport to+ # name and nothing a resume could reuse: the neutral label, not a promise of "http".+ assert variant.partial_transport is None+ # Judged against the ACTIVE root's repo dir: this partial's own folder is where the resume+ # will NOT go.+ assert roots and all(root.parent == active for root in roots), roots+ assert variant.partial_resumable is False+ assert variant.download_remaining_bytes == 4096++ # The other way round: a partial in the ACTIVE cache is judged by the copy a resume continues.+ quant, (repo, _path) = next(+ (q, value) for q, value in expected.items() if value[0].parent == active+ )+ snap = repo / "snapshots" / ("d" * 40)+ (snap / f"Model-{quant}-00001-of-00002.gguf").write_bytes(b"0" * 256)+ assert download_manifest.write_cancel_marker(+ "model", repo_id, quant, "http", hub_cache = repo.parent+ )+ inventory_scan.invalidate_hf_cache_scans()+ roots.clear()+ response = asyncio.run(+ gguf_variants.get_gguf_variants_response(+ repo_id, prefer_local_cache = True, offline = True, include_cache_locations = True+ )+ )+ variant = next(v for v in response.variants if v.quant == quant)+ assert variant.partial and not variant.downloaded+ assert roots and all(root == repo for root in roots), roots+ assert variant.partial_transport == "http"+++def test_a_cached_only_quant_is_judged_by_its_own_partial_state(cache_locations, monkeypatch):+ """A quant the current revision no longer lists has no scoped answer to consult, so the+ merge has to fall back to the copy's own per-snapshot verdict instead of trusting the+ synthesized row and advertising a cancelled download as loadable."""+ from hub.utils import gguf_sources+ from hub.utils.gguf import GgufVariantInfo++ repo_id, expected = cache_locations+ active = hf_cache_settings.get_hf_cache_paths().hub_cache+ quant, (repo, path) = next(+ (q, value) for q, value in expected.items() if value[0].parent != active+ )+ other = next(q for q, value in expected.items() if value[0].parent == active)+ listed = GgufVariantInfo(filename = f"Model-{other}.gguf", quant = other, size_bytes = 256)+ monkeypatch.setattr(gguf_variants, "list_gguf_variants", lambda *a, **k: ([listed], False, []))+ source = gguf_sources.CachedGgufSource(+ GgufVariantInfo(filename = path.name, quant = quant, size_bytes = 256),+ path.parent,+ False,+ )+ # The current revision cannot describe this quant, so its scoped answer returns no row.+ monkeypatch.setattr(+ gguf_sources, "cached_gguf_sources", lambda *a, **k: {quant.lower(): source}+ )+ monkeypatch.setattr(gguf_sources, "cached_gguf_source_partial", lambda *a, **k: True)+ inventory_scan.invalidate_hf_cache_scans()++ response = asyncio.run(+ gguf_variants.get_gguf_variants_response(repo_id, include_cache_locations = True)+ )+ variant = next(v for v in response.variants if v.quant == quant)+ assert not variant.downloaded+ assert variant.partial+++def test_the_delete_preview_follows_the_copy_the_row_carries(cache_locations, cache_client):+ """The listing hands each row the copy it resolved, and the confirm dialog must preview+ that same copy: without the reference the preview measures the active duplicate and+ describes a delete the user did not ask for."""+ repo_id, expected = cache_locations+ active = hf_cache_settings.get_hf_cache_paths().hub_cache+ quant = "Q4_K_M"+ for repo, path in expected.values():+ (path.parent / f"Model-{quant}.gguf").write_bytes(b"0" * 256)+ inventory_scan.invalidate_hf_cache_scans()+ remembered = next(repo for repo, _ in expected.values() if repo.parent != active)+ active_repo = next(repo for repo, _ in expected.values() if repo.parent == active)++ unscoped = cache_client.post(+ "/api/hub/delete-impact", json = {"repo_id": repo_id, "variant": quant}+ )+ assert unscoped.status_code == 200, unscoped.text+ assert unscoped.json()["cache_path"] == str(active_repo)++ scoped = cache_client.post(+ "/api/hub/delete-impact",+ json = {"repo_id": repo_id, "variant": quant, "cache_path": str(remembered)},+ )+ assert scoped.status_code == 200, scoped.text+ assert scoped.json()["cache_path"] == str(remembered)+ assert scoped.json()["reclaimed_bytes"] == 256++[email protected]("invalid_kind", ["unremembered", "expired_reference"])+def test_delete_preview_rejects_an_invalid_explicit_cache_copy(+ cache_locations, cache_client, tmp_path, invalid_kind+):+ """A stale picker target cannot promise a harmless delete that confirmation rejects."""+ from fastapi import HTTPException++ repo_id, expected = cache_locations+ cache_path = (+ str(tmp_path / "unremembered" / "models--Org--Model-GGUF")+ if invalid_kind == "unremembered"+ else "ref:" + "0" * 32+ )+ payload = {"repo_id": repo_id, "variant": "Q6_K", "cache_path": cache_path}+ preview = cache_client.post("/api/hub/delete-impact", json = payload)+ assert preview.status_code == 400, preview.text+ assert preview.json()["detail"] == "Invalid cache_path"+ with pytest.raises(HTTPException) as rejected:+ deletion._delete_cached_model_blocking(repo_id, "Q6_K", None, cache_path)+ assert rejected.value.status_code == 400+ assert rejected.value.detail == "Invalid cache_path"+ assert all(path.exists() for _, path in expected.values())diff --git a/studio/backend/tests/test_gguf_cache_switch_readiness.py b/studio/backend/tests/test_gguf_cache_switch_readiness.pynew file mode 100644index 00000000000..f5f71bf006f--- /dev/null+++ b/studio/backend/tests/test_gguf_cache_switch_readiness.py@@ -0,0 +1,233 @@+# 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 asyncio++import pytest++from hub.services.models import gguf_variants+from hub.utils import inventory_scan+from .gguf_cache_location_fixtures import cache_client, cache_locations+from utils import hf_cache_settings++[email protected]("entrypoint", ["source", "listing", "loader", "worker"])+def test_interrupted_projector_prefers_ready_duplicate(cache_locations, monkeypatch, entrypoint):+ from core.inference.llama_cpp import cached_gguf_for_load+ from hub.utils import download_manifest+ from hub.utils.gguf_sources import cached_gguf_sources++ repo_id, expected = cache_locations+ active = hf_cache_settings.get_hf_cache_paths().hub_cache+ quant = "Q4_K_M"+ filename = f"Model-{quant}.gguf"+ healthy = None+ for repo, path in expected.values():+ snapshot = path.parent+ (snapshot / filename).write_bytes(b"0" * 256)+ if repo.parent != active:+ (snapshot / "mmproj-F16.gguf").write_bytes(b"0" * 128)+ healthy = snapshot+ assert download_manifest.write_manifest(+ "model",+ repo_id,+ quant,+ [+ download_manifest.ExpectedFile(filename, 256),+ download_manifest.ExpectedFile("mmproj-F16.gguf", 128),+ ],+ hub_cache = repo.parent,+ commit_hash = snapshot.name,+ )+ assert healthy is not None+ inventory_scan.invalidate_hf_cache_scans()+ if entrypoint == "source":+ assert cached_gguf_sources(repo_id)[quant.lower()].snapshot == healthy+ elif entrypoint == "loader":+ assert cached_gguf_for_load(repo_id, quant) == str(healthy / filename)+ elif entrypoint == "worker":+ from core.inference.llama_cpp import LlamaCppBackend++ def offline(*args, **kwargs):+ raise ConnectionError("offline test")++ monkeypatch.setattr("huggingface_hub.list_repo_files", offline)+ monkeypatch.setattr("huggingface_hub.get_paths_info", offline)+ monkeypatch.setattr(+ "core.inference.llama_cpp.hf_hub_download_with_xet_fallback",+ lambda *args, **kwargs: pytest.fail("must reuse the complete remembered copy"),+ )+ actual = LlamaCppBackend()._download_gguf(hf_repo = repo_id, hf_variant = quant)+ assert actual == str(healthy / filename)+ assert (healthy / "mmproj-F16.gguf").is_file()+ else:+ response = asyncio.run(+ gguf_variants.get_gguf_variants_response(+ repo_id,+ prefer_local_cache = True,+ offline = True,+ include_cache_locations = True,+ )+ )+ variant = next(v for v in response.variants if v.quant == quant)+ assert variant.downloaded and not variant.partial+ assert variant.cache_path == str(healthy.parent.parent)++[email protected]("token", [False, "hf_fixture_token"])+def test_pin_listing_needs_explicit_token_when_ambient_is_denied(+ cache_locations, monkeypatch, token+):+ from hub.utils.gguf import GgufVariantInfo++ repo_id, expected = cache_locations+ quant, (repo, path) = next(+ (q, value)+ for q, value in expected.items()+ if value[0].parent != hf_cache_settings.get_hf_cache_paths().hub_cache+ )+ variant = GgufVariantInfo(filename = path.name, quant = quant, size_bytes = 256)+ # Main decides this by probing the Hub, and the fixture repo is not really there. The repo is+ # private to an ambient caller and reachable with an explicit token, which is the difference+ # this test measures, so answer the probe instead of the network.+ monkeypatch.setattr(+ "hub.utils.hf_tokens._explicit_token_reaches_repo",+ lambda repo, token, *a, **k: token is not None,+ )+ monkeypatch.setattr(gguf_variants, "list_gguf_variants", lambda *a, **k: ([variant], False, []))+ response = asyncio.run(+ gguf_variants.get_gguf_variants_response(+ repo_id,+ hf_token = token,+ prefer_local_cache = True,+ include_cache_locations = True,+ )+ )+ actual = next(v for v in response.variants if v.quant == quant)+ assert actual.downloaded is bool(token)++[email protected]("entrypoint", ["listing", "source"])+def test_incomplete_remembered_copy_is_not_advertised_complete(+ cache_locations, monkeypatch, entrypoint+):+ """An offline/local answer has no Hub check to fall back on, so the remembered copy is+ judged by its own manifest: a quant whose companion never finished is not a complete+ copy the picker may offer to load, even though every main shard is on disk."""+ from hub.utils import download_manifest+ from hub.utils.gguf_sources import cached_gguf_source_partial, cached_gguf_sources++ repo_id, expected = cache_locations+ active = hf_cache_settings.get_hf_cache_paths().hub_cache+ quant = "Q4_K_M"+ filename = f"Model-{quant}.gguf"+ # The remembered copy holds every main shard but is missing its projector, which is+ # exactly the torn state a completed-looking snapshot can hide.+ remembered = None+ for repo, path in expected.values():+ if repo.parent == active:+ continue+ snapshot = path.parent+ (snapshot / filename).write_bytes(b"0" * 256)+ remembered = snapshot+ assert download_manifest.write_manifest(+ "model",+ repo_id,+ quant,+ [+ download_manifest.ExpectedFile(filename, 256),+ download_manifest.ExpectedFile("mmproj-F16.gguf", 128),+ ],+ hub_cache = repo.parent,+ commit_hash = snapshot.name,+ )+ assert remembered is not None+ inventory_scan.invalidate_hf_cache_scans()+ assert not (remembered / "mmproj-F16.gguf").is_file()+ assert cached_gguf_source_partial(repo_id, quant, remembered)++ if entrypoint == "source":+ assert cached_gguf_sources(repo_id)[quant.lower()].snapshot == remembered+ return++ response = asyncio.run(+ gguf_variants.get_gguf_variants_response(+ repo_id,+ prefer_local_cache = True,+ offline = True,+ include_cache_locations = True,+ )+ )+ variant = next(v for v in response.variants if v.quant == quant)+ assert not variant.downloaded+ assert variant.partial+ assert variant.cache_path == str(remembered.parent.parent)+++def test_a_healthy_duplicate_is_preferred_over_a_cancelled_copy(cache_locations):+ """A copy its own snapshot state marks partial -- here a cancel marker -- must not shadow a+ healthy duplicate of the same quant: the merge would report the quant as unusable and offer+ a retry for a copy that is already loadable from the other remembered folder."""+ from hub.utils import download_manifest+ from hub.utils.gguf_sources import cached_gguf_source_partial, cached_gguf_sources++ repo_id, expected = cache_locations+ active = hf_cache_settings.get_hf_cache_paths().hub_cache+ quant = "Q4_K_M"+ filename = f"Model-{quant}.gguf"+ # The same quant is present in two folders, which is exactly what duplicate ranking decides.+ cancelled = healthy = None+ for repo, path in expected.values():+ snapshot = path.parent+ (snapshot / filename).write_bytes(b"0" * 256)+ if repo.parent == active:+ cancelled = snapshot+ else:+ healthy = snapshot+ assert cancelled is not None and healthy is not None+ # Manifest-verified by construction (every file it declares exists), yet partial by its own+ # marker -- the state a manifest-only comparison cannot see.+ assert download_manifest.write_cancel_marker(+ "model", repo_id, quant, hub_cache = cancelled.parent.parent.parent+ )+ inventory_scan.invalidate_hf_cache_scans()+ assert cached_gguf_source_partial(repo_id, quant, cancelled)+ assert not cached_gguf_source_partial(repo_id, quant, healthy)+ assert cached_gguf_sources(repo_id)[quant.lower()].snapshot == healthy++ response = asyncio.run(+ gguf_variants.get_gguf_variants_response(+ repo_id,+ prefer_local_cache = True,+ offline = True,+ include_cache_locations = True,+ )+ )+ variant = next(v for v in response.variants if v.quant == quant)+ assert variant.downloaded+ assert not variant.partial+ assert variant.cache_path == str(healthy.parent.parent)+++def test_an_authorized_anonymous_caller_still_sees_remembered_caches(cache_locations, monkeypatch):+ """hub_cached_read_refused authorizes a public repo for the sentinel; a second anonymous+ test here re-refused it and dropped a quant that exists only in a remembered folder."""+ repo_id, expected = cache_locations+ active = hf_cache_settings.get_hf_cache_paths().hub_cache+ quant, (repo, _path) = next(+ (q, value) for q, value in expected.items() if value[0].parent != active+ )+ monkeypatch.setattr("hub.utils.hf_tokens._explicit_token_reaches_repo", lambda *a, **k: True)+ monkeypatch.setattr(gguf_variants, "list_gguf_variants", lambda *a, **k: ([], False, []))+ inventory_scan.invalidate_hf_cache_scans()+ response = asyncio.run(+ gguf_variants.get_gguf_variants_response(+ repo_id,+ hf_token = False,+ prefer_local_cache = True,+ offline = True,+ include_cache_locations = True,+ )+ )+ found = next(v for v in response.variants if v.quant == quant)+ assert found.cache_path == str(repo)diff --git a/studio/backend/tests/test_gguf_cache_switch_resolution.py b/studio/backend/tests/test_gguf_cache_switch_resolution.pynew file mode 100644index 00000000000..90da8d55471--- /dev/null+++ b/studio/backend/tests/test_gguf_cache_switch_resolution.py@@ -0,0 +1,211 @@+# 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 asyncio++import pytest++from hub.services.models import gguf_variants+from hub.utils import inventory_scan+from .gguf_cache_location_fixtures import cache_client, cache_locations+from utils import hf_cache_settings+++def test_media_sources_do_not_enter_chat_resolution(cache_locations, monkeypatch):+ from hub.utils.gguf_sources import cached_gguf_action_path, cached_gguf_sources++ repo_id, expected = cache_locations+ monkeypatch.setattr(+ "hub.services.models.catalog_classification._gguf_path_task", lambda *args: "text-to-image"+ )+ assert cached_gguf_sources(repo_id) == {}+ assert cached_gguf_action_path(repo_id, "Q6_K") is None+ explicit = str(expected["Q6_K"][0])+ assert cached_gguf_action_path(repo_id, "Q6_K", explicit) == explicit++[email protected]("missing_context", [False, True])+def test_cached_quant_keeps_its_own_context(cache_locations, cache_client, missing_context):+ import struct++ repo_id, expected = cache_locations+ contexts = {"Q6_K": 131072, "Q8_0": None if missing_context else 32768}++ def gguf_string(value):+ encoded = value.encode()+ return struct.pack("<Q", len(encoded)) + encoded++ for quant, (_, path) in expected.items():+ context = contexts[quant]+ header = b"GGUF" + struct.pack("<IQQ", 3, 0, 1 if context is None else 2)+ header += gguf_string("general.architecture") + struct.pack("<I", 8) + gguf_string("llama")+ if context is not None:+ header += gguf_string("llama.context_length") + struct.pack("<II", 4, context)+ path.write_bytes(header.ljust(256, b"\0"))+ inventory_scan.invalidate_hf_cache_scans()+ response = cache_client.get(+ "/api/models/gguf-variants",+ params = {+ "repo_id": repo_id,+ "prefer_local_cache": True,+ "offline": True,+ "include_cache_locations": True,+ },+ )+ assert response.status_code == 200, response.text+ listing = response.json()+ # This is the native limit the picker supplies when the user selects/configures a quant.+ actual = {+ v["quant"]: v.get("context_length", listing["context_length"])+ for v in listing["variants"]+ if v["downloaded"]+ }+ assert actual == contexts++[email protected]("undersized", [False, True])[email protected]("fail_repeat_listing", [False, True])+def test_inactive_source_uses_scoped_online_status(+ cache_locations, monkeypatch, undersized, fail_repeat_listing+):+ from hub.utils.download_manifest import ExpectedFile+ from hub.utils.gguf import GgufVariantInfo+ from hub.utils.gguf_plan import plan_from_expected_files++ repo_id, expected = cache_locations+ quant, (repo, path) = next(+ (q, source)+ for q, source in expected.items()+ if source[0].parent != hf_cache_settings.get_hf_cache_paths().hub_cache+ )+ # A normal HF snapshot symlink identifies the old blob independently of its byte size.+ payload = path.read_bytes()+ path.unlink()+ blob = repo / "blobs" / ("a" * 64)+ blob.parent.mkdir(exist_ok = True)+ blob.write_bytes(payload[:32] if undersized else payload)+ path.symlink_to(blob)+ variant = GgufVariantInfo(filename = path.name, quant = quant, size_bytes = 256)+ requirement = plan_from_expected_files(quant, [ExpectedFile(path.name, 256, "b" * 64)])+ listing_calls = []++ def list_online(*args, **kwargs):+ listing_calls.append(repo_id)+ if fail_repeat_listing and len(listing_calls) > 1:+ raise ConnectionError("a repeated Hub request failed")+ return [variant], False, []++ monkeypatch.setattr(gguf_variants, "list_gguf_variants", list_online)+ monkeypatch.setattr(gguf_variants, "_variant_requirement_cache_get", lambda *a: requirement)+ inventory_scan.invalidate_hf_cache_scans()+ scoped = asyncio.run(+ gguf_variants.get_gguf_variants_response(+ repo_id,+ local_path = str(path.parent),+ )+ )+ listing_calls.clear()+ merged = asyncio.run(+ gguf_variants.get_gguf_variants_response(+ repo_id,+ include_cache_locations = True,+ )+ )+ assert listing_calls == [repo_id]+ direct = next(v for v in scoped.variants if v.quant == quant)+ actual = next(v for v in merged.variants if v.quant == quant)+ assert direct.downloaded is not undersized+ assert direct.update_available is not undersized+ assert (actual.downloaded, actual.partial, actual.update_available) == (+ direct.downloaded,+ direct.partial,+ direct.update_available,+ )+++def test_memory_estimate_uses_the_copy_selected_for_load(cache_locations):+ from core.inference.llama_cpp import cached_gguf_for_load+ from routes.models import _resolve_quant_gguf++ repo_id, expected = cache_locations+ active = hf_cache_settings.get_hf_cache_paths().hub_cache+ for repo, path in expected.values():+ (path.parent / "Model-Q4_K_M.gguf").write_bytes(+ b"0" * (128 if repo.parent == active else 512)+ )+ inventory_scan.invalidate_hf_cache_scans()+ loaded = cached_gguf_for_load(repo_id, "Q4_K_M")+ estimated, size = _resolve_quant_gguf(repo_id, "Q4_K_M", False)+ assert estimated == loaded+ assert size == 128++[email protected]("endpoint", ["/api/models/gguf-variants", "/api/hub/gguf-variants"])[email protected]("failure", ["network", 503, 401, 403, 404, 429])+def test_inactive_only_chat_cache_handles_hub_failures(+ cache_locations, cache_client, monkeypatch, endpoint, failure+):+ import httpx++ repo_id, expected = cache_locations+ active_root = hf_cache_settings.get_hf_cache_paths().hub_cache+ active_path = next(path for repo, path in expected.values() if repo.parent == active_root)+ active_path.unlink()+ quant, (repo, path) = next(+ (quant, pair) for quant, pair in expected.items() if pair[0].parent != active_root+ )+ inventory_scan.invalidate_hf_cache_scans()+ error = (+ ConnectionError("Hub temporarily unavailable")+ if failure == "network"+ else (+ httpx.HTTPStatusError(+ "Hub response failed",+ request = httpx.Request("GET", "https://huggingface.co/api/models/Org/Model-GGUF"),+ response = httpx.Response(failure),+ )+ )+ )++ def unavailable(*args, **kwargs):+ raise error++ monkeypatch.setattr(gguf_variants, "list_gguf_variants", unavailable)+ transient = failure == "network" or failure == 503+ if transient:+ scoped = cache_client.get(+ endpoint,+ params = {"repo_id": repo_id, "local_path": str(path.parent)},+ )+ assert scoped.status_code == 200, scoped.text+ assert {v["quant"] for v in scoped.json()["variants"] if v["downloaded"]} == {quant}++ response = cache_client.get(+ endpoint,+ params = {+ "repo_id": repo_id,+ "local_path": repo_id,+ "include_cache_locations": True,+ },+ )+ if not transient:+ assert response.status_code == failure, response.text+ return+ assert response.status_code == 200, response.text+ variants = [v for v in response.json()["variants"] if v["downloaded"]]+ assert [(v["quant"], v["cache_path"]) for v in variants] == [(quant, str(repo))]+ assert not variants[0]["partial"]++[email protected]("task", ["text-to-image", "text-to-video", "text-to-speech"])+def test_media_loader_does_not_reuse_inactive_cache(cache_locations, monkeypatch, task):+ from core.inference.llama_cpp import cached_gguf_for_load++ repo_id, expected = cache_locations+ active = hf_cache_settings.get_hf_cache_paths().hub_cache+ monkeypatch.setattr(+ "hub.services.models.catalog_classification._gguf_path_task", lambda *args: task+ )+ for quant, (repo, path) in expected.items():+ actual = cached_gguf_for_load(repo_id, quant)+ assert actual == (str(path) if repo.parent == active else None)diff --git a/studio/backend/tests/test_gguf_variant_rows.py b/studio/backend/tests/test_gguf_variant_rows.pyindex d3112ffeaf3..1812ffc7d74 100644--- a/studio/backend/tests/test_gguf_variant_rows.py+++ b/studio/backend/tests/test_gguf_variant_rows.py@@ -1112,7 +1112,7 @@ def test_every_branch_derives_the_default_from_the_root_rows():assert service._default_variant_candidates(rows[:1]) == ["distilled/model-Q6_K.gguf"]# No branch may call pick_best_gguf on the raw filenames any more.source = inspect.getsource(service)- assert source.count("pick_best_gguf(_default_variant_candidates(") == 4+ assert source.count("pick_best_gguf(_default_variant_candidates(") == 5assert "pick_best_gguf(filenames)" not in sourcediff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex 440fb3122c6..b5f9f424cfb 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -2645,7 +2645,7 @@ function buildAutoLoadSources(listVariants: () =>listGgufVariants(repo.repo_id, undefined, {preferLocalCache: true,- localPath: repo.cache_path,+ localPath: repo.load_id || repo.cache_path,signal,}).then((response) => response.variants),});diff --git a/studio/frontend/src/features/chat/api/gguf-variants-request.ts b/studio/frontend/src/features/chat/api/gguf-variants-request.tsindex f3b87e55a48..cbf3f207bb9 100644--- a/studio/frontend/src/features/chat/api/gguf-variants-request.ts+++ b/studio/frontend/src/features/chat/api/gguf-variants-request.ts@@ -17,6 +17,7 @@ export const GGUF_VARIANTS_TIMEOUT_MS = 30_000;export interface GgufVariantsRequestOptions {preferLocalCache?: boolean;+ includeCacheLocations?: boolean;localPath?: string | null;signal?: AbortSignal;}@@ -29,6 +30,10 @@ export function ggufVariantsQuery(offline: boolean,): URLSearchParams {const params = new URLSearchParams({ repo_id: repoId });+ // Chat resolves logical quants across remembered folders. Media callers opt out.+ if (options?.includeCacheLocations !== false) {+ params.set("include_cache_locations", "true");+ }if (options?.preferLocalCache || offline) {params.set("prefer_local_cache", "true");}diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.tsindex 2ddbf020dea..65a80227a2e 100644--- a/studio/frontend/src/features/chat/types/api.ts+++ b/studio/frontend/src/features/chat/types/api.ts@@ -160,6 +160,11 @@ export interface ValidateModelResponse {}export interface GgufVariantDetail {+ context_length?: number | null;+ cache_path?: string | null;+ /** Opaque stand-in for `cache_path` under host-path redaction; the only name an API-key+ * caller has for one specific copy, so a delete keeps it instead of the cleared path. */+ cache_ref?: string | null;filename: string;/** Selection identity. Path-qualified when a repo holds several checkpoints at one quant. */quant: string;diff --git a/studio/frontend/src/features/hub/catalog/delete-impact.tsx b/studio/frontend/src/features/hub/catalog/delete-impact.tsxindex 712ec68aa57..cc17f5eea6a 100644--- a/studio/frontend/src/features/hub/catalog/delete-impact.tsx+++ b/studio/frontend/src/features/hub/catalog/delete-impact.tsx@@ -17,6 +17,8 @@ export function useDeleteImpact(open: boolean,repoId: string,variant?: string | null,+ /** The copy the delete targets, so the preview measures that one and not another duplicate. */+ cachePath?: string | null,): DeleteImpact | null {const [impact, setImpact] = useState<DeleteImpact | null>(null);useEffect(() => {@@ -25,13 +27,13 @@ export function useDeleteImpact(return;}let cancelled = false;- void fetchDeleteImpact(repoId, variant ?? undefined).then((result) => {+ void fetchDeleteImpact(repoId, variant ?? undefined, cachePath ?? undefined).then((result) => {if (!cancelled) setImpact(result);});return () => {cancelled = true;};- }, [open, repoId, variant]);+ }, [open, repoId, variant, cachePath]);return impact;}@@ -60,6 +62,11 @@ export function DeleteImpactSummary({ impact }: { impact: DeleteImpact | null })const freeable = impact.freeable_companions.reduce((sum, c) => sum + c.size_bytes, 0);return (<span className="mt-2 block space-y-1 text-ui-12p5">+ {impact.cache_path && (+ <span className="block break-all text-muted-foreground" data-testid="delete-impact-folder">+ Folder: {impact.cache_path}+ </span>+ )}<span className="block text-foreground" data-testid="delete-impact-reclaimed">Frees {formatBytes(impact.reclaimed_bytes)} of disk space.</span>diff --git a/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx b/studio/frontend/src/features/hub/catalog/gguf-download-card.tsxindex b05e35fc923..fd075833919 100644--- a/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx+++ b/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx@@ -603,13 +603,14 @@ export function GgufDownloadCard({const hfToken = useHfTokenStore((s) => s.token);const online = useOnlineStatus();const partialsResumable = useHttpPartialsResumable();- const localVariantPath = cachePath?.trim() || null;+ const localVariantPath = showMemoryBar ? null : cachePath?.trim() || null;const { variants, loading, error, refreshError, refresh } =useGgufVariantFetchState({repoId,hfToken,preferLocalCache,localPath: localVariantPath,+ includeCacheLocations: showMemoryBar,});const [selectedQuantState, setSelectedQuantState] = useState<{repoId: string;@@ -843,7 +844,13 @@ export function GgufDownloadCard({const deleteTargetLabel = deleteTargetVariant? ggufVariantDisplayLabel(deleteTargetVariant): deleteTarget;- const deleteImpact = useDeleteImpact(deleteTarget !== null, repoId, deleteTarget);+ // The same identity the delete below sends, so the preview measures the copy that goes.+ const deleteImpact = useDeleteImpact(+ deleteTarget !== null,+ repoId,+ deleteTarget,+ deleteTargetVariant?.cache_ref ?? deleteTargetVariant?.cache_path ?? cachePath ?? undefined,+ );const { deleting, runDelete } = useDeleteConfirmAction({action: async () => {if (!deleteTarget) return;@@ -851,7 +858,12 @@ export function GgufDownloadCard({repoId,deleteTarget,hfToken || undefined,- cachePath ?? undefined,+ // Redaction clears the path and leaves the reference: forwarding it keeps the+ // delete on this row instead of whichever duplicate the server ranks first.+ deleteTargetVariant?.cache_ref ??+ deleteTargetVariant?.cache_path ??+ cachePath ??+ undefined,);},successMessage: () =>diff --git a/studio/frontend/src/features/hub/catalog/models-catalog-rows.tsx b/studio/frontend/src/features/hub/catalog/models-catalog-rows.tsxindex 8905692e7f8..930c109e6b9 100644--- a/studio/frontend/src/features/hub/catalog/models-catalog-rows.tsx+++ b/studio/frontend/src/features/hub/catalog/models-catalog-rows.tsx@@ -1,6 +1,8 @@// 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 { isChatGgufTask, reconcileGgufPinsAfterDelete } from "@/features/model-picker/components/model-selector/reconcile-gguf-pins";+import {Tooltip,TooltipContent,@@ -776,9 +778,14 @@ export const InventoryRow = memo(function InventoryRow({undefined,rowCachePath,);- // Deleted repos can't stay pinned: drop the repo pin and any of- // its per-quant pins so stale rows don't linger up top.- usePinnedModelsStore.getState().unpinRepo(deletableRepoId);+ if (row.isGguf && isChatGgufTask(row.pipelineTag)) {+ await reconcileGgufPinsAfterDelete(+ deletableRepoId,+ useHfTokenStore.getState().token || undefined,+ );+ } else {+ usePinnedModelsStore.getState().unpinRepo(deletableRepoId);+ }}},onDeleted: onChange,diff --git a/studio/frontend/src/features/hub/catalog/use-gguf-variant-fetch-state.ts b/studio/frontend/src/features/hub/catalog/use-gguf-variant-fetch-state.tsindex aeba45383dc..d8521681f72 100644--- a/studio/frontend/src/features/hub/catalog/use-gguf-variant-fetch-state.ts+++ b/studio/frontend/src/features/hub/catalog/use-gguf-variant-fetch-state.ts@@ -27,6 +27,7 @@ export function useGgufVariantFetchState({repoId,hfToken,preferLocalCache = false,+ includeCacheLocations = false,localPath = null,enabled = true,errorFallback = "Failed to load variants",@@ -34,6 +35,7 @@ export function useGgufVariantFetchState({repoId: string;hfToken?: string | null;preferLocalCache?: boolean;+ includeCacheLocations?: boolean;localPath?: string | null;enabled?: boolean;errorFallback?: string;@@ -44,8 +46,8 @@ export function useGgufVariantFetchState({() =>`${repoId}::${fingerprintToken(hfToken)}::${preferLocalCache ? "local" : "remote"- }::${localVariantPath ?? ""}`,- [hfToken, localVariantPath, preferLocalCache, repoId],+ }::${localVariantPath ?? ""}::${includeCacheLocations}`,+ [hfToken, localVariantPath, preferLocalCache, includeCacheLocations, repoId],);const variantKey = useMemo(() => `${variantScopeKey}::${variantsVersion}`,@@ -94,6 +96,7 @@ export function useGgufVariantFetchState({try {const response = await listGgufVariants(repoId, hfToken || undefined, {preferLocalCache,+ includeCacheLocations,localPath: localVariantPath,signal: controller.signal,});@@ -135,6 +138,7 @@ export function useGgufVariantFetchState({hfToken,localVariantPath,preferLocalCache,+ includeCacheLocations,repoId,variantScopeKey,variantKey,diff --git a/studio/frontend/src/features/hub/inventory/api.ts b/studio/frontend/src/features/hub/inventory/api.tsindex efb5974ad25..0d5e3cf3404 100644--- a/studio/frontend/src/features/hub/inventory/api.ts+++ b/studio/frontend/src/features/hub/inventory/api.ts@@ -177,6 +177,11 @@ export interface ScanFolderInfo {}export interface GgufVariantDetail {+ context_length?: number | null;+ cache_path?: string | null;+ /** Opaque stand-in for `cache_path` under host-path redaction; the only name an+ * API-key caller has for one specific copy. */+ cache_ref?: string | null;filename: string;quant: string;display_label?: string | null;@@ -327,6 +332,7 @@ export interface CompanionAssetInfo {}export interface DeleteImpact {+ cache_path?: string | null;repo_id: string;variant?: string | null;reclaimed_bytes: number;@@ -340,13 +346,16 @@ export interface DeleteImpact {export async function fetchDeleteImpact(repoId: string,variant?: string | null,+ cachePath?: string | null,): Promise<DeleteImpact | null> {try {const response = await authFetch("/api/hub/delete-impact", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify(- variant ? { repo_id: repoId, variant } : { repo_id: repoId },+ variant+ ? { repo_id: repoId, variant, ...(cachePath ? { cache_path: cachePath } : {}) }+ : { repo_id: repoId, ...(cachePath ? { cache_path: cachePath } : {}) },),});if (!response.ok) return null;@@ -477,6 +486,7 @@ export async function listGgufVariants(hfToken?: string,options?: {preferLocalCache?: boolean;+ includeCacheLocations?: boolean;localPath?: string | null;signal?: AbortSignal;},@@ -487,7 +497,7 @@ export async function listGgufVariants(const signal = options?.signal;const key = `${repoId}::${fingerprintToken(hfToken)}::${preferLocalCache ? "local" : "remote"- }::${localPathCacheKey(localPath)}`;+ }::${localPathCacheKey(localPath)}::${!!options?.includeCacheLocations}`;const now = Date.now();const hit = ggufVariantsCache.get(key);if (hit && now < hit.expiresAt) {@@ -499,6 +509,9 @@ export async function listGgufVariants(ggufVariantsCache.delete(key);}const params = new URLSearchParams({ repo_id: repoId });+ if (options?.includeCacheLocations) {+ params.set("include_cache_locations", "true");+ }if (preferLocalCache) {params.set("prefer_local_cache", "true");}diff --git a/studio/frontend/src/features/model-picker/components/model-selector/model-row-menu.tsx b/studio/frontend/src/features/model-picker/components/model-selector/model-row-menu.tsxindex f6abaea9b86..09bed305a6e 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/model-row-menu.tsx+++ b/studio/frontend/src/features/model-picker/components/model-selector/model-row-menu.tsx@@ -73,7 +73,7 @@ interface ModelRowMenuDelete {description: ReactNode;/** Repo (and quant) to preview the delete for, so the dialog can state what it actually reclaims* and what shared assets it leaves behind. Omit to keep the plain wording. */- impact?: { repoId: string; variant?: string | null };+ impact?: { repoId: string; variant?: string | null; cachePath?: string | null };successMessage: string;disabled?: boolean;onConfirm: () => Promise<void> | void;@@ -116,6 +116,7 @@ export function ModelRowMenu({deleteOpen && Boolean(del?.impact),del?.impact?.repoId ?? "",del?.impact?.variant,+ del?.impact?.cachePath,);const [updateOpen, setUpdateOpen] = useState(false);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.tsxindex 74044132b08..faaa00f9043 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@@ -1,6 +1,8 @@// 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 { isChatGgufTask, reconcileGgufPinsAfterDelete } from "./reconcile-gguf-pins";+import { ModelMemoryBar } from "@/components/model-memory-bar";import { shouldRefreshPickerInventoryOnMount } from "@/components/resource-picker/picker-tab-policy";import { Checkbox } from "@/components/ui/checkbox";@@ -252,6 +254,7 @@ import {ggufQuantChipLabel,ggufQuantDetailLabel,ggufVariantPickerLabel,+ ggufVariantContextLength,groupGgufVariantsForPicker,h3PickerHasOnlyPrunedBuilds,preferredGgufVariantByGroup,@@ -1537,6 +1540,7 @@ async function readSoleQuant(try {const res = await listGgufVariantsCached(target.repoId, hfToken, {localPath: target.localSource,+ includeCacheLocations: target.includeCacheLocations,});const normalized = normalizeGgufVariantsResponse(res);const variant = verifiedSoleHubVariant(@@ -1579,6 +1583,7 @@ function useSoleDownloadedQuants(return {repoId: repo.repo_id,localSource,+ includeCacheLocations: !mediaPageForTask(repo.task),fingerprint,key: soleQuantKey(versions[index], localSource, fingerprint),};@@ -1698,7 +1703,7 @@ function GgufVariantExpander({renderUpdateDescription?: (quant: string) => ReactNode;getUpdateSuccessMessage?: (quant: string) => string;updateDisabled?: boolean;- onDelete?: (quant: string) => Promise<void> | void;+ onDelete?: (quant: string, cachePath?: string | null) => Promise<void> | void;deleteTitle?: string;renderDeleteDescription?: (quant: string) => ReactNode;getDeleteSuccessMessage?: (quant: string) => string;@@ -1755,10 +1760,10 @@ function GgufVariantExpander({setResolvedLocally(false);});- // The row's own directory, so disk contents count against that cache, not the active one. No- // preferLocalCache: it answers from disk alone.+ // Chat rows name the repository; media and explicit local rows retain their folder scope.listGgufVariants(repoId, hfToken, {...(localSource ? { localPath: localSource } : {}),+ includeCacheLocations: !mediaPageForTask(pipelineTag),signal: controller.signal,}).then((res) => {@@ -1785,7 +1790,7 @@ function GgufVariantExpander({canceled = true;controller.abort();};- }, [repoId, localSource, refreshKey, hfToken]);+ }, [repoId, localSource, refreshKey, hfToken, pipelineTag]);// Covers Unix absolute, Windows drive, UNC, relative and tilde paths.const isLocalPath = /^(\/|\.{1,2}[\\/]|~[\\/]|[A-Za-z]:[\\/]|\\\\)/.test(@@ -1808,6 +1813,7 @@ function GgufVariantExpander({downloaded?: boolean,sizeBytes?: number,downloadPresentation?: ModelSelectorChangeMeta["downloadPresentation"],+ contextLength: number | null = nativeContext,) => {const isAvailable = isLocalPath || downloaded === true;onSelect(repoId, {@@ -1820,7 +1826,7 @@ function GgufVariantExpander({isDownloaded: isLocalPath ? true : downloaded,expectedBytes: sizeBytes,downloadPresentation,- contextLength: isAvailable ? nativeContext : undefined,+ contextLength: isAvailable ? contextLength : undefined,isGguf: true,isVision: variantVisionHint,pipelineTag,@@ -2169,6 +2175,7 @@ function GgufVariantExpander({const fit = getVariantFit(v);const oom = fit === "oom";const expectedBytes = ggufVariantExpectedBytes(v);+ const variantContext = ggufVariantContextLength(v, nativeContext);// This row's own dependency group, never the listing's: see the footprintVariants comment above.const companionBytes =companionBytesByKey.get(v.dependency_key ?? "") ?? null;@@ -2188,6 +2195,7 @@ function GgufVariantExpander({v.downloaded,expectedBytes,pendingDrafterPresentation(v),+ variantContext,)}className={cn(@@ -2289,7 +2297,7 @@ function GgufVariantExpander({ggufVariant: v.quant,isDownloaded: true,expectedBytes,- contextLength: nativeContext,+ contextLength: variantContext,isGguf: true,isVision: variantVisionHint,})@@ -2345,7 +2353,11 @@ function GgufVariantExpander({onDeleteVariant? {title: deleteVariantTitle,- impact: { repoId, variant: v.quant },+ impact: {+ repoId,+ variant: v.quant,+ cachePath: v.cache_ref ?? v.cache_path,+ },description: renderDeleteVariantDescription?.(v.quant,) ?? (@@ -2362,13 +2374,14 @@ function GgufVariantExpander({`Deleted ${repoId} ${v.quant}`,disabled: deleteDisabled,onConfirm: async () => {- await onDeleteVariant(v.quant);- // Drop the pin too: a pinned row for a deleted file loads something gone.- if (pinnedKeys.includes(pinKey(repoId, v.quant))) {+ await onDeleteVariant(v.quant, v.cache_ref ?? v.cache_path);+ if (isChatGgufTask(pipelineTag)) {+ await reconcileGgufPinsAfterDelete(repoId, hfToken);+ } else if (pinnedKeys.includes(pinKey(repoId, v.quant))) {togglePinnedQuant(repoId, v.quant);}- // Re-fetch this expander's variants so the deleted quant stops showing as downloaded while the- // repo's other cached quants remain.+ // Re-fetch this expander's variants so the deleted quant stops showing as+ // downloaded while other cached quants remain.setRefreshKey((key) => key + 1);},}@@ -4572,12 +4585,13 @@ export function HubModelPicker({}, [pinnedIds, sortedCachedGguf, formatFilter]);const [pinnedQuantValidation, setPinnedQuantValidation] = useState<{validated: boolean;- downloaded: ReadonlySet<string>;+ /** Verified downloads by pin key; the value is the copy the listing resolved them in. */+ downloaded: ReadonlyMap<string, string | null>;visionByRepo: ReadonlyMap<string, boolean>;sizes: ReadonlyMap<string, number>;}>({validated: false,- downloaded: new Set(),+ downloaded: new Map(),visionByRepo: new Map(),sizes: new Map(),});@@ -4586,7 +4600,7 @@ export function HubModelPicker({const key = pinKey(repoId, quant);setPinnedQuantValidation((prev) => {if (!prev.downloaded.has(key)) return prev;- const downloaded = new Set(prev.downloaded);+ const downloaded = new Map(prev.downloaded);downloaded.delete(key);return { ...prev, downloaded };});@@ -4607,7 +4621,9 @@ export function HubModelPicker({const response = await listGgufVariantsCached(repoId,hfToken || undefined,- { preferLocalCache: true },+ { preferLocalCache: true, includeCacheLocations: !mediaPageForTask(+ sortedCachedGguf.find((row) => row.repo_id === repoId)?.task,+ ) },);const normalized = normalizeGgufVariantsResponse(response);const downloaded = normalized.variants.filter(@@ -4616,8 +4632,11 @@ export function HubModelPicker({return {repoId,hasVision: normalized.hasVision,- downloaded: downloaded.map((variant) =>- pinKey(repoId, variant.quant),+ downloaded: downloaded.map(+ (variant): [string, string | null] => [+ pinKey(repoId, variant.quant),+ variant.cache_ref ?? variant.cache_path ?? null,+ ],),sizes: downloaded.map((variant) =>@@ -4634,7 +4653,7 @@ export function HubModelPicker({if (!cancelled) {setPinnedQuantValidation({validated: true,- downloaded: new Set(groups.flatMap((group) => group.downloaded)),+ downloaded: new Map(groups.flatMap((group) => group.downloaded)),visionByRepo: new Map(groups.flatMap((group) =>group.hasVision === undefined@@ -4650,12 +4669,12 @@ export function HubModelPicker({return () => {cancelled = true;};- }, [hfToken, pinnedQuantCandidates]);- const downloadedPinnedQuantKeys = useMemo<ReadonlySet<string>>(+ }, [hfToken, pinnedQuantCandidates, sortedCachedGguf]);+ const downloadedPinnedQuantPaths = useMemo<ReadonlyMap<string, string | null>>(() =>pinnedQuantValidation.validated? pinnedQuantValidation.downloaded- : new Set(),+ : new Map(),[pinnedQuantValidation],);@@ -4664,11 +4683,11 @@ export function HubModelPicker({const q = normalizeForSearch(debouncedQuery.trim());return pinnedQuantCandidates.filter((entry) =>- downloadedPinnedQuantKeys.has(pinKey(entry.repoId, entry.quant)) &&+ downloadedPinnedQuantPaths.has(pinKey(entry.repoId, entry.quant)) &&(!q ||normalizeForSearch(`${entry.repoId} ${entry.quant}`).includes(q)),);- }, [debouncedQuery, downloadedPinnedQuantKeys, pinnedQuantCandidates]);+ }, [debouncedQuery, downloadedPinnedQuantPaths, pinnedQuantCandidates]);const pinnedCachedModelRows = useMemo(() =>@@ -5728,6 +5747,10 @@ export function HubModelPicker({// Its repo's own sole-quant row, with that row's load target and selection state.const soleRow = pinnedSoleQuantRows.get(pinKey(entry.repoId, entry.quant));if (soleRow) return renderSoleQuantGgufRow(soleRow.repo, soleRow.sole);+ // The copy the validation listing resolved this quant in, so the delete removes that one.+ const pinnedCopyPath = downloadedPinnedQuantPaths.get(+ pinKey(entry.repoId, entry.quant),+ );const optionKey = makeModelOptionKey("pinned-quant",pinKey(entry.repoId, entry.quant),@@ -5832,7 +5855,11 @@ export function HubModelPicker({title: "Delete cached model?",// Same preview the Hub On Device row asks for, so a companion base an installed image model// still needs shows the reason and a disabled Delete.- impact: { repoId: entry.repoId, variant: entry.quant },+ impact: {+ repoId: entry.repoId,+ variant: entry.quant,+ cachePath: pinnedCopyPath,+ },description: (<>This will remove{" "}@@ -5849,10 +5876,14 @@ export function HubModelPicker({entry.repoId,entry.quant,hfToken || undefined,+ pinnedCopyPath ?? undefined,);refreshCachedLists();- // The file is gone, so drop its pin too.- togglePinned(entry.repoId, entry.quant);+ if (isChatGgufTask(diffusionTaskById.get(entry.repoId.toLowerCase()))) {+ await reconcileGgufPinsAfterDelete(entry.repoId, hfToken || undefined);+ } else {+ togglePinned(entry.repoId, entry.quant);+ }},}}/>@@ -5963,7 +5994,14 @@ export function HubModelPicker({}}del={{title: "Delete cached model?",- impact: { repoId: c.repo_id, variant: variant.quant },+ impact: {+ repoId: c.repo_id,+ variant: variant.quant,+ cachePath:+ variant.cache_ref ??+ variant.cache_path ??+ (mediaPageForTask(c.task) ? c.cache_path : null),+ },description: (<>This will remove{" "}@@ -5980,10 +6018,16 @@ export function HubModelPicker({c.repo_id,variant.quant,hfToken || undefined,- c.cache_path || undefined,+ variant.cache_ref ??+ variant.cache_path ??+ (mediaPageForTask(c.task) ? c.cache_path : undefined) ??+ undefined,);- // The file is gone, so drop its pin too.- if (isPinned) togglePinned(c.repo_id, variant.quant);+ if (isChatGgufTask(c.task)) {+ await reconcileGgufPinsAfterDelete(c.repo_id, hfToken || undefined);+ } else if (isPinned) {+ togglePinned(c.repo_id, variant.quant);+ }prunePinnedQuantValidation(c.repo_id, variant.quant);refreshCachedLists();},@@ -6074,8 +6118,12 @@ export function HubModelPicker({hfToken || undefined,c.cache_path || undefined,);- // Every quant goes with the repo, so every quant pin goes too.- unpinRepo(c.repo_id);+ if (isChatGgufTask(c.task)) {+ // Another remembered folder may still hold a pinned quant.+ await reconcileGgufPinsAfterDelete(c.repo_id, hfToken || undefined);+ } else {+ unpinRepo(c.repo_id);+ }},onDeleted: refreshCachedLists,}}@@ -6111,12 +6159,13 @@ export function HubModelPicker({onUpdate: (quant, expectedBytes) =>updateGgufVariant(c.repo_id, quant, expectedBytes),updateDisabled: loadedModelId === c.repo_id,- onDelete: async (quant) => {+ onDelete: async (quant, cachePath) => {await deleteCachedModel(c.repo_id,quant,hfToken || undefined,- c.cache_path || undefined,+ cachePath ??+ (mediaPageForTask(c.task) ? c.cache_path || undefined : undefined),);prunePinnedQuantValidation(c.repo_id, quant);refreshCachedLists();@@ -7569,11 +7618,12 @@ export function HubModelPicker({systemRamGb={expanderRamGb || undefined}budgetKnown={expanderBudgetGpu.budgetKnown}variantActions={{- onDelete: async (quant) => {+ onDelete: async (quant, cachePath) => {await deleteCachedModel(id,quant,hfToken || undefined,+ cachePath ?? undefined,);prunePinnedQuantValidation(id, quant);refreshCachedLists();@@ -7699,11 +7749,12 @@ export function HubModelPicker({systemRamGb={expanderRamGb || undefined}budgetKnown={expanderBudgetGpu.budgetKnown}variantActions={{- onDelete: async (quant) => {+ onDelete: async (quant, cachePath) => {await deleteCachedModel(id,quant,hfToken || undefined,+ cachePath ?? undefined,);prunePinnedQuantValidation(id, quant);refreshCachedLists();@@ -7823,11 +7874,12 @@ export function HubModelPicker({systemRamGb={expanderRamGb || undefined}budgetKnown={expanderBudgetGpu.budgetKnown}variantActions={{- onDelete: async (quant) => {+ onDelete: async (quant, cachePath) => {await deleteCachedModel(id,quant,hfToken || undefined,+ cachePath ?? undefined,);prunePinnedQuantValidation(id, quant);refreshCachedLists();diff --git a/studio/frontend/src/features/model-picker/components/model-selector/reconcile-gguf-pins.ts b/studio/frontend/src/features/model-picker/components/model-selector/reconcile-gguf-pins.tsnew file mode 100644index 00000000000..cdbc88a6768--- /dev/null+++ b/studio/frontend/src/features/model-picker/components/model-selector/reconcile-gguf-pins.ts@@ -0,0 +1,92 @@+// 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 { listGgufVariants } from "@/features/chat/api/chat-api";+import {+ fetchCachedGgufInventory,+ fetchCachedModelsInventory,+} from "@/features/hub/inventory/api";+import { pinnedQuantEntries, usePinnedModelsStore } from "./pinned-models";+import {+ ggufVariantsMatchForPicker,+ modelIdsMatchForPicker,+} from "./row-identity";++export function isChatGgufTask(task: string | null | undefined): boolean {+ return !task || task === "text-generation" || task === "image-text-to-text";+}++/** Whether the cache still holds a runnable copy of *repoId* that is not a GGUF quant.+ * A repo can cache its GGUF quants and a safetensors copy side by side, and the bare pin+ * covers that whole repo, so deleting the last quant must not drop it while such a copy+ * survives. The models listing is the only source for those copies: it reports their own+ * readiness, and an unconfirmed scan is not evidence either way. */+async function hasRunnableNonGgufCopy(+ repoId: string,+ hfToken?: string,+): Promise<boolean> {+ const models = await fetchCachedModelsInventory(hfToken);+ if (models.scan_confirmed === false) return true;+ return models.cached.some(+ (copy) =>+ // An adapter holds no base weights, so /load has to fetch them from the Hub: it is not+ // a runnable copy this pin could keep pointing at.+ copy.model_format !== "adapter" &&+ copy.capabilities?.can_chat !== false &&+ modelIdsMatchForPicker(copy.repo_id, repoId),+ );+}++export async function reconcileGgufPinsAfterDelete(+ repoId: string,+ hfToken?: string,+): Promise<void> {+ try {+ const inventory = await fetchCachedGgufInventory(hfToken);+ if (inventory.scan_confirmed === false) return;+ const copies = inventory.cached.filter((copy) =>+ modelIdsMatchForPicker(copy.repo_id, repoId),+ );+ const variants =+ copies.length > 0+ ? (+ await listGgufVariants(repoId, hfToken, {+ preferLocalCache: true,+ })+ ).variants+ : [];+ // An anonymous Hub listing cannot disprove the complete copy found on disk.+ if (+ !hfToken &&+ copies.some((copy) => !copy.partial) &&+ !variants.some((variant) => variant.downloaded || variant.partial)+ )+ return;+ const state = usePinnedModelsStore.getState();+ // The bare pin stands for the repo as a whole -- its non-GGUF copies included -- so it+ // goes only when no loadable copy of any format is left.+ if (+ !variants.some((v) => v.downloaded && !v.partial) &&+ !(await hasRunnableNonGgufCopy(repoId, hfToken))+ ) {+ for (const pin of state.pinned) {+ if (modelIdsMatchForPicker(pin, repoId)) state.togglePinned(pin);+ }+ }+ for (const pin of pinnedQuantEntries(state.pinned)) {+ if (+ modelIdsMatchForPicker(pin.repoId, repoId) &&+ !variants.some(+ (v) =>+ ggufVariantsMatchForPicker(v.quant, pin.quant) &&+ v.downloaded &&+ !v.partial,+ )+ ) {+ state.togglePinned(pin.repoId, pin.quant);+ }+ }+ } catch {+ // An unavailable scan is not evidence that the last downloaded copy is gone.+ }+}diff --git a/studio/frontend/src/features/model-picker/components/model-selector/sole-quant-cache.ts b/studio/frontend/src/features/model-picker/components/model-selector/sole-quant-cache.tsindex d3d533d8798..5d666c5228e 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/sole-quant-cache.ts+++ b/studio/frontend/src/features/model-picker/components/model-selector/sole-quant-cache.ts@@ -10,6 +10,7 @@export interface SoleQuantTarget {repoId: string;localSource: string | null;+ includeCacheLocations?: boolean;fingerprint: string;key: string;}diff --git a/studio/frontend/src/features/model-picker/components/model-selector/variant-presentation.ts b/studio/frontend/src/features/model-picker/components/model-selector/variant-presentation.tsindex 596e5c79f47..dd81093a3bd 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/variant-presentation.ts+++ b/studio/frontend/src/features/model-picker/components/model-selector/variant-presentation.ts@@ -180,3 +180,11 @@ export function preferredGgufVariantByGroup<T extends PresentableGgufVariant>(}),);}++/** Missing on older responses; null means this source's metadata is unknown. */+export function ggufVariantContextLength(+ variant: { context_length?: number | null },+ fallback: number | null,+): number | null {+ return variant.context_length === undefined ? fallback : variant.context_length;+}diff --git a/studio/frontend/tests/auto-load-target-key.test.ts b/studio/frontend/tests/auto-load-target-key.test.tsindex 95241416d2c..c7c8541d387 100644--- a/studio/frontend/tests/auto-load-target-key.test.ts+++ b/studio/frontend/tests/auto-load-target-key.test.ts@@ -57,3 +57,53 @@ test("a decomposed filename is the same candidate as its composed form", () => {test("repo ids still fold case", () => {assert.ok(sameKey("unsloth/Qwen3-0.6B-GGUF", "UNSLOTH/qwen3-0.6b-gguf"));});+++test("startup remembers an inactive quant through the logical chat inventory target", async () => {+ const declarations = ["buildAutoLoadSources", "resolveAutoLoadCandidate"].map((name) => {+ const begin = source.indexOf(`function ${name}(`);+ assert.ok(begin >= 0);+ const asyncPrefix = name === "resolveAutoLoadCandidate" ? "async " : "";+ return asyncPrefix + source.slice(begin, source.indexOf("\n}", begin) + 2);+ }).join("\n");+ const compile = new Function(+ "listGgufVariants", "isGgufLocalRow", "isAutoLoadableGgufVariant",+ ts.transpileModule(declarations, {+ compilerOptions: { target: ts.ScriptTarget.ES2020 },+ }).outputText + "; return { buildAutoLoadSources, resolveAutoLoadCandidate };",+ );+ const repoId = "Org/Model";+ const cachePath = "/cache/default/models--Org--Model";+ const scopes: (string | undefined)[] = [];+ const helpers = compile(+ async (_id: string, _token: undefined, options: { localPath?: string }) => {+ scopes.push(options.localPath);+ const quants = options.localPath === repoId ? ["Q6_K", "Q8_0"] : ["Q6_K"];+ return { variants: quants.map((quant, i) => ({+ quant, downloaded: true, size_bytes: 100 + i,+ })) };+ },+ () => true,+ () => true,+ );+ const rows = [{ repo_id: repoId, load_id: repoId, cache_path: cachePath, size_bytes: 300 }];+ const [logical] = helpers.buildAutoLoadSources(rows, [], [], 8192);+ const candidate = await helpers.resolveAutoLoadCandidate(logical, "Q8_0", () => false);+ assert.equal(candidate.ggufVariant, "Q8_0");+ assert.equal(candidate.loadId, repoId);+ assert.deepEqual(scopes, [repoId]);++ const snapshot = cachePath + "/snapshots/revision";+ const [explicit] = helpers.buildAutoLoadSources([{ ...rows[0], load_id: snapshot }], [], [], 8192);+ await explicit.listVariants();+ assert.equal(scopes.at(-1), snapshot);+ const [legacy] = helpers.buildAutoLoadSources([{ ...rows[0], load_id: undefined }], [], [], 8192);+ await legacy.listVariants();+ assert.equal(scopes.at(-1), cachePath);+ const localPath = "/models/local";+ const [local] = helpers.buildAutoLoadSources([], [], [{+ id: localPath, path: localPath, capabilities: { requires_variant: true },+ }], 8192);+ await local.listVariants();+ assert.equal(scopes.at(-1), localPath);+});diff --git a/studio/frontend/tests/gguf-delete-cache-reference.test.ts b/studio/frontend/tests/gguf-delete-cache-reference.test.tsnew file mode 100644index 00000000000..7a7d624d05f--- /dev/null+++ b/studio/frontend/tests/gguf-delete-cache-reference.test.ts@@ -0,0 +1,160 @@+// 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 test from "node:test";+import ts from "typescript";++function readSource(path: string) {+ const text = readFileSync(new URL(path, import.meta.url), "utf8");+ return { text, source: ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX) };+}++const card = readSource("../src/features/hub/catalog/gguf-download-card.tsx");+const inventoryApi = readSource("../src/features/hub/inventory/api.ts");+const impact = readSource("../src/features/hub/catalog/delete-impact.tsx");+const pickers = readSource(+ "../src/features/model-picker/components/model-selector/pickers.tsx",+);++test("the delete action forwards the redacted cache reference first", () => {+ // Redaction nulls `cache_path` and answers with `cache_ref`; a delete that reads only the+ // path sends nothing and the server reselects whichever duplicate ranks first.+ const deleteCall = card.text.slice(card.text.indexOf("await deleteCachedModel("));+ const args = deleteCall.slice(0, deleteCall.indexOf(");"));+ const referenceAt = args.indexOf("deleteTargetVariant?.cache_ref");+ const pathAt = args.indexOf("deleteTargetVariant?.cache_path");+ assert.ok(referenceAt > -1, "the delete call must read the row's cache_ref");+ assert.ok(pathAt > -1, "the path remains the fallback");+ assert.ok(referenceAt < pathAt, "cache_ref is preferred over the cleared cache_path");+ assert.match(args, /cachePath\s*\?\?/, "the card-level cachePath is still the last fallback");+});++test("the variant model declares cache_ref, so the reference survives parsing", () => {+ const declaration = inventoryApi.source.statements.find(+ (node): node is ts.InterfaceDeclaration =>+ ts.isInterfaceDeclaration(node) && node.name.text === "GgufVariantDetail",+ );+ assert.ok(declaration, "GgufVariantDetail must exist");+ const fields = declaration.members+ .filter(ts.isPropertySignature)+ .map((member) => member.name.getText(inventoryApi.source));+ assert.ok(fields.includes("cache_ref"), `cache_ref missing from: ${fields.join(", ")}`);+});++test("a logical quant delete carries the copy its own row was listed in", () => {+ // The server re-resolves a quant-level delete that carries no copy, and that resolution+ // cannot see the scoped companion readiness the online listing ranked duplicates by, so the+ // row's own cache path is the only thing that keeps the delete on the advertised copy.+ const expanderCall = pickers.text.match(+ /await onDeleteVariant\(v\.quant, v\.cache_ref \?\? v\.cache_path\)/,+ );+ assert.ok(expanderCall, "the expander row must hand its listed copy to the delete");+ const impact = pickers.text.match(+ /impact: \{\s*repoId,\s*variant: v\.quant,\s*cachePath: v\.cache_ref \?\? v\.cache_path,\s*\}/,+ );+ assert.ok(impact, "the confirm preview must measure the same copy the delete removes");++ const pinnedCopy = pickers.text.match(+ /const pinnedCopyPath = downloadedPinnedQuantPaths\.get\(/,+ );+ assert.ok(pinnedCopy, "the pinned row must look up the copy its validation resolved");+ assert.match(+ pickers.text,+ /pinnedCopyPath \?\? undefined,/,+ "the pinned delete must forward that copy",+ );+ assert.match(+ pickers.text,+ /cachePath \?\?\n\s*\(mediaPageForTask\(c\.task\) \? c\.cache_path \|\| undefined : undefined\)/,+ "the On Device expander must prefer the row's copy and keep the media fallback",+ );+});++test("the delete preview accepts the copy so it measures that one", () => {+ const fn = inventoryApi.text.slice(+ inventoryApi.text.indexOf("export async function fetchDeleteImpact"),+ );+ const body = fn.slice(0, fn.indexOf("\n}"));+ assert.match(body, /cachePath\?: string \| null,/, "the preview must accept a copy");+ assert.ok(+ body.includes("cachePath ? { cache_path: cachePath } : {}"),+ "the preview must send the copy it was given",+ );+ assert.ok(+ impact.text.includes("cachePath?: string | null,") &&+ impact.text.includes("fetchDeleteImpact(repoId, variant ?? undefined, cachePath ?? undefined)"),+ "the hook must forward the copy and refetch when it changes",+ );+ const menu = readSource("../src/features/model-picker/components/model-selector/model-row-menu.tsx");+ assert.match(+ menu.text,+ /impact\?: \{ repoId: string; variant\?: string \| null; cachePath\?: string \| null \}/,+ "the row menu must accept the copy for its preview",+ );+ assert.match(+ menu.text,+ /del\?\.impact\?\.cachePath,/,+ "the row menu must pass the copy to the preview hook",+ );+});+++test("a redacted listing keeps the copy on the picker rows and their previews", () => {+ // Redaction nulls `cache_path` and answers with `cache_ref`. A row that reads only the path+ // sends nothing, and the server then ranks duplicates itself, which cannot see the scoped+ // readiness the listing ranked them by.+ const chatTypes = readSource("../src/features/chat/types/api.ts");+ const declaration = chatTypes.source.statements.find(+ (node): node is ts.InterfaceDeclaration =>+ ts.isInterfaceDeclaration(node) && node.name.text === "GgufVariantDetail",+ );+ assert.ok(declaration, "the chat GgufVariantDetail must exist");+ const fields = declaration.members+ .filter(ts.isPropertySignature)+ .map((member) => member.name.getText(chatTypes.source));+ assert.ok(+ fields.includes("cache_ref"),+ `the chat variant model must declare cache_ref: ${fields.join(", ")}`,+ );++ // The picker rows: expander, sole quant, and the pinned copy the validation listing resolved.+ assert.match(+ pickers.text,+ /await onDeleteVariant\(v\.quant, v\.cache_ref \?\? v\.cache_path\)/,+ "the expander delete must prefer the reference",+ );+ assert.match(+ pickers.text,+ /cachePath: v\.cache_ref \?\? v\.cache_path,/,+ "the expander preview must measure the same copy",+ );+ assert.match(+ pickers.text,+ /pinKey\(repoId, variant\.quant\),\s*\n\s*variant\.cache_ref \?\? variant\.cache_path \?\? null,/,+ "the pinned copy lookup must prefer the reference",+ );+ assert.match(+ pickers.text,+ /variant\.cache_ref \?\?\n\s*variant\.cache_path \?\?\n\s*\(mediaPageForTask\(c\.task\) \? c\.cache_path : null\)/,+ "the On Device row preview must prefer the reference and keep the media fallback",+ );+ assert.match(+ pickers.text,+ /variant\.cache_ref \?\?\n\s*variant\.cache_path \?\?\n\s*\(mediaPageForTask\(c\.task\) \? c\.cache_path : undefined\)/,+ "the On Device delete must prefer the reference and keep the media fallback",+ );+});++test("the disk card previews the copy its delete sends", () => {+ // The delete already preferred the reference; the preview above it did not, so an API-key+ // caller was shown another duplicate's reclaimed bytes.+ const preview = card.text.slice(card.text.indexOf("const deleteImpact = useDeleteImpact("));+ const args = preview.slice(0, preview.indexOf(");"));+ assert.match(+ args,+ /deleteTargetVariant\?\.cache_ref \?\? deleteTargetVariant\?\.cache_path \?\? cachePath \?\? undefined/,+ "the preview must receive the same reference the delete sends",+ );+});diff --git a/studio/frontend/tests/gguf-delete-pin-scope.test.ts b/studio/frontend/tests/gguf-delete-pin-scope.test.tsnew file mode 100644index 00000000000..3c2a7909a0d--- /dev/null+++ b/studio/frontend/tests/gguf-delete-pin-scope.test.ts@@ -0,0 +1,98 @@+// 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 test from "node:test";+import ts from "typescript";+import { pinKey, pinnedQuantEntries } from "../src/features/model-picker/components/model-selector/pinned-models.ts";+import { ggufVariantsMatchForPicker, modelIdsMatchForPicker } from "../src/features/model-picker/components/model-selector/row-identity.ts";++function readSource(path: string) {+ const text = readFileSync(new URL(path, import.meta.url), "utf8");+ return ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+}++function compile(expression: string, context: Record<string, unknown>) {+ const js = ts.transpileModule(`const callback = ${expression};`, {+ compilerOptions: { target: ts.ScriptTarget.ES2020 },+ }).outputText;+ return new Function(...Object.keys(context), js + "; return callback;")(...Object.values(context));+}++const helper = readSource("../src/features/model-picker/components/model-selector/reconcile-gguf-pins.ts");+function helperFunction(name: string) {+ const declaration = helper.statements.find(+ (node) => ts.isFunctionDeclaration(node) && node.name?.text === name,+ );+ assert.ok(declaration, name);+ return declaration.getText(helper).replace("export ", "");+}+const isChatGgufTask = compile(helperFunction("isChatGgufTask"), {});+const callbacks: { name: string; body: string; wholeRepo: boolean }[] = [];+for (const path of [+ "../src/features/model-picker/components/model-selector/pickers.tsx",+ "../src/features/hub/catalog/models-catalog-rows.tsx",+]) {+ const source = readSource(path);+ function visit(node: ts.Node) {+ if (ts.isPropertyAssignment(node) && node.name.getText(source) === "onConfirm") {+ const body = node.initializer.getText(source);+ if (body.includes("reconcileGgufPinsAfterDelete")) {+ const name = path.includes("models-catalog") ? "catalog repo"+ : body.includes("onDeleteVariant(v.quant") ? "expander quant"+ : body.includes("entry.repoId") ? "pinned quant"+ : body.includes("variant.quant") ? "sole quant" : "picker repo";+ callbacks.push({ name, body, wholeRepo: name.endsWith("repo") });+ }+ }+ ts.forEachChild(node, visit);+ }+ visit(source);+}+assert.equal(callbacks.length, 5);++for (const task of [null, "text-generation", "image-text-to-text", "text-to-image", "text-to-video", "image-to-video", "text-to-speech", "automatic-speech-recognition"]) {+ const chat = task === null || task === "text-generation" || task === "image-text-to-text";+ for (const { name, body, wholeRepo } of callbacks) {+ test(`${name} keeps ${task ?? "unknown chat"} deletion pin scope`, async () => {+ const repoId = "Org/Model";+ const deleted = "Q6_K";+ const surviving = "Q8_0";+ let pinned = [repoId, pinKey(repoId, deleted), pinKey(repoId, surviving)];+ const togglePinned = (repo: string, quant?: string) => {+ const key = pinKey(repo, quant);+ pinned = pinned.includes(key) ? pinned.filter((item) => item !== key) : [...pinned, key];+ };+ const unpinRepo = () => { pinned = []; };+ const usePinnedModelsStore = { getState: () => ({ pinned, togglePinned, unpinRepo }) };+ const reconcile = compile(helperFunction("reconcileGgufPinsAfterDelete"), {+ fetchCachedGgufInventory: async () => ({ cached: [{ repo_id: repoId }], scan_confirmed: true }),+ // A media quant survives only in the inactive copy. Whole-row controls+ // also retain a second copy, where media previously cleared all repo pins.+ listGgufVariants: async () => ({ variants: chat || wholeRepo ? [{ quant: surviving, downloaded: true, partial: false }] : [] }),+ usePinnedModelsStore, pinnedQuantEntries, modelIdsMatchForPicker, ggufVariantsMatchForPicker,+ });+ let reconciliations = 0;+ const callback = compile(body, {+ repoId, hfToken: "hf_fixture_token", pipelineTag: task,+ useHfTokenStore: { getState: () => ({ token: "hf_fixture_token" }) },+ v: { quant: deleted }, entry: { repoId, quant: deleted },+ c: { repo_id: repoId, task, cache_path: "/inactive/cache" },+ variant: { quant: deleted }, isPinned: true, pinnedKeys: [...pinned],+ pinnedCopyPath: "/inactive/cache",+ row: { kind: "cache", isGguf: true, pipelineTag: task, cachePath: "/inactive/cache" },+ deletableRepoId: repoId, isDataset: false,+ diffusionTaskById: new Map([[repoId.toLowerCase(), task]]),+ mediaPageForTask: (value: string | null) => value && !["text-generation", "image-text-to-text"].includes(value) ? "images" : null,+ isChatGgufTask, usePinnedModelsStore, pinKey, togglePinned, togglePinnedQuant: togglePinned, unpinRepo,+ reconcileGgufPinsAfterDelete: async (...args: unknown[]) => { reconciliations++; assert.equal(args[1], "hf_fixture_token"); await reconcile(...args); },+ onDeleteVariant: async () => {}, deleteCachedModel: async () => {}, deleteCachedDataset: async () => {},+ refreshCachedLists: () => {}, prunePinnedQuantValidation: () => {}, setRefreshKey: () => {},+ });+ await callback();+ assert.deepEqual(pinned, !chat && wholeRepo ? [] : [repoId, pinKey(repoId, surviving)]);+ assert.equal(reconciliations, chat ? 1 : 0);+ });+ }+}diff --git a/studio/frontend/tests/gguf-source-pins.test.ts b/studio/frontend/tests/gguf-source-pins.test.tsnew file mode 100644index 00000000000..38b47cd9c78--- /dev/null+++ b/studio/frontend/tests/gguf-source-pins.test.ts@@ -0,0 +1,150 @@+// 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 test from "node:test";+import ts from "typescript";+import {+ pinKey,+ pinnedQuantEntries,+} from "../src/features/model-picker/components/model-selector/pinned-models.ts";+import {+ ggufVariantsMatchForPicker,+ modelIdsMatchForPicker,+} from "../src/features/model-picker/components/model-selector/row-identity.ts";++const source = readFileSync(+ new URL(+ "../src/features/model-picker/components/model-selector/reconcile-gguf-pins.ts",+ import.meta.url,+ ),+ "utf8",+);+const declaration = source+ // Both functions travel together: the reconciler calls the non-GGUF survivor probe.+ .slice(source.indexOf("async function hasRunnableNonGgufCopy"))+ .replace("export ", "");+const compile = new Function(+ "listCachedGguf",+ "fetchCachedGgufInventory",+ "fetchCachedModelsInventory",+ "listGgufVariants",+ "pinnedQuantEntries",+ "usePinnedModelsStore",+ "modelIdsMatchForPicker",+ "ggufVariantsMatchForPicker",+ ts.transpileModule(declaration, {+ compilerOptions: { target: ts.ScriptTarget.ES2020 },+ }).outputText + "; return reconcileGgufPinsAfterDelete;",+);++for (const requested of ["Org/Model", "org/model"]) {+ for (const remaining of [+ "anonymous",+ "anonymous-partial-inventory",+ "duplicate",+ "absent",+ "partial",+ "unavailable",+ "unconfirmed-absent",+ "unconfirmed-partial",+ "lowercase-quant",+ "other-quant",+ "legacy-confirmation",+ "non-gguf-survivor",+ ]) {+ test(`GGUF pins after deleting ${requested}: ${remaining}`, async () => {+ const original = ["Org/Model", pinKey("Org/Model", "Q8_0")];+ let pinned = [...original];+ let variantCalls = 0;+ const inventory = async () => {+ if (remaining === "unavailable") throw new Error("scan unavailable");+ return {+ cached: remaining.endsWith("absent")+ ? []+ : [+ {+ repo_id: "org/model",+ partial:+ remaining.endsWith("partial") ||+ remaining === "anonymous-partial-inventory",+ },+ ],+ scan_confirmed:+ remaining === "legacy-confirmation"+ ? undefined+ : !remaining.startsWith("unconfirmed"),+ };+ };+ const modelsInventory = async () => ({+ cached:+ remaining === "non-gguf-survivor"+ ? [+ {+ repo_id: "org/model",+ model_format: "safetensors",+ partial: false,+ capabilities: { can_chat: true },+ },+ ]+ : [],+ scan_confirmed: true,+ });+ const run = compile(+ // The bare pin must survive the last quant when a non-GGUF copy of the same+ // repo is still cached and runnable, and fall only when none is left.+ async () => (await inventory()).cached,+ inventory,+ modelsInventory,+ async () => {+ variantCalls += 1;+ return {+ variants: [+ {+ quant:+ remaining === "lowercase-quant"+ ? "q8_0"+ : remaining === "other-quant"+ ? "Q6_K"+ : "Q8_0",+ downloaded:+ !remaining.startsWith("anonymous") &&+ !remaining.endsWith("partial") &&+ // The last quant is what was just deleted; only a non-GGUF copy is left.+ remaining !== "non-gguf-survivor",+ },+ ],+ };+ },+ pinnedQuantEntries,+ {+ getState: () => ({+ pinned,+ togglePinned: (repo: string, quant?: string) => {+ pinned = pinned.filter((p) => p !== pinKey(repo, quant));+ },+ }),+ },+ modelIdsMatchForPicker,+ ggufVariantsMatchForPicker,+ );+ // The survivor case carries a token: an anonymous listing stops at the guard that+ // trusts the complete copy on disk, before any pin is reconsidered.+ await run(+ requested,+ remaining === "non-gguf-survivor" ? "hf_fixture_token" : undefined,+ );+ const expected =+ remaining === "absent" ||+ remaining === "partial" ||+ remaining === "anonymous-partial-inventory"+ ? []+ : remaining === "other-quant" || remaining === "non-gguf-survivor"+ ? ["Org/Model"]+ : original;+ assert.deepEqual(pinned, expected);+ if (remaining.startsWith("unconfirmed")) assert.equal(variantCalls, 0);+ });+ }+}diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.pyindex c3ed88477ab..2deb8906b03 100644--- a/tests/studio/test_model_picker_contracts.py+++ b/tests/studio/test_model_picker_contracts.py@@ -665,7 +665,7 @@ def test_variant_expander_refreshes_after_delete():shown as downloaded and clickable and tries to reload the removed file."""src = _read("features/model-picker/components/model-selector/pickers.tsx")del_confirm = re.search(- r"await onDeleteVariant\(v\.quant\);.*?setRefreshKey\(\(key\) => key \+ 1\)",+ r"await onDeleteVariant\(v\.quant, v\.cache_ref \?\? v\.cache_path\);.*?setRefreshKey\(\(key\) => key \+ 1\)",src,re.S,)@@ -865,15 +865,16 @@ def test_pinned_validation_uses_cached_local_variant_listing():def test_chat_autoload_scopes_variant_lookup_to_cached_repo_path():- """Autoload must probe the exact cache row it will load, including rows- retained from a previously selected Hugging Face cache."""+ """Autoload probes its load ID: a logical chat GGUF repo spans remembered roots,+ while an explicit local row still scans only its own directory."""src = _read("features/chat/api/chat-adapter.ts")- # Both cache-backed sources scan the exact path they will load from, not the- # bare repo id.+ # Logical chat repositories use the same load_id for listing and loading; explicit+ # local rows remain scoped to the physical path they name.sources = src.split("function buildAutoLoadSources", 1)[1]sources = sources.split("function isRememberedSource", 1)[0]assert sources.count("preferLocalCache: true") == 2- assert "localPath: repo.cache_path" in sources+ assert "localPath: repo.load_id || repo.cache_path" in sources+ assert "loadId: repo.load_id || repo.repo_id" in sourcesassert "localPath: row.path" in sources# #7767 moved the query building out of chat-api into its own module, so the listing