Skip to content

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

Studio: show cache sizes and clear individual Hugging Face model copies (#15488)

Daniel Hanb489a92ed9b6
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index 2508cb4df14..dd44c2261bc 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -77,7 +77,7 @@ from utils.upload_limits import (
upload_limit_bytes,
upload_limit_label,
)
-from utils.cache_inventory import CACHE_KEYS, cache_inventory, purge_caches
+from utils.cache_inventory import CACHE_KEYS, cache_inventory, cache_breakdown, purge_caches
from utils.xet_notice_settings import reserve_xet_notice
from utils.chat_preferences_settings import (
get_show_model_disclaimer,
@@ -903,6 +903,10 @@ class CacheEntryResponse(BaseModel):
# Clearing costs a re-download, so it is never folded into a clear-everything action.
opt_in: bool
paths: list[str]
+ measured_paths: list[str] = Field(default_factory = list)
+ clear_size_bytes: Optional[int] = None
+ clear_entry_count: Optional[int] = None
+ system_disk_bytes: Optional[int] = None
size_bytes: int
entry_count: int
present: bool
@@ -1396,6 +1400,19 @@ async def get_caches(
return CacheInventoryResponse(**inventory)
+@_owner_settings_router.get("/caches/{key}/breakdown")
+async def get_cache_breakdown(
+ key: str,
+ current_subject: str = Depends(get_current_subject),
+ via_api_key: bool = Depends(authenticated_via_api_key),
+):
+ require_ui_session(via_api_key)
+ try:
+ return await asyncio.to_thread(cache_breakdown, key)
+ except ValueError as exc:
+ raise HTTPException(status_code = 400, detail = str(exc)) from exc
+
+
@_owner_settings_router.post("/caches/purge", response_model = CachePurgeResponse)
async def purge_caches_endpoint(
payload: CachePurgePayload,
diff --git a/studio/backend/tests/test_api_cache_routes.py b/studio/backend/tests/test_api_cache_routes.py
index ef56e9de976..a75d5cdca47 100644
--- a/studio/backend/tests/test_api_cache_routes.py
+++ b/studio/backend/tests/test_api_cache_routes.py
@@ -151,3 +151,16 @@ def test_an_api_key_caller_cannot_force_a_rescan(monkeypatch):
assert asked == []
assert remote.get("/api/settings/caches").status_code == 200
assert asked == [False]
+
+
+def test_hf_breakdown_requires_ui_session_and_is_only_requested_on_demand(monkeypatch, client):
+ calls = []
+ monkeypatch.setattr(
+ settings_route, "cache_breakdown", lambda key: calls.append(key) or {"entries": []}
+ )
+ response = client.get("/api/settings/caches/hf_hub/breakdown")
+ assert response.status_code == 200
+ assert calls == ["hf_hub"]
+ client.app.dependency_overrides[authenticated_via_api_key] = lambda: True
+ assert client.get("/api/settings/caches/hf_hub/breakdown").status_code == 403
+ assert calls == ["hf_hub"]
diff --git a/studio/backend/tests/test_cache_inventory.py b/studio/backend/tests/test_cache_inventory.py
index 267936bc91a..994ebb96116 100644
--- a/studio/backend/tests/test_cache_inventory.py
+++ b/studio/backend/tests/test_cache_inventory.py
@@ -1705,3 +1705,274 @@ def test_a_registry_created_during_a_purge_is_born_reserved(monkeypatch):
assert fresh.claim_repository_owner("late/set", object()) == (False, "deleting")
finally:
dataset_downloads.end_cache_purge()
+
+
+def test_hf_occupancy_is_measured_even_when_documents_clear_is_forbidden(
+ tmp_path, monkeypatch, isolated_caches
+):
+ hub = isolated_caches / "hub"
+ _write(hub / "models--org--model" / "blobs" / "weights", "x" * 123)
+ monkeypatch.setattr(cache_inventory, "protected_trees", lambda: {isolated_caches})
+ entry = describe_cache(definition_for("hf_hub"))
+ assert entry["size_bytes"] == 123
+ assert entry["purgeable"] is False
+ assert entry["clear_size_bytes"] == 0
+ assert "protected folder" in entry["blocked_reason"]
+ assert (hub / "models--org--model" / "blobs" / "weights").exists()
+
+
+def test_hf_history_counts_storage_without_widening_clear(tmp_path, monkeypatch, isolated_caches):
+ from utils import hf_cache_settings
+
+ active = isolated_caches / "hub"
+ previous = tmp_path / "previous" / "hub"
+ mine = _write(active / "models--org--active" / "blobs" / "weight", "a" * 15)
+ kept = _write(previous / "models--org--old" / "blobs" / "weight", "b" * 27)
+ monkeypatch.setattr(
+ hf_cache_settings, "known_hf_hub_caches", lambda: [active, previous, active]
+ )
+ entry = describe_cache(definition_for("hf_hub"))
+ assert entry["size_bytes"] == 42
+ assert entry["clear_size_bytes"] == 15
+ assert entry["paths"] == [str(active)]
+ assert len(entry["measured_paths"]) == 2
+ purge_caches(["hf_hub"])
+ assert not mine.exists()
+ assert kept.exists()
+
+
+def test_hf_breakdown_is_on_demand_and_includes_incomplete_blobs(
+ tmp_path, monkeypatch, isolated_caches
+):
+ hub = isolated_caches / "hub"
+ _write(hub / "models--org--model" / "blobs" / "weight.incomplete", "a" * 120)
+ _write(hub / "datasets--org--data" / "snapshots" / "revision" / "data.json", "b" * 25)
+ called = []
+ original = cache_inventory.cache_breakdown
+ monkeypatch.setattr(
+ cache_inventory, "cache_breakdown", lambda key: (called.append(key), original(key))[1]
+ )
+ describe_cache(definition_for("hf_hub"))
+ assert called == []
+ entries = cache_inventory.cache_breakdown("hf_hub")["entries"]
+ assert [entry["size_bytes"] for entry in entries] == [120, 25]
+ assert entries[0]["name"] == "models--org--model"
+ with pytest.raises(ValueError):
+ cache_inventory.cache_breakdown("../outside")
+
+
+def test_hf_measurement_does_not_walk_a_protected_root(tmp_path, monkeypatch, isolated_caches):
+ from utils import hf_cache_settings
+
+ monkeypatch.setattr(hf_cache_settings, "known_hf_hub_caches", lambda: [tmp_path])
+ monkeypatch.setattr(cache_inventory, "protected_paths", lambda: {tmp_path})
+ walked = []
+ monkeypatch.setattr(
+ cache_inventory, "_measure_root", lambda root, **kwargs: (walked.append(root) or 0, 0)
+ )
+ describe_cache(definition_for("hf_hub"))
+ assert tmp_path not in walked
+
+
+def test_hf_shared_file_occupies_space_even_when_clear_cannot_reclaim_it(tmp_path, isolated_caches):
+ cached = _write(isolated_caches / "hub" / "models--org--shared" / "blobs" / "weight", "w" * 800)
+ os.link(cached, tmp_path / "installed-weight")
+
+ entry = describe_cache(definition_for("hf_hub"))
+ assert entry["size_bytes"] == 800
+ assert entry["clear_size_bytes"] == 0
+ assert cache_inventory.cache_breakdown("hf_hub")["entries"][0]["size_bytes"] == 800
+
+
+def test_hf_history_deduplicates_shared_inodes_and_walks_each_root_once(
+ tmp_path, monkeypatch, isolated_caches
+):
+ from utils import hf_cache_settings
+
+ active = isolated_caches / "hub"
+ previous = tmp_path / "old" / "hub"
+ shared = _write(active / "models--org--shared" / "blobs" / "weight", "w" * 800)
+ previous_blob = previous / "models--org--copy" / "blobs" / "weight"
+ previous_blob.parent.mkdir(parents = True)
+ os.link(shared, previous_blob)
+ _write(active / "models--org--unique" / "blobs" / "weight", "u" * 25)
+ monkeypatch.setattr(hf_cache_settings, "known_hf_hub_caches", lambda: [active, previous])
+ walked = []
+ measure = cache_inventory._measure_root
+ monkeypatch.setattr(
+ cache_inventory,
+ "_measure_root",
+ lambda root, **kwargs: (walked.append(root), measure(root, **kwargs))[1],
+ )
+
+ entry = describe_cache(definition_for("hf_hub"))
+ assert entry["size_bytes"] == 825
+ assert entry["clear_size_bytes"] == 25
+ assert walked.count(active) == walked.count(previous) == 1
+ breakdown = cache_inventory.cache_breakdown("hf_hub")["entries"]
+ assert sum(row["size_bytes"] for row in breakdown) == 825
+ purge_caches(["hf_hub"])
+ assert previous_blob.read_text(encoding = "utf-8") == "w" * 800
+
+
+def test_empty_active_hf_cache_has_no_clearable_entries_despite_history(
+ tmp_path, monkeypatch, isolated_caches
+):
+ from utils import hf_cache_settings
+
+ previous = tmp_path / "old" / "hub"
+ _write(previous / "models--org--old" / "blobs" / "weight", "w" * 80)
+ monkeypatch.setattr(
+ hf_cache_settings, "known_hf_hub_caches", lambda: [isolated_caches / "hub", previous]
+ )
+ entry = describe_cache(definition_for("hf_hub"))
+ assert entry["size_bytes"] == 80
+ assert entry["entry_count"] == 1
+ assert entry["clear_entry_count"] == 0
+ assert entry["clear_size_bytes"] == 0
+
+
+def test_system_cache_accounting_matches_system_volume_when_studio_is_elsewhere(
+ tmp_path, monkeypatch
+):
+ from types import SimpleNamespace
+ from utils.paths import storage_roots
+
+ system = Path(os.path.abspath(os.sep))
+ studio = tmp_path / "studio-on-another-disk"
+ real_stat = Path.stat
+
+ def stat(path, *args, **kwargs):
+ if path == system:
+ return SimpleNamespace(st_dev = 1)
+ if path == studio:
+ return SimpleNamespace(st_dev = 2)
+ return real_stat(path, *args, **kwargs)
+
+ with monkeypatch.context() as patch:
+ patch.setattr(Path, "stat", stat)
+ patch.setattr(storage_roots, "studio_root", lambda: studio)
+ assert cache_inventory._system_disk_device() == 1
+
+ ledger = cache_inventory._OccupancyLedger()
+ ledger.add(SimpleNamespace(st_dev = 1, st_ino = 10, st_size = 100), system / "old-model")
+ ledger.add(SimpleNamespace(st_dev = 2, st_ino = 20, st_size = 200), studio / "new-model")
+ monkeypatch.setattr(cache_inventory, "_system_disk_device", lambda: 1)
+ monkeypatch.setattr(
+ cache_inventory.shutil,
+ "disk_usage",
+ lambda path: SimpleNamespace(total = 1000 if Path(path) == system else 2000, free = 100),
+ )
+ assert cache_inventory._system_disk_occupancy(ledger) == 100
+
+
+def test_distinct_device_ids_in_the_same_pool_still_count_as_system_storage(tmp_path, monkeypatch):
+ from types import SimpleNamespace
+
+ system = Path(os.path.abspath(os.sep))
+ ledger = cache_inventory._OccupancyLedger()
+ ledger.add(SimpleNamespace(st_dev = 1, st_ino = 10, st_size = 100), system / "cached")
+ ledger.add(SimpleNamespace(st_dev = 2, st_ino = 20, st_size = 200), tmp_path / "data" / "cached")
+ ledger.add(SimpleNamespace(st_dev = 3, st_ino = 30, st_size = 300), tmp_path / "unknown" / "cached")
+ monkeypatch.setattr(cache_inventory, "_system_disk_device", lambda: 1)
+
+ def usage(path):
+ if Path(path) == tmp_path / "unknown":
+ raise PermissionError("unreadable device")
+ return SimpleNamespace(total = 10**12, free = 10**11 - (1024 if Path(path) != system else 0))
+
+ monkeypatch.setattr(cache_inventory.shutil, "disk_usage", usage)
+ assert cache_inventory._system_disk_occupancy(ledger) == 300
+
+
+def test_hf_model_breakdown_actions_name_one_exact_known_cache_copy(
+ tmp_path, monkeypatch, isolated_caches
+):
+ from utils import hf_cache_settings
+ from hub.utils.hf_cache_state import scoped_delete_root
+
+ active = isolated_caches / "hub"
+ old = tmp_path / "previous" / "hub"
+ for root in (active, old):
+ _write(root / "models--Org--Model" / "blobs" / "weight", "model")
+ _write(active / "models--gpt2" / "blobs" / "weight", "standalone")
+ monkeypatch.setattr(hf_cache_settings, "known_hf_hub_caches", lambda: [active, old])
+
+ rows = cache_inventory.cache_breakdown("hf_hub")["entries"]
+ copies = [row for row in rows if row.get("repo_id") == "Org/Model"]
+ assert len(copies) == 2
+ assert {row["cache_path"] for row in copies} == {
+ str(root / "models--Org--Model") for root in (active, old)
+ }
+ for row in rows:
+ assert row["delete_allowed"] is True
+ assert row["repo_type"] == "model"
+ assert row["cache_path"] == row["path"]
+ assert (
+ scoped_delete_root("model", row["repo_id"], row["cache_path"])
+ == Path(row["cache_path"]).parent
+ )
+
+
+ "name",
+ [
+ ".locks",
+ "datasets--Org--Data",
+ "spaces--Org--Space",
+ "models--",
+ "models----Model",
+ "models--Org--Model--nested",
+ "models--Org--bad..name",
+ "models--Org--Model.git",
+ ],
+)
+def test_hf_breakdown_never_offers_model_actions_for_non_model_or_malformed_rows(
+ tmp_path, isolated_caches, name
+):
+ _write(isolated_caches / "hub" / name / "data", "cache")
+ row = cache_inventory.cache_breakdown("hf_hub")["entries"][0]
+ assert row["delete_allowed"] is False
+ assert "repo_id" not in row and "cache_path" not in row
+
+
+def test_hf_breakdown_does_not_turn_a_model_shaped_file_into_a_delete_action(isolated_caches):
+ _write(isolated_caches / "hub" / "models--Org--File", "not a repository directory")
+ row = cache_inventory.cache_breakdown("hf_hub")["entries"][0]
+ assert row["delete_allowed"] is False
+
+
+def test_hf_breakdown_actions_are_confined_to_hub_approved_roots(
+ tmp_path, monkeypatch, isolated_caches
+):
+ outside = tmp_path / "not-a-known-cache"
+ _write(outside / "models--Org--Model" / "blobs" / "weight", "unrelated")
+ monkeypatch.setattr(cache_inventory, "_measurement_roots", lambda _definition: [outside])
+ row = cache_inventory.cache_breakdown("hf_hub")["entries"][0]
+ assert row["delete_allowed"] is False
+ assert "cache_path" not in row
+
+
+def test_hf_breakdown_does_not_offer_model_actions_inside_xet_cache(isolated_caches):
+ _write(isolated_caches / "xet" / "models--Org--Model" / "data", "xet")
+ row = cache_inventory.cache_breakdown("hf_xet")["entries"][0]
+ assert row["delete_allowed"] is False
+
+
[email protected]("link_kind", ["symlink", "junction"])
+def test_model_action_identity_refuses_links_even_to_valid_named_directories(
+ tmp_path, monkeypatch, isolated_caches, link_kind
+):
+ from types import SimpleNamespace
+
+ root = isolated_caches / "hub"
+ directory = root / "models--Org--Model"
+ directory.mkdir()
+ entry = SimpleNamespace(
+ name = directory.name,
+ path = str(directory),
+ is_symlink = lambda: link_kind == "symlink",
+ is_dir = lambda **_kwargs: True,
+ )
+ monkeypatch.setattr(cache_inventory, "_is_junction", lambda _path: link_kind == "junction")
+ assert cache_inventory._model_cache_action(root, entry) == {"delete_allowed": False}
diff --git a/studio/backend/utils/cache_inventory.py b/studio/backend/utils/cache_inventory.py
index 9b684664b38..b9a2b1f9306 100644
--- a/studio/backend/utils/cache_inventory.py
+++ b/studio/backend/utils/cache_inventory.py
@@ -718,12 +718,44 @@ class LinkLedger:
return self._single + sum(size for size, links, met in self._multi.values() if met >= links)
-def _record_entry(entry: os.DirEntry, ledger: LinkLedger) -> None:
+class _OccupancyLedger:
+ """Disk occupancy includes shared files even when clearing cannot free them."""
+
+ def __init__(self) -> None:
+ self._seen: set[tuple] = set()
+ self.bytes = 0
+ self.by_device: dict[int, int] = {}
+ self.device_paths: dict[int, Path] = {}
+
+ def add(self, info, path: Path | str) -> None:
+ # Some network filesystems report st_ino 0: identify by path instead.
+ identity = (info.st_dev, info.st_ino) if info.st_ino else (info.st_dev, str(path))
+ if identity in self._seen:
+ return
+ self._seen.add(identity)
+ size = int(info.st_size)
+ self.bytes += size
+ self.by_device[info.st_dev] = self.by_device.get(info.st_dev, 0) + size
+ self.device_paths.setdefault(info.st_dev, Path(path).parent)
+
+
+def _record_entry(
+ entry: os.DirEntry,
+ ledger: LinkLedger,
+ occupancy: Optional[_OccupancyLedger] = None,
+) -> None:
try:
- stat = entry.stat(follow_symlinks = False)
+ # Windows DirEntry.stat zeroes st_dev, st_ino and st_nlink.
+ stat = (
+ os.stat(entry.path, follow_symlinks = False)
+ if occupancy is not None and os.name == "nt"
+ else entry.stat(follow_symlinks = False)
+ )
except OSError:
return
ledger.add(stat)
+ if occupancy is not None:
+ occupancy.add(stat, entry.path)
def _descendable(entry: os.DirEntry) -> bool:
@@ -731,7 +763,11 @@ def _descendable(entry: os.DirEntry) -> bool:
return not _is_junction(entry.path)
-def _walk_into(stack: list, ledger: LinkLedger) -> int:
+def _walk_into(
+ stack: list,
+ ledger: LinkLedger,
+ occupancy: Optional[_OccupancyLedger] = None,
+) -> int:
"""Sizes every directory on the stack and below it; returns the entries seen.
A uv or triton cache can hold millions of files, so the loop body is the whole cost: paths
@@ -755,6 +791,9 @@ def _walk_into(stack: list, ledger: LinkLedger) -> int:
if _descendable(entry):
push(entry.path)
continue
+ if occupancy is not None:
+ _record_entry(entry, ledger, occupancy)
+ continue
try:
found = entry.stat(follow_symlinks = False)
except OSError:
@@ -770,13 +809,23 @@ def _walk_into(stack: list, ledger: LinkLedger) -> int:
return count
-def _measure_tree(path: Path, ledger: LinkLedger) -> int:
+def _measure_tree(
+ path: Path,
+ ledger: LinkLedger,
+ occupancy: Optional[_OccupancyLedger] = None,
+) -> int:
"""Size is left to the ledger: a multi-link inode's cost is only known after every root is walked."""
- return _walk_into([os.fspath(path)], ledger)
+ return _walk_into([os.fspath(path)], ledger, occupancy)
-def _measure_root(root: Path, *, patterns: Optional[Iterable[str]] = None) -> tuple[int, int]:
- ledger = LinkLedger()
+def _measure_root(
+ root: Path,
+ *,
+ patterns: Optional[Iterable[str]] = None,
+ ledger: Optional[LinkLedger] = None,
+ occupancy: Optional[_OccupancyLedger] = None,
+) -> tuple[int, int]:
+ ledger = LinkLedger() if ledger is None else ledger
entries = 0
try:
if Path(root).is_symlink() or _is_junction(root) or not Path(root).is_dir():
@@ -797,11 +846,11 @@ def _measure_root(root: Path, *, patterns: Optional[Iterable[str]] = None) -> tu
if _descendable(entry):
subdirs.append(entry.path)
continue
- _record_entry(entry, ledger)
+ _record_entry(entry, ledger, occupancy)
except OSError as exc:
logger.debug(f"Could not size {root}: {exc}")
subdirs.reverse()
- _walk_into(subdirs, ledger)
+ _walk_into(subdirs, ledger, occupancy)
return ledger.freeable_bytes(), entries
@@ -831,6 +880,134 @@ def _resolve_roots(definition: CacheDefinition) -> list[Path]:
return roots
+def _measurement_roots(definition: CacheDefinition) -> list[Path]:
+ """Remembered HF locations count towards storage, but never widen a purge."""
+ roots = _resolve_roots(definition)
+ if definition.key == "hf_hub":
+ from utils.hf_cache_settings import known_hf_hub_caches
+ roots.extend(known_hf_hub_caches())
+ elif definition.key in {"hf_datasets", "hf_xet", "hf_assets"}:
+ child = definition.key.removeprefix("hf_")
+ roots.extend(home / child for home in _hf_homes())
+ unique: list[Path] = []
+ protected = protected_paths()
+ for root in roots:
+ resolved = _safe_resolve(root)
+ if resolved is None or resolved in unique:
+ continue
+ # Never walk a protected root itself, or a link into one.
+ try:
+ assert_purgeable_root(root, protected = protected, trees = set(), keep = {})
+ except CachePurgeRefused:
+ continue
+ if any(_is_within(resolved, previous) for previous in unique):
+ continue
+ unique = [previous for previous in unique if not _is_within(previous, resolved)]
+ unique.append(resolved)
+ return unique
+
+
+def _system_disk_device():
+ # The volume /api/system and models_disk_usage report, wherever Studio lives.
+ try:
+ return Path(os.path.abspath(os.sep)).stat().st_dev
+ except OSError:
+ return None
+
+
+def _system_disk_occupancy(occupancy: _OccupancyLedger) -> int:
+ from utils.system_disk import _SAME_POOL_SLACK
+
+ device = _system_disk_device()
+ total = occupancy.by_device.get(device, 0)
+ if device is None:
+ return 0
+ try:
+ system = shutil.disk_usage(os.path.abspath(os.sep))
+ except (OSError, ValueError):
+ return total
+ for other, size in occupancy.by_device.items():
+ if other == device:
+ continue
+ # As models_disk_usage: APFS Data / btrfs subvolumes share the pool under another st_dev.
+ try:
+ usage = shutil.disk_usage(occupancy.device_paths[other])
+ except (OSError, ValueError):
+ continue
+ if usage.total == system.total and abs(usage.free - system.free) < _SAME_POOL_SLACK:
+ total += size
+ return total
+
+
+def _model_cache_action(root: Path, entry: os.DirEntry) -> dict:
+ """An identity for the existing guarded Hub action, never a path-delete grant."""
+ refused = {"delete_allowed": False}
+ try:
+ if (
+ not entry.name.startswith("models--")
+ or entry.is_symlink()
+ or _is_junction(entry.path)
+ or not entry.is_dir(follow_symlinks = False)
+ ):
+ return refused
+ from hub.utils.paths import is_valid_repo_id
+ from hub.utils.hf_cache_state import scoped_delete_root
+
+ repo_id = entry.name[len("models--") :].replace("--", "/")
+ if not is_valid_repo_id(repo_id):
+ return refused
+ candidate = _safe_resolve(Path(entry.path))
+ if candidate is None or candidate.parent != root or candidate.name != entry.name:
+ return refused
+ # cache_path is the repo directory; the Hub delete re-validates its root.
+ if scoped_delete_root("model", repo_id, str(candidate)) != root:
+ return refused
+ return {
+ "repo_id": repo_id,
+ "repo_type": "model",
+ "cache_path": str(candidate),
+ "delete_allowed": True,
+ }
+ except (ImportError, OSError, ValueError, RuntimeError):
+ return refused
+
+
+def cache_breakdown(key: str) -> dict:
+ """Read-only, on-demand HF directory breakdown; never accepts a browser path."""
+ if key not in {"hf_hub", "hf_datasets", "hf_xet", "hf_assets"}:
+ raise ValueError("Only Hugging Face caches have a directory breakdown.")
+ rows = []
+ occupancy = _OccupancyLedger()
+ for root in _measurement_roots(definition_for(key)):
+ try:
+ with os.scandir(root) as scan:
+ for entry in scan:
+ if entry.is_symlink() or _is_junction(entry.path):
+ continue
+ before = occupancy.bytes
+ if entry.is_dir(follow_symlinks = False):
+ _measure_root(Path(entry.path), occupancy = occupancy)
+ else:
+ info = (
+ os.stat(entry.path, follow_symlinks = False)
+ if os.name == "nt"
+ else entry.stat(follow_symlinks = False)
+ )
+ occupancy.add(info, entry.path)
+ size = occupancy.bytes - before
+ action = (
+ _model_cache_action(root, entry)
+ if key == "hf_hub"
+ else {"delete_allowed": False}
+ )
+ rows.append(
+ {"name": entry.name, "path": entry.path, "size_bytes": size, **action}
+ )
+ except OSError:
+ continue
+ return {"entries": sorted(rows, key = lambda row: (-row["size_bytes"], row["path"]))}
+
+
def describe_cache(definition: CacheDefinition) -> dict:
"""Size one cache and say whether it may be purged, without deleting."""
patterns = _patterns_for(definition)
@@ -862,23 +1039,53 @@ def describe_cache(definition: CacheDefinition) -> dict:
blocked_reason = _link_mode_refusal(definition.key)
if blocked_reason is not None:
purgeable = False
- if definition.custom_measure is not None:
- total, entries = (0, 0) if blocked_reason is not None else definition.custom_measure()
- else:
- total = 0
+ measured_paths = roots
+ system_disk_bytes = None
+ if definition.key in {"hf_hub", "hf_datasets", "hf_xet", "hf_assets"}:
+ # Occupancy is measured even where clearing is refused (e.g. under Documents).
+ measured_paths = _measurement_roots(definition)
entries = 0
- for root in measurable:
- size, count = _measure_root(root, patterns = patterns)
- total += size
+ clear_entries = 0
+ occupancy = _OccupancyLedger()
+ clear_ledger = LinkLedger()
+ clear_roots = {_safe_resolve(root) for root in measurable} if purgeable else set()
+ for root in measured_paths:
+ clearable = _safe_resolve(root) in clear_roots
+ _, count = _measure_root(
+ root,
+ patterns = patterns,
+ occupancy = occupancy,
+ ledger = clear_ledger if clearable else None,
+ )
entries += count
+ if clearable:
+ clear_entries += count
+ total = occupancy.bytes
+ clear_size = clear_ledger.freeable_bytes()
+ system_disk_bytes = _system_disk_occupancy(occupancy)
+ else:
+ if definition.custom_measure is not None:
+ total, entries = (0, 0) if blocked_reason is not None else definition.custom_measure()
+ else:
+ total = entries = 0
+ for root in measurable:
+ size, count = _measure_root(root, patterns = patterns)
+ total += size
+ entries += count
+ clear_size = total
+ clear_entries = entries
return {
"key": definition.key,
"group": definition.group,
"opt_in": definition.opt_in,
"paths": [str(root) for root in roots],
+ "measured_paths": [str(root) for root in measured_paths],
+ "clear_size_bytes": clear_size,
+ "clear_entry_count": clear_entries,
+ "system_disk_bytes": system_disk_bytes,
"size_bytes": total,
"entry_count": entries,
- "present": bool(roots),
+ "present": bool(roots or measured_paths),
"purgeable": bool(roots) and purgeable,
"blocked_reason": blocked_reason,
}
@@ -1001,7 +1208,7 @@ def cache_inventory(*, refresh: bool = False) -> dict:
_refresh_in_background(definition)
total = sum(entry["size_bytes"] for entry in entries if entry["present"])
reclaimable = sum(
- entry["size_bytes"]
+ entry.get("clear_size_bytes", entry["size_bytes"])
for entry in entries
if entry["present"] and entry["purgeable"] and not entry["opt_in"]
)
diff --git a/studio/frontend/src/features/settings/api/caches.ts b/studio/frontend/src/features/settings/api/caches.ts
index 0db2967e171..08ca51835a4 100644
--- a/studio/frontend/src/features/settings/api/caches.ts
+++ b/studio/frontend/src/features/settings/api/caches.ts
@@ -32,6 +32,10 @@ export type CacheEntry = {
group: CacheGroup;
optIn: boolean;
paths: string[];
+ measuredPaths?: string[];
+ clearSizeBytes?: number | null;
+ clearEntryCount?: number | null;
+ systemDiskBytes?: number | null;
sizeBytes: number;
entryCount: number;
present: boolean;
@@ -67,6 +71,14 @@ type ApiCacheEntry = {
opt_in: boolean;
paths: string[];
// biome-ignore lint/style/useNamingConvention: API schema
+ measured_paths?: string[];
+ // biome-ignore lint/style/useNamingConvention: API schema
+ clear_size_bytes?: number | null;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ clear_entry_count?: number | null;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ system_disk_bytes?: number | null;
+ // biome-ignore lint/style/useNamingConvention: API schema
size_bytes: number;
// biome-ignore lint/style/useNamingConvention: API schema
entry_count: number;
@@ -110,6 +122,10 @@ function entryFromApi(value: ApiCacheEntry): CacheEntry {
group: value.group,
optIn: value.opt_in,
paths: value.paths,
+ measuredPaths: value.measured_paths,
+ clearSizeBytes: value.clear_size_bytes,
+ clearEntryCount: value.clear_entry_count,
+ systemDiskBytes: value.system_disk_bytes,
sizeBytes: value.size_bytes,
entryCount: value.entry_count,
present: value.present,
@@ -160,6 +176,48 @@ export async function loadCacheInventory(
return inventoryFromApi(await response.json());
}
+export type CacheBreakdownEntry = {
+ name: string;
+ path: string;
+ sizeBytes: number;
+ repoId?: string;
+ repoType?: "model";
+ cachePath?: string;
+ deleteAllowed?: boolean;
+};
+
+export async function loadCacheBreakdown(
+ key: CacheKey,
+): Promise<CacheBreakdownEntry[]> {
+ const response = await authFetch(`/api/settings/caches/${key}/breakdown`);
+ if (!response.ok) {
+ throw new Error(
+ await readFastApiError(response, "Failed to measure cache folders"),
+ );
+ }
+ const result = (await response.json()) as {
+ entries: {
+ name: string;
+ path: string;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ size_bytes: number;
+ repo_id?: string;
+ repo_type?: "model";
+ cache_path?: string;
+ delete_allowed?: boolean;
+ }[];
+ };
+ return result.entries.map((entry) => ({
+ name: entry.name,
+ path: entry.path,
+ sizeBytes: entry.size_bytes,
+ repoId: entry.repo_id,
+ repoType: entry.repo_type,
+ cachePath: entry.cache_path,
+ deleteAllowed: entry.delete_allowed === true,
+ }));
+}
+
export async function purgeCaches(
keys: readonly CacheKey[],
): Promise<CachePurgeOutcome> {
@@ -184,7 +242,7 @@ export function bulkPurgeKeys(inventory: CacheInventory): CacheKey[] {
entry.present &&
entry.purgeable &&
!entry.optIn &&
- entry.entryCount > 0,
+ (entry.clearEntryCount ?? entry.entryCount) > 0,
)
.map((entry) => entry.key);
}
diff --git a/studio/frontend/src/features/settings/components/cache-storage-rows.tsx b/studio/frontend/src/features/settings/components/cache-storage-rows.tsx
index 9a5d307a24b..26a91f0b5a0 100644
--- a/studio/frontend/src/features/settings/components/cache-storage-rows.tsx
+++ b/studio/frontend/src/features/settings/components/cache-storage-rows.tsx
@@ -21,14 +21,17 @@ import { Delete02Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { useCallback, useEffect, useRef, useState } from "react";
import {
+ type CacheBreakdownEntry,
type CacheEntry,
type CacheInventory,
type CacheKey,
bulkPurgeKeys,
+ loadCacheBreakdown,
loadCacheInventory,
purgeCaches,
} from "../api/caches";
import { SettingsCardRow } from "./storage-overview";
+import { HfCacheModelClear } from "./hf-cache-model-clear";
/** Decimal units, matching the Storage section's disk readings. */
export function formatCacheSize(bytes: number): string {
@@ -90,9 +93,15 @@ export function singleClearDescriptionKeys(key: CacheKey): TranslationKey[] {
return cost ? [cost, ...spared] : spared;
}
-function presentCaches(inventory: CacheInventory | null): CacheEntry[] {
+export function presentCaches(inventory: CacheInventory | null): CacheEntry[] {
if (!inventory) return [];
- return inventory.caches.filter((entry) => entry.present);
+ return inventory.caches
+ .filter((entry) => entry.present)
+ .sort(
+ (first, second) =>
+ second.sizeBytes - first.sizeBytes ||
+ first.key.localeCompare(second.key),
+ );
}
export function useCacheStorage() {
@@ -193,6 +202,104 @@ export function useCacheStorage() {
export type CacheStorage = ReturnType<typeof useCacheStorage>;
+const HF_REPO_PREFIX = /^(models|datasets|spaces)--/;
+
+export function HuggingFaceCacheFolders({
+ entry,
+ version,
+ disabled = false,
+}: { entry: CacheEntry; version: CacheInventory | null; disabled?: boolean }) {
+ const t = useT();
+ const [open, setOpen] = useState(false);
+ const [rows, setRows] = useState<CacheBreakdownEntry[] | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ useEffect(() => {
+ if (!open) {
+ return;
+ }
+ let current = true;
+ setRows(null);
+ setError(null);
+ void loadCacheBreakdown(entry.key).then(
+ (next) => {
+ if (current) {
+ setRows(
+ next.filter((row) => row.sizeBytes > 0 || row.deleteAllowed),
+ );
+ }
+ },
+ (reason) => {
+ if (current) {
+ setError(reason instanceof Error ? reason.message : String(reason));
+ }
+ },
+ );
+ return () => {
+ current = false;
+ };
+ }, [open, entry.key, version]);
+ return (
+ <div className="mt-1 min-w-0">
+ <Button
+ variant="ghost"
+ size="xs"
+ aria-expanded={open}
+ onClick={() => setOpen((value) => !value)}
+ >
+ {t(
+ open
+ ? "settings.resources.storage.caches.hideFolders"
+ : "settings.resources.storage.caches.showFolders",
+ )}
+ </Button>
+ {open ? (
+ <div
+ className="mt-1 flex flex-col gap-1 text-xs text-muted-foreground"
+ aria-live="polite"
+ >
+ {error ? (
+ <span role="alert">{error}</span>
+ ) : rows === null ? (
+ t("settings.resources.storage.caches.measuring")
+ ) : rows.length === 0 ? (
+ t("settings.resources.storage.caches.empty")
+ ) : (
+ rows.map((row) => (
+ <div
+ key={row.path}
+ title={row.path}
+ className="flex min-w-0 justify-between gap-4"
+ >
+ <span className="truncate font-mono">
+ {row.repoId ??
+ row.name.replace(HF_REPO_PREFIX, "").replaceAll("--", "/")}
+ </span>
+ <div className="flex shrink-0 items-center gap-2">
+ <span className="tabular-nums">
+ {formatCacheSize(row.sizeBytes)}
+ </span>
+ <span className="w-12">
+ {row.deleteAllowed &&
+ row.repoType === "model" &&
+ row.repoId &&
+ row.cachePath ? (
+ <HfCacheModelClear
+ repoId={row.repoId}
+ cachePath={row.cachePath}
+ disabled={disabled}
+ />
+ ) : null}
+ </span>
+ </div>
+ </div>
+ ))
+ )}
+ </div>
+ ) : null}
+ </div>
+ );
+}
+
export function CacheStorageRows({ cache }: { cache: CacheStorage }) {
const t = useT();
const {
@@ -276,15 +383,15 @@ export function CacheStorageRows({ cache }: { cache: CacheStorage }) {
key={entry.key}
className="flex flex-wrap items-start justify-between gap-2 border-t border-border/60 py-2.5"
>
- <div className="flex min-w-0 flex-col gap-0.5">
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">
<span className="text-sm text-foreground">
{t(CACHE_NAME_KEYS[entry.key])}
</span>
<span
- title={entry.paths.join("\n")}
+ title={(entry.measuredPaths ?? entry.paths).join("\n")}
className="max-w-lg truncate font-mono text-ui-11 text-muted-foreground"
>
- {entry.paths[0] ?? ""}
+ {(entry.measuredPaths ?? entry.paths)[0] ?? ""}
</span>
{entry.optIn && OPT_IN_COST_KEYS[entry.key] ? (
<span className="text-xs text-amber-600 dark:text-amber-400">
@@ -298,8 +405,15 @@ export function CacheStorageRows({ cache }: { cache: CacheStorage }) {
})}
</span>
) : null}
+ {entry.measuredPaths?.some(
+ (path) => !entry.paths.includes(path),
+ ) ? (
+ <span className="text-xs text-muted-foreground">
+ {t("settings.resources.storage.caches.previousLocations")}
+ </span>
+ ) : null}
</div>
- <div data-title-line-control={true} className="flex gap-3">
+ <div data-title-line-control={true} className="flex shrink-0 gap-3">
<span className="text-xs tabular-nums text-muted-foreground">
{formatCacheSize(entry.sizeBytes)}
</span>
@@ -311,7 +425,7 @@ export function CacheStorageRows({ cache }: { cache: CacheStorage }) {
clearing ||
loadError !== null ||
!entry.purgeable ||
- entry.entryCount === 0
+ (entry.clearEntryCount ?? entry.entryCount) === 0
}
onClick={() =>
entry.optIn
@@ -322,6 +436,16 @@ export function CacheStorageRows({ cache }: { cache: CacheStorage }) {
{t("settings.resources.storage.caches.clearOneAction")}
</Button>
</div>
+ {/* Own line: inside the title column it widens it and wraps the controls below. */}
+ {entry.key === "hf_hub" || entry.key === "hf_datasets" ? (
+ <div className="min-w-0 basis-full">
+ <HuggingFaceCacheFolders
+ entry={entry}
+ version={inventory}
+ disabled={loading || clearing}
+ />
+ </div>
+ ) : null}
</div>
))
)}
diff --git a/studio/frontend/src/features/settings/components/hf-cache-model-clear.tsx b/studio/frontend/src/features/settings/components/hf-cache-model-clear.tsx
new file mode 100644
index 00000000000..093d689a5aa
--- /dev/null
+++ b/studio/frontend/src/features/settings/components/hf-cache-model-clear.tsx
@@ -0,0 +1,87 @@
+// 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 { useState } from "react";
+import { Button } from "@/components/ui/button";
+import {
+ DeleteImpactSummary,
+ useDeleteImpact,
+} from "@/features/hub/catalog/delete-impact";
+import { DeleteConfirmDialog } from "@/features/hub/catalog/download-card";
+import { deleteCachedModel } from "@/features/hub/inventory";
+import { useHfTokenStore } from "@/features/hub/stores/hf-token-store";
+import { useT } from "@/i18n";
+import { toast } from "@/lib/toast";
+
+/** Share the Hub's exact-copy deletion, dependency checks and inventory events. */
+export function HfCacheModelClear({
+ repoId,
+ cachePath,
+ disabled = false,
+}: {
+ repoId: string;
+ cachePath: string;
+ disabled?: boolean;
+}) {
+ const t = useT();
+ const [open, setOpen] = useState(false);
+ const [deleting, setDeleting] = useState(false);
+ const hfToken = useHfTokenStore((state) => state.token);
+ const impact = useDeleteImpact(open, repoId, null, cachePath);
+ const clear = async () => {
+ if (deleting || disabled || (impact?.blocked_by.length ?? 0) > 0) return;
+ setDeleting(true);
+ try {
+ await deleteCachedModel(
+ repoId,
+ undefined,
+ hfToken || undefined,
+ cachePath,
+ );
+ setOpen(false);
+ } catch (error) {
+ toast.error(t("settings.resources.storage.caches.clearFailed"), {
+ description: error instanceof Error ? error.message : String(error),
+ });
+ } finally {
+ setDeleting(false);
+ }
+ };
+ return (
+ <>
+ <Button
+ variant="ghost"
+ size="xs"
+ disabled={disabled || deleting}
+ aria-label={t("settings.resources.storage.caches.confirmOneTitle", {
+ name: repoId,
+ })}
+ title={cachePath}
+ onClick={() => setOpen(true)}
+ >
+ {t("settings.resources.storage.caches.clearOneAction")}
+ </Button>
+ <DeleteConfirmDialog
+ open={open}
+ onOpenChange={(next) => {
+ if (!deleting) setOpen(next);
+ }}
+ title={t("settings.resources.storage.caches.confirmOneTitle", {
+ name: repoId,
+ })}
+ description={
+ <>
+ {t("settings.resources.storage.caches.clearModelDescription")}
+ <span className="mt-2 block break-all font-mono text-ui-11">
+ {cachePath}
+ </span>
+ <DeleteImpactSummary impact={impact} />
+ </>
+ }
+ deleting={deleting}
+ blocked={disabled || (impact?.blocked_by.length ?? 0) > 0}
+ onConfirm={() => void clear()}
+ />
+ </>
+ );
+}
diff --git a/studio/frontend/src/features/settings/tabs/resources-tab.tsx b/studio/frontend/src/features/settings/tabs/resources-tab.tsx
index ae2b4677adc..aca27be92a1 100644
--- a/studio/frontend/src/features/settings/tabs/resources-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/resources-tab.tsx
@@ -564,13 +564,17 @@ export function ResourcesTab() {
!(metrics.modelsDisk && entry.key === "hf_hub") &&
onSystemDisk(entry.paths),
);
+ const diskBytes = (entry: (typeof cache.entries)[number]) =>
+ entry.systemDiskBytes ??
+ (systemEntries.includes(entry) ? entry.sizeBytes : 0);
const modelsDiskGb =
- (systemEntries.find((entry) => entry.key === "hf_hub")?.sizeBytes ?? 0) /
- 1e9;
+ cache.entries
+ .filter((entry) => entry.key === "hf_hub")
+ .reduce((sum, entry) => sum + diskBytes(entry), 0) / 1e9;
const cachesDiskGb =
- systemEntries
+ cache.entries
.filter((entry) => entry.key !== "hf_hub")
- .reduce((sum, entry) => sum + entry.sizeBytes, 0) / 1e9;
+ .reduce((sum, entry) => sum + diskBytes(entry), 0) / 1e9;
const otherDiskGb = Math.max(
0,
metrics.diskUsed - modelsDiskGb - cachesDiskGb,
@@ -578,7 +582,7 @@ export function ResourcesTab() {
const cacheValue = (diskGb: number) =>
cache.inventory ? formatDiskSize(diskGb) : t("common.loading");
const storageSegments: StorageSegment[] = [
- ...(metrics.modelsDisk
+ ...(metrics.modelsDisk && modelsDiskGb === 0
? []
: [
{
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index da343bb4aed..efee8b84ad4 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -2507,6 +2507,10 @@ export const ar = {
hideDetailsAction: "إخفاء التفاصيل",
clearAction: "مسح ذاكرات التخزين المؤقت",
clearOneAction: "مسح",
+ showFolders: "إظهار المجلدات",
+ hideFolders: "إخفاء المجلدات",
+ previousLocations: "يشمل المواقع السابقة. يؤثر زر المسح الرئيسي على مجلد ذاكرة التخزين المؤقت الحالي. تمسح أزرار النماذج النسخة المحددة فقط.",
+ clearModelDescription: "يؤدي هذا إلى إزالة هذه النسخة المخزنة مؤقتًا فقط. سيتم تنزيلها مرة أخرى عند الحاجة.",
clearingAction: "جارٍ المسح...",
confirmTitle: "هل تريد مسح الملفات المخزّنة مؤقتًا؟",
confirmDescription: "سيؤدي ذلك إلى تحرير نحو {size}.",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 5e28fd7db27..54796bdf5d7 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -2551,6 +2551,10 @@ export const de = {
hideDetailsAction: "Details ausblenden",
clearAction: "Caches leeren",
clearOneAction: "Leeren",
+ showFolders: "Ordner anzeigen",
+ hideFolders: "Ordner ausblenden",
+ previousLocations: "Enthält frühere Speicherorte. Die Hauptschaltfläche Leeren betrifft den aktuellen Cache-Ordner. Modellschaltflächen leeren nur die ausgewählte Kopie.",
+ clearModelDescription: "Damit wird nur diese zwischengespeicherte Kopie entfernt. Sie wird bei Bedarf erneut heruntergeladen.",
clearingAction: "Wird geleert...",
confirmTitle: "Zwischengespeicherte Dateien leeren?",
confirmDescription: "Das gibt etwa {size} frei.",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 6702922a883..2cc4fd70ed8 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -2581,6 +2581,10 @@ export const en = {
detailsAction: "Details",
recheckAction: "Recheck",
hideDetailsAction: "Hide details",
+ showFolders: "Show folders",
+ hideFolders: "Hide folders",
+ previousLocations: "Includes previous locations. The main Clear button affects the current cache folder. Model buttons clear only the selected copy.",
+ clearModelDescription: "This removes only this cached copy. It will be downloaded again when needed.",
clearAction: "Clear caches",
clearOneAction: "Clear",
clearingAction: "Clearing...",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index a9a885a8c22..b6bb6835897 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -2534,6 +2534,10 @@ export const es = {
hideDetailsAction: "Ocultar detalles",
clearAction: "Borrar cachés",
clearOneAction: "Borrar",
+ showFolders: "Mostrar carpetas",
+ hideFolders: "Ocultar carpetas",
+ previousLocations: "Incluye ubicaciones anteriores. El botón Borrar principal afecta a la carpeta de caché actual. Los botones de modelo borran solo la copia seleccionada.",
+ clearModelDescription: "Esto elimina solo esta copia en caché. Se volverá a descargar cuando sea necesario.",
clearingAction: "Borrando...",
confirmTitle: "¿Borrar los archivos en caché?",
confirmDescription: "Esto libera unos {size}.",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 145e4ab1d66..67ceddfd9b6 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -2538,6 +2538,10 @@ export const fr = {
hideDetailsAction: "Masquer les détails",
clearAction: "Vider les caches",
clearOneAction: "Vider",
+ showFolders: "Afficher les dossiers",
+ hideFolders: "Masquer les dossiers",
+ previousLocations: "Inclut les emplacements précédents. Le bouton Vider principal concerne le dossier de cache actuel. Les boutons de modèle ne vident que la copie sélectionnée.",
+ clearModelDescription: "Cela supprime uniquement cette copie en cache. Elle sera téléchargée à nouveau si nécessaire.",
clearingAction: "Vidage en cours...",
confirmTitle: "Vider les fichiers en cache ?",
confirmDescription: "Cela libère environ {size}.",
diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.ts
index ad4573246d9..23bde6dda92 100644
--- a/studio/frontend/src/i18n/locales/he.ts
+++ b/studio/frontend/src/i18n/locales/he.ts
@@ -2637,6 +2637,10 @@ export const he = {
hideDetailsAction: "הסתר פרטים",
clearAction: "נקה מטמונים",
clearOneAction: "ניקוי",
+ showFolders: "הצגת תיקיות",
+ hideFolders: "הסתרת תיקיות",
+ previousLocations: "כולל מיקומים קודמים. לחצן הניקוי הראשי משפיע על תיקיית המטמון הנוכחית. לחצני המודלים מנקים רק את העותק שנבחר.",
+ clearModelDescription: "פעולה זו מסירה רק את העותק השמור הזה. הוא יורד שוב בעת הצורך.",
clearingAction: "מנקה...",
confirmTitle: "לנקות את הקבצים השמורים במטמון?",
confirmDescription: "פעולה זו תפנה כ-{size}.",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index a7a555ffd56..73f26b8e38d 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -2513,6 +2513,10 @@ export const hi = {
hideDetailsAction: "विवरण छिपाएँ",
clearAction: "कैश साफ़ करें",
clearOneAction: "साफ़ करें",
+ showFolders: "फ़ोल्डर दिखाएँ",
+ hideFolders: "फ़ोल्डर छिपाएँ",
+ previousLocations: "इसमें पिछले स्थान शामिल हैं। मुख्य साफ़ करें बटन मौजूदा कैश फ़ोल्डर पर लागू होता है। मॉडल बटन केवल चुनी गई कॉपी साफ़ करते हैं।",
+ clearModelDescription: "यह केवल इस कैश की गई कॉपी को हटाता है। ज़रूरत पड़ने पर इसे फिर से डाउनलोड किया जाएगा।",
clearingAction: "साफ़ किया जा रहा है...",
confirmTitle: "कैश की गई फ़ाइलें साफ़ करें?",
confirmDescription: "इससे लगभग {size} खाली होगा।",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 75f0358150e..a11e76bbed2 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -2454,6 +2454,10 @@ export const it = {
hideDetailsAction: "Nascondi dettagli",
clearAction: "Svuota le cache",
clearOneAction: "Svuota",
+ showFolders: "Mostra cartelle",
+ hideFolders: "Nascondi cartelle",
+ previousLocations: "Include le posizioni precedenti. Il pulsante Svuota principale riguarda la cartella cache attuale. I pulsanti dei modelli svuotano solo la copia selezionata.",
+ clearModelDescription: "Rimuove solo questa copia nella cache. Verrà scaricata di nuovo quando servirà.",
clearingAction: "Svuotamento in corso...",
confirmTitle: "Svuotare i file nella cache?",
confirmDescription: "Libera circa {size}.",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index b1a85c904c1..04826f50e32 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -2489,6 +2489,10 @@ export const ja = {
hideDetailsAction: "詳細を隠す",
clearAction: "キャッシュを削除",
clearOneAction: "削除",
+ showFolders: "フォルダを表示",
+ hideFolders: "フォルダを非表示",
+ previousLocations: "以前の場所も含みます。メインの削除ボタンは現在のキャッシュフォルダが対象です。モデルのボタンは選択したコピーのみを削除します。",
+ clearModelDescription: "このキャッシュ済みコピーのみを削除します。必要になったときに再度ダウンロードされます。",
clearingAction: "削除しています...",
confirmTitle: "キャッシュファイルを削除しますか?",
confirmDescription: "約{size}の空き容量ができます。",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 6861872f976..eada14ae25c 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -2501,6 +2501,10 @@ export const ko = {
hideDetailsAction: "자세히 숨기기",
clearAction: "캐시 정리",
clearOneAction: "정리",
+ showFolders: "폴더 표시",
+ hideFolders: "폴더 숨기기",
+ previousLocations: "이전 위치를 포함합니다. 기본 정리 버튼은 현재 캐시 폴더에 적용됩니다. 모델 버튼은 선택한 사본만 정리합니다.",
+ clearModelDescription: "이 캐시된 사본만 제거합니다. 필요할 때 다시 다운로드됩니다.",
clearingAction: "정리하는 중...",
confirmTitle: "캐시 파일을 정리할까요?",
confirmDescription: "약 {size}의 공간이 확보됩니다.",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 877a13539ef..44ca54b788f 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -2522,6 +2522,10 @@ export const ptBR = {
hideDetailsAction: "Ocultar detalhes",
clearAction: "Limpar caches",
clearOneAction: "Limpar",
+ showFolders: "Mostrar pastas",
+ hideFolders: "Ocultar pastas",
+ previousLocations: "Inclui locais anteriores. O botão Limpar principal afeta a pasta de cache atual. Os botões de modelo limpam apenas a cópia selecionada.",
+ clearModelDescription: "Isso remove apenas esta cópia em cache. Ela será baixada novamente quando necessário.",
clearingAction: "Limpando...",
confirmTitle: "Limpar os arquivos em cache?",
confirmDescription: "Isso libera cerca de {size}.",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 84a574f2efb..9225e73d965 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -2519,6 +2519,10 @@ export const ru = {
hideDetailsAction: "Скрыть подробности",
clearAction: "Очистить кеши",
clearOneAction: "Очистить",
+ showFolders: "Показать папки",
+ hideFolders: "Скрыть папки",
+ previousLocations: "Включает прежние расположения. Основная кнопка «Очистить» затрагивает текущую папку кэша. Кнопки моделей очищают только выбранную копию.",
+ clearModelDescription: "Будет удалена только эта копия в кэше. При необходимости она будет загружена снова.",
clearingAction: "Очистка...",
confirmTitle: "Очистить кешированные файлы?",
confirmDescription: "Это освободит примерно {size}.",
diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.ts
index 6dedb68e156..1c9ac14d7e4 100644
--- a/studio/frontend/src/i18n/locales/sv.ts
+++ b/studio/frontend/src/i18n/locales/sv.ts
@@ -2716,6 +2716,10 @@ export const sv = {
hideDetailsAction: "Dölj detaljer",
clearAction: "Rensa cacheminnen",
clearOneAction: "Rensa",
+ showFolders: "Visa mappar",
+ hideFolders: "Dölj mappar",
+ previousLocations: "Inkluderar tidigare platser. Huvudknappen Rensa påverkar den aktuella cachemappen. Modellknapparna rensar bara den valda kopian.",
+ clearModelDescription: "Detta tar bara bort den här cachade kopian. Den laddas ned igen vid behov.",
clearingAction: "Rensar...",
confirmTitle: "Rensa cachade filer?",
confirmDescription: "Detta frigör ungefär {size}.",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 58665094a70..82280b19733 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -2474,6 +2474,10 @@ export const zhCN = {
hideDetailsAction: "隐藏详情",
clearAction: "清理缓存",
clearOneAction: "清理",
+ showFolders: "显示文件夹",
+ hideFolders: "隐藏文件夹",
+ previousLocations: "包含以前的位置。主清理按钮作用于当前缓存文件夹。模型按钮仅清理所选副本。",
+ clearModelDescription: "这只会删除此缓存副本。需要时会重新下载。",
clearingAction: "正在清理...",
confirmTitle: "要清理缓存文件吗?",
confirmDescription: "这将释放约{size}。",
diff --git a/studio/frontend/tests/cache-folder-breakdown.test.ts b/studio/frontend/tests/cache-folder-breakdown.test.ts
new file mode 100644
index 00000000000..44586ac45aa
--- /dev/null
+++ b/studio/frontend/tests/cache-folder-breakdown.test.ts
@@ -0,0 +1,210 @@
+// 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 test from "node:test";
+import { loadWithStubs, stubJsxRuntime } from "./helpers/module-stubs.ts";
+import type { StubElement } from "./helpers/module-stubs.ts";
+
+function elements(node: unknown): StubElement[] {
+ if (Array.isArray(node)) return node.flatMap(elements);
+ if (!node || typeof node !== "object" || !("type" in node)) return [];
+ const element = node as StubElement;
+ return [element, ...elements(element.props.children)];
+}
+
+test("only verified model-copy rows expose Clear and retain individual locations", async () => {
+ const state: unknown[] = [];
+ let cursor = 0;
+ let effect: (() => void) | undefined;
+ let deps: unknown[] = [];
+ const good = {
+ name: "models--Org--Model",
+ sizeBytes: 100,
+ repoId: "Org/Model",
+ repoType: "model",
+ deleteAllowed: true,
+ };
+ const copies = [
+ {
+ ...good,
+ path: "/one/models--Org--Model",
+ cachePath: "/one/models--Org--Model",
+ },
+ {
+ ...good,
+ path: "/two/models--Org--Model",
+ cachePath: "/two/models--Org--Model",
+ },
+ {
+ ...good,
+ path: "/forbidden",
+ cachePath: "/forbidden",
+ deleteAllowed: false,
+ },
+ { ...good, path: "/dataset", cachePath: "/dataset", repoType: "dataset" },
+ { ...good, path: "/missing-copy" },
+ { name: ".locks", path: "/locks", sizeBytes: 1 },
+ { name: ".locks", path: "/empty-locks", sizeBytes: 0 },
+ ];
+ const component = loadWithStubs<{
+ HuggingFaceCacheFolders: (props: unknown) => unknown;
+ }>(
+ new URL(
+ "../src/features/settings/components/cache-storage-rows.tsx",
+ import.meta.url,
+ ),
+ {
+ react: {
+ useState: (initial: unknown) => {
+ const index = cursor++;
+ if (!(index in state)) state[index] = initial;
+ return [
+ state[index],
+ (next: unknown) => {
+ state[index] =
+ typeof next === "function" ? next(state[index]) : next;
+ },
+ ];
+ },
+ useEffect: (next: () => void, values: unknown[]) => {
+ if (values.some((value, index) => value !== deps[index])) {
+ deps = values;
+ effect = next;
+ }
+ },
+ },
+ "react/jsx-runtime": stubJsxRuntime(),
+ "@/components/ui/button": { Button: "Button" },
+ "@/components/ui/dialog": {},
+ "@/features/hub/stores/inventory-events": {},
+ "@/i18n": { useT: () => (key: string) => key },
+ "@/lib/toast": {},
+ "@hugeicons/core-free-icons": {},
+ "@hugeicons/react": {},
+ "../api/caches": { loadCacheBreakdown: async () => copies },
+ "./hf-cache-model-clear": { HfCacheModelClear: "HfCacheModelClear" },
+ "./storage-overview": {},
+ },
+ );
+ const version = {};
+ const render = () => {
+ cursor = 0;
+ const tree = component.HuggingFaceCacheFolders({
+ entry: { key: "hf_hub" },
+ version,
+ disabled: true,
+ });
+ const pending = effect;
+ effect = undefined;
+ pending?.();
+ return tree;
+ };
+ const trigger = elements(render()).find(
+ (element) => element.type === "Button",
+ )!;
+ (trigger.props.onClick as () => void)();
+ render();
+ await Promise.resolve();
+ const actions = elements(render()).filter(
+ (element) => element.type === "HfCacheModelClear",
+ );
+ const listed = elements(render())
+ .map((element) => element.props.title)
+ .filter((title) => typeof title === "string");
+ assert.ok(listed.includes("/locks"));
+ assert.ok(!listed.includes("/empty-locks"));
+ assert.deepEqual(
+ actions.map((action) => action.props),
+ [
+ {
+ repoId: "Org/Model",
+ cachePath: "/one/models--Org--Model",
+ disabled: true,
+ },
+ {
+ repoId: "Org/Model",
+ cachePath: "/two/models--Org--Model",
+ disabled: true,
+ },
+ ],
+ );
+});
+
+test("HF folders are requested only on expansion and stale walks cannot replace a refreshed result", async () => {
+ const state: unknown[] = [];
+ let cursor = 0;
+ let effect: (() => (() => void) | void) | undefined;
+ let previousDeps: unknown[] = [];
+ let cleanup: (() => void) | void;
+ const requests: ((rows: unknown[]) => void)[] = [];
+ const rows = loadWithStubs<{
+ HuggingFaceCacheFolders: (props: unknown) => unknown;
+ }>(
+ new URL(
+ "../src/features/settings/components/cache-storage-rows.tsx",
+ import.meta.url,
+ ),
+ {
+ react: {
+ useState: (initial: unknown) => {
+ const index = cursor++;
+ if (!(index in state)) state[index] = initial;
+ return [
+ state[index],
+ (next: unknown) => {
+ state[index] =
+ typeof next === "function" ? next(state[index]) : next;
+ },
+ ];
+ },
+ useEffect: (next: typeof effect, deps: unknown[]) => {
+ if (deps.some((value, index) => value !== previousDeps[index])) {
+ cleanup?.();
+ previousDeps = deps;
+ effect = next;
+ }
+ },
+ },
+ "react/jsx-runtime": stubJsxRuntime(),
+ "@/components/ui/button": { Button: "Button" },
+ "@/components/ui/dialog": {},
+ "@/features/hub/stores/inventory-events": {},
+ "@/i18n": { useT: () => (key: string) => key },
+ "@/lib/toast": {},
+ "@hugeicons/core-free-icons": {},
+ "@hugeicons/react": {},
+ "../api/caches": {
+ loadCacheBreakdown: () =>
+ new Promise((resolve) => requests.push(resolve)),
+ },
+ "./hf-cache-model-clear": { HfCacheModelClear: "HfCacheModelClear" },
+ "./storage-overview": {},
+ },
+ );
+ function render(version: unknown) {
+ cursor = 0;
+ const tree = rows.HuggingFaceCacheFolders({
+ entry: { key: "hf_hub" },
+ version,
+ }) as { props: { children: { props: { onClick: () => void } }[] } };
+ const pending = effect;
+ effect = undefined;
+ if (pending) cleanup = pending();
+ return tree;
+ }
+ const first = {};
+ const tree = render(first);
+ assert.equal(requests.length, 0);
+ tree.props.children[0].props.onClick();
+ render(first);
+ assert.equal(requests.length, 1);
+ const refreshed = {};
+ render(refreshed);
+ assert.equal(requests.length, 2);
+ requests[1]([{ name: "models--new--repo", path: "/new", sizeBytes: 100 }]);
+ await Promise.resolve();
+ requests[0]([{ name: "stale", path: "/stale", sizeBytes: 999 }]);
+ await Promise.resolve();
+ assert.match(JSON.stringify(render(refreshed)), /new\/repo/);
+ assert.doesNotMatch(JSON.stringify(render(refreshed)), /stale/);
+});
diff --git a/studio/frontend/tests/cache-rows-model-folder.test.ts b/studio/frontend/tests/cache-rows-model-folder.test.ts
index 878fbec7e84..6233c875cef 100644
--- a/studio/frontend/tests/cache-rows-model-folder.test.ts
+++ b/studio/frontend/tests/cache-rows-model-folder.test.ts
@@ -15,6 +15,7 @@ const ROWS_URL = new URL(
type Rows = {
singleClearDescriptionKeys: (key: string) => string[];
+ presentCaches: (inventory: unknown) => { key: string; sizeBytes: number }[];
};
function loadRows(): Rows {
@@ -46,12 +47,37 @@ function loadRows(): Rows {
loadCacheInventory: async () => null,
purgeCaches: async () => null,
},
+ "./hf-cache-model-clear": { HfCacheModelClear: "HfCacheModelClear" },
"./storage-overview": { SettingsCardRow: noop },
});
}
const SAFETY = "settings.resources.storage.caches.safety";
+test("cache rows show largest occupancy first with deterministic ties and no input mutation", () => {
+ const { presentCaches } = loadRows();
+ const entries = Object.freeze([
+ Object.freeze({ key: "uv", sizeBytes: 20, present: true }),
+ Object.freeze({ key: "triton", sizeBytes: 500, present: true }),
+ Object.freeze({ key: "hf_hub", sizeBytes: 500, present: true }),
+ Object.freeze({ key: "pip", sizeBytes: 900, present: false }),
+ ]);
+ const result = presentCaches({ caches: entries });
+ assert.deepEqual(
+ result.map((row) => row.key),
+ ["hf_hub", "triton", "uv"],
+ );
+ assert.deepEqual(
+ entries.map((row) => row.key),
+ ["uv", "triton", "hf_hub", "pip"],
+ );
+ assert.deepEqual(
+ presentCaches({ caches: [...entries].reverse() }).map((row) => row.key),
+ result.map((row) => row.key),
+ );
+ assert.deepEqual(presentCaches(null), []);
+});
+
test("the model cache clear does not promise that models are untouched", () => {
assert.ok(
en.settings.resources.storage.caches.safety.includes("Downloaded models"),
@@ -167,6 +193,7 @@ function driveRows(options: {
loadCacheInventory: options.load,
purgeCaches: options.purge ?? (async () => ({})),
},
+ "./hf-cache-model-clear": { HfCacheModelClear: "HfCacheModelClear" },
"./storage-overview": { SettingsCardRow: "SettingsCardRow" },
});
diff --git a/studio/frontend/tests/hf-cache-model-clear.test.ts b/studio/frontend/tests/hf-cache-model-clear.test.ts
new file mode 100644
index 00000000000..b3a80434d90
--- /dev/null
+++ b/studio/frontend/tests/hf-cache-model-clear.test.ts
@@ -0,0 +1,246 @@
+// 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 test from "node:test";
+import {
+ loadWithStubs,
+ stubJsxRuntime,
+ type StubElement,
+} from "./helpers/module-stubs.ts";
+
+type ClearProps = { repoId: string; cachePath: string; disabled?: boolean };
+type Delete = (...args: unknown[]) => Promise<void>;
+
+function drive(
+ options: { path?: string; disabled?: boolean; remove?: Delete } = {},
+) {
+ const states: unknown[] = [];
+ let cursor = 0;
+ let blocked: string[] = [];
+ const calls: unknown[][] = [];
+ const previews: unknown[][] = [];
+ const errors: unknown[][] = [];
+ const component = loadWithStubs<{
+ HfCacheModelClear: (props: ClearProps) => StubElement;
+ }>(
+ new URL(
+ "../src/features/settings/components/hf-cache-model-clear.tsx",
+ import.meta.url,
+ ),
+ {
+ react: {
+ useState: (initial: unknown) => {
+ const index = cursor++;
+ if (!(index in states)) states[index] = initial;
+ return [
+ states[index],
+ (value: unknown) => {
+ states[index] = value;
+ },
+ ];
+ },
+ },
+ "react/jsx-runtime": stubJsxRuntime(),
+ "@/components/ui/button": { Button: "Button" },
+ "@/features/hub/catalog/delete-impact": {
+ DeleteImpactSummary: "DeleteImpactSummary",
+ useDeleteImpact: (...args: unknown[]) => {
+ previews.push(args);
+ return { blocked_by: blocked };
+ },
+ },
+ "@/features/hub/catalog/download-card": {
+ DeleteConfirmDialog: "DeleteConfirmDialog",
+ },
+ "@/features/hub/inventory": {
+ deleteCachedModel: async (...args: unknown[]) => {
+ calls.push(args);
+ await options.remove?.(...args);
+ },
+ },
+ "@/features/hub/stores/hf-token-store": {
+ useHfTokenStore: (select: (value: { token: string }) => string) =>
+ select({ token: "test-hf-token" }),
+ },
+ "@/i18n": { useT: () => (key: string) => key },
+ "@/lib/toast": {
+ toast: { error: (...args: unknown[]) => errors.push(args) },
+ },
+ },
+ );
+ return {
+ calls,
+ previews,
+ errors,
+ block: (models: string[]) => {
+ blocked = models;
+ },
+ render: () => {
+ cursor = 0;
+ const tree = component.HfCacheModelClear({
+ repoId: "Org/Model",
+ cachePath: options.path ?? "/cache/hub/models--Org--Model",
+ disabled: options.disabled,
+ });
+ const [button, dialog] = tree.props.children as StubElement[];
+ return {
+ button,
+ dialog,
+ open: () => (button.props.onClick as () => void)(),
+ confirm: () => (dialog.props.onConfirm as () => void)(),
+ close: () =>
+ (dialog.props.onOpenChange as (open: boolean) => void)(false),
+ };
+ },
+ };
+}
+
+const settle = async () => {
+ for (let i = 0; i < 8; i++) await Promise.resolve();
+};
+
+test("opening and cancelling a confirmation never deletes a model", () => {
+ const run = drive();
+ assert.equal(run.render().dialog.props.open, false);
+ run.render().open();
+ assert.equal(run.render().dialog.props.open, true);
+ run.render().close();
+ assert.equal(run.render().dialog.props.open, false);
+ assert.deepEqual(run.calls, []);
+});
+
+test("two copies of one repo retain their exact path in preview and deletion", async () => {
+ const current = drive({ path: "C:/models/hub/models--Org--Model" });
+ const historical = drive({ path: "D:/previous/hub/models--Org--Model" });
+ historical.render().open();
+ historical.render().confirm();
+ await settle();
+ assert.deepEqual(historical.previews.at(-1), [
+ true,
+ "Org/Model",
+ null,
+ "D:/previous/hub/models--Org--Model",
+ ]);
+ assert.deepEqual(historical.calls, [
+ [
+ "Org/Model",
+ undefined,
+ "test-hf-token",
+ "D:/previous/hub/models--Org--Model",
+ ],
+ ]);
+ assert.deepEqual(current.calls, []);
+ assert.equal(historical.render().dialog.props.open, false);
+});
+
+test("shared-asset impact blocks confirmation even if its handler is called", async () => {
+ const run = drive();
+ run.block(["Org/Dependent"]);
+ run.render().open();
+ assert.equal(run.render().dialog.props.blocked, true);
+ run.render().confirm();
+ await settle();
+ assert.deepEqual(run.calls, []);
+ assert.equal(run.render().dialog.props.open, true);
+});
+
+test("a refresh-disabled clear cannot issue a delete", async () => {
+ const run = drive({ disabled: true });
+ assert.equal(run.render().button.props.disabled, true);
+ run.render().confirm();
+ await settle();
+ assert.deepEqual(run.calls, []);
+});
+
+test("an in-flight delete stays open and cannot be submitted twice", async () => {
+ let finish!: () => void;
+ const run = drive({
+ remove: () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ });
+ run.render().open();
+ run.render().confirm();
+ assert.equal(run.render().dialog.props.deleting, true);
+ run.render().confirm();
+ run.render().close();
+ assert.equal(run.render().dialog.props.open, true);
+ assert.equal(run.calls.length, 1);
+ finish();
+ await settle();
+ assert.equal(run.render().dialog.props.open, false);
+ assert.equal(run.render().dialog.props.deleting, false);
+});
+
+test("a guarded server refusal keeps the selected-copy confirmation open", async () => {
+ const run = drive({
+ remove: async () => {
+ throw new Error("Unload the model before deleting");
+ },
+ });
+ run.render().open();
+ run.render().confirm();
+ await settle();
+ assert.equal(run.render().dialog.props.open, true);
+ assert.equal(run.render().dialog.props.deleting, false);
+ assert.equal(run.errors.length, 1);
+ assert.deepEqual(run.errors[0][1], {
+ description: "Unload the model before deleting",
+ });
+});
+
+test("successful model Clear uses the Hub API's normal inventory refresh and lifecycle events", async () => {
+ const requests: { url: string; init?: RequestInit }[] = [];
+ const events: string[] = [];
+ const hub = loadWithStubs<{ deleteCachedModel: Delete }>(
+ new URL("../src/features/hub/inventory/api.ts", import.meta.url),
+ {
+ "@/features/auth": {
+ authFetch: async (url: string, init?: RequestInit) => {
+ requests.push({ url, init });
+ return new Response(null, { status: 200 });
+ },
+ },
+ "@/features/hub/lib/abort-signals": {},
+ "@/features/hub/lib/hub-token-header": {
+ hubTokenHeader: () => ({ "X-HF-Token": "test-hf-token" }),
+ },
+ "@/lib/format-fastapi-error": {},
+ "@/features/hub/lib/local-path": {},
+ "@/features/hub/lib/network": {},
+ "@/features/hub/lib/token-fingerprint": {},
+ "@/features/hub/stores/inventory-events": {
+ bumpInventoryVersion: () => events.push("inventory"),
+ },
+ "@/lib/model-lifecycle-events": {
+ notifyModelDeleted: (repo: string) => events.push(`deleted:${repo}`),
+ },
+ "../download-manager/download-manager-state": {
+ discardDeletedModelInventoryHints: () => events.push("hints"),
+ },
+ "./gguf-variants-cache-events": {
+ bumpGgufVariantsCacheVersion: () => events.push("variants"),
+ },
+ },
+ );
+ const run = drive({ remove: hub.deleteCachedModel });
+ run.render().open();
+ run.render().confirm();
+ await settle();
+ assert.equal(requests.length, 1);
+ assert.equal(requests[0].url, "/api/hub/delete-cached");
+ assert.equal(requests[0].init?.method, "DELETE");
+ assert.deepEqual(JSON.parse(String(requests[0].init?.body)), {
+ repo_id: "Org/Model",
+ cache_path: "/cache/hub/models--Org--Model",
+ });
+ assert.deepEqual(events, [
+ "hints",
+ "inventory",
+ "deleted:Org/Model",
+ "variants",
+ ]);
+ assert.equal(run.render().dialog.props.open, false);
+});
diff --git a/studio/frontend/tests/settings-cache-purge.test.ts b/studio/frontend/tests/settings-cache-purge.test.ts
index 26c2ffc7038..7ebcb9c9c57 100644
--- a/studio/frontend/tests/settings-cache-purge.test.ts
+++ b/studio/frontend/tests/settings-cache-purge.test.ts
@@ -10,6 +10,15 @@ import test from "node:test";
import { loadWithStubs } from "./helpers/module-stubs.ts";
type CachesApi = {
+ loadCacheBreakdown: (key: string) => Promise<
+ {
+ path: string;
+ repoId?: string;
+ repoType?: string;
+ cachePath?: string;
+ deleteAllowed?: boolean;
+ }[]
+ >;
loadCacheInventory: () => Promise<unknown>;
purgeCaches: (keys: readonly string[]) => Promise<unknown>;
inventoryFromApi: (value: unknown) => {
@@ -53,6 +62,65 @@ function json(body: unknown): Response {
});
}
+test("breakdown preserves each model copy's action identity and requires an explicit permission boolean", async () => {
+ const first = "/active/hub/models--Org--Model";
+ const second = "/previous/hub/models--Org--Model";
+ const { api, requests } = loadApi(() =>
+ json({
+ entries: [
+ {
+ name: "models--Org--Model",
+ path: first,
+ size_bytes: 30,
+ repo_id: "Org/Model",
+ repo_type: "model",
+ cache_path: first,
+ delete_allowed: true,
+ },
+ {
+ name: "models--Org--Model",
+ path: second,
+ size_bytes: 50,
+ repo_id: "Org/Model",
+ repo_type: "model",
+ cache_path: second,
+ delete_allowed: true,
+ },
+ {
+ name: ".locks",
+ path: "/locks",
+ size_bytes: 1,
+ delete_allowed: false,
+ },
+ {
+ name: "unverified",
+ path: "/unverified",
+ size_bytes: 1,
+ delete_allowed: "true",
+ },
+ ],
+ }),
+ );
+ const rows = await api.loadCacheBreakdown("hf_hub");
+ assert.equal(requests[0].url, "/api/settings/caches/hf_hub/breakdown");
+ assert.deepEqual(
+ rows
+ .slice(0, 2)
+ .map((row) => [
+ row.repoId,
+ row.repoType,
+ row.cachePath,
+ row.deleteAllowed,
+ ]),
+ [
+ ["Org/Model", "model", first, true],
+ ["Org/Model", "model", second, true],
+ ],
+ );
+ assert.equal(rows[2].deleteAllowed, false);
+ assert.equal(rows[3].deleteAllowed, false);
+});
+
const apiEntry = (
key: string,
overrides: Record<string, unknown> = {},
@@ -180,3 +248,20 @@ test("a cache that measures zero bytes but holds entries is still cleared", () =
);
assert.deepEqual(api.bulkPurgeKeys(inventory), ["triton"]);
});
+
+test("historical cache occupancy never enables a clear of an empty active cache", () => {
+ const { api } = loadApi(() => json({}));
+ const inventory = api.inventoryFromApi(
+ apiInventory([
+ apiEntry("hf_xet", {
+ size_bytes: 10000,
+ entry_count: 100,
+ clear_size_bytes: 0,
+ clear_entry_count: 0,
+ measured_paths: ["/old/xet"],
+ system_disk_bytes: 10000,
+ }),
+ ]),
+ );
+ assert.deepEqual(api.bulkPurgeKeys(inventory), []);
+});